Skip to content

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

refactor(llm): make AI SDK the sole completion runtime (#14979)

Hassieb Pakzadbc9f3a40b296
diff --git a/.agents/skills/backend-dev-guidelines/references/architecture-overview.md b/.agents/skills/backend-dev-guidelines/references/architecture-overview.md
index 593935a0fa..f8d2967c11 100644
--- a/.agents/skills/backend-dev-guidelines/references/architecture-overview.md
+++ b/.agents/skills/backend-dev-guidelines/references/architecture-overview.md
@@ -349,7 +349,7 @@ import {
redis,
clickhouseClient,
StorageService,
- fetchLLMCompletion,
+ generateLLMText,
filterToPrisma,
} from "@langfuse/shared/src/server";
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml
index 7e38d74ea5..6e2120bd4f 100644
--- a/.github/workflows/pipeline.yml
+++ b/.github/workflows/pipeline.yml
@@ -96,9 +96,7 @@ jobs:
filters: |
llm_connections:
- 'packages/shared/package.json'
- - 'packages/shared/src/server/llm/fetchLLMCompletion.ts'
- - 'packages/shared/src/server/llm/secureLlmFetch.ts'
- - 'packages/shared/src/server/llm/utils.ts'
+ - 'packages/shared/src/server/llm/**'
- 'worker/src/__tests__/llmConnections.test.ts'
lint:
diff --git a/packages/shared/AGENTS.md b/packages/shared/AGENTS.md
index d2b3575352..540fbb53a5 100644
--- a/packages/shared/AGENTS.md
+++ b/packages/shared/AGENTS.md
@@ -47,7 +47,8 @@ Use root [AGENTS.md](../../AGENTS.md) for monorepo-level rules.
- `@langfuse/shared/src/server` via `src/server/index.ts`: server-only barrel
for shared backend services, repositories, queue helpers/contracts, Redis and
ClickHouse helpers, auth helpers, logger/instrumentation, ingestion helpers,
- LLM execution helpers, and server test utilities.
+ AI SDK-native LLM execution helpers (`generateLLMText` and
+ `streamLLMText`), and server test utilities.
- `@langfuse/shared/src/db` via `src/db.ts`: Prisma client singleton plus
Prisma namespace/types for direct database access. Never route this into
frontend-safe code.
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 14be3f1e4e..5c247d08ca 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -100,7 +100,6 @@
"@ai-sdk/google": "^4.0.6",
"@ai-sdk/google-vertex": "^5.0.8",
"@ai-sdk/openai": "^4.0.0",
- "@anthropic-ai/vertex-sdk": "^0.17.1",
"@aws-sdk/client-cloudwatch": "catalog:",
"@aws-sdk/client-lambda": "catalog:",
"@aws-sdk/client-s3": "catalog:",
@@ -111,11 +110,6 @@
"@azure/storage-blob": "^12.26.0",
"@clickhouse/client": "1.23.1",
"@google-cloud/storage": "^7.19.0",
- "@langchain/anthropic": "^1.3.26",
- "@langchain/aws": "^1.3.4",
- "@langchain/core": "^1.1.48",
- "@langchain/google": "^0.1.11",
- "@langchain/openai": "^1.4.2",
"@opentelemetry/api": ">=1.0.0 <1.10.0",
"@opentelemetry/otlp-transformer": "^0.220.0",
"@opentelemetry/resources": "^2.9.0",
@@ -140,7 +134,6 @@
"ioredis": "^5.10.1",
"ipaddr.js": "^2.2.0",
"jsonpath-plus": "10.3.0",
- "langchain": "^1.3.0",
"langfuse-langchain": "3.38.20",
"lodash": "^4.18.1",
"lossless-json": "^4.1.1",
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 3cd8e005fc..8ae0bd89cc 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -475,21 +475,6 @@ const EnvSchema = z.object({
.positive()
.default(120_000), // 2 minutes
- // Comma-separated list of LLM adapters (LLMAdapter enum values: "openai",
- // "anthropic", "azure", "bedrock", "google-vertex-ai", "google-ai-studio")
- // 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/index.ts b/packages/shared/src/server/index.ts
index 462f1c9ef2..ad3e277edb 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -42,7 +42,7 @@ export * from "./auth/customSsoProvider";
export * from "./auth/gitHubEnterpriseProvider";
export * from "./auth/jumpcloudProvider";
export * from "./auth/userProjectRoleAuth";
-export * from "./llm/fetchLLMCompletion";
+export * from "./llm/llmText";
export * from "./llm/errors";
export * from "./llm/utils";
export * from "./llm/types";
diff --git a/packages/shared/src/server/llm/ai-sdk/executeAiSdkCompletion.ts b/packages/shared/src/server/llm/ai-sdk/executeAiSdkCompletion.ts
deleted file mode 100644
index 30ee42d5f2..0000000000
--- a/packages/shared/src/server/llm/ai-sdk/executeAiSdkCompletion.ts
+++ /dev/null
@@ -1,302 +0,0 @@
-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 type { LLMConnectionConfig } from "../../../interfaces/customLLMProviderConfigSchemas";
-import {
- ChatMessage,
- LLMJSONSchema,
- LLMToolDefinition,
- ModelParams,
- ToolCallResponse,
- ToolCallResponseSchema,
- TraceSinkParams,
-} from "../types";
-import { mapChatMessagesToModelMessages } from "./messages";
-import { buildAiSdkModel, type CreateSecureFetch } from "./providers";
-import type { AiSdkEngineDecision } from "./resolveLlmExecutionDecision";
-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>;
- llmConnectionConfig?: LLMConnectionConfig | null;
- shouldUseLangfuseAPIKey?: boolean;
- maxRetries?: number;
- timeoutMs: number;
- createFetch: CreateSecureFetch;
- decision: AiSdkEngineDecision;
- 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,
- decision,
- 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 = await buildAiSdkModel({
- decision,
- modelParams,
- apiKey: params.apiKey,
- baseURL: params.baseURL,
- extraHeaders: params.extraHeaders,
- config: params.llmConnectionConfig,
- shouldUseLangfuseAPIKey: params.shouldUseLangfuseAPIKey ?? false,
- createFetch: params.createFetch,
- });
- modelMessages = mapChatMessagesToModelMessages(messages, {
- adapter: modelParams.adapter,
- });
- 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,
- ...(decision.translatedProviderOptions
- ? {
- providerOptions: {
- [decision.providerOptionsName]:
- decision.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.test.ts b/packages/shared/src/server/llm/ai-sdk/messages.test.ts
index 93543daa6c..0d295380ec 100644
--- a/packages/shared/src/server/llm/ai-sdk/messages.test.ts
+++ b/packages/shared/src/server/llm/ai-sdk/messages.test.ts
@@ -53,7 +53,7 @@ describe("mapChatMessagesToModelMessages", () => {
}
});
- it("drops a lone empty message like the LangChain filter", () => {
+ it("drops a lone empty message", () => {
expect(
mapChatMessagesToModelMessages([{ ...systemMessage, content: "" }], {
adapter: LLMAdapter.Anthropic,
diff --git a/packages/shared/src/server/llm/ai-sdk/messages.ts b/packages/shared/src/server/llm/ai-sdk/messages.ts
index fc9fa181bb..cd6cb2fde6 100644
--- a/packages/shared/src/server/llm/ai-sdk/messages.ts
+++ b/packages/shared/src/server/llm/ai-sdk/messages.ts
@@ -23,8 +23,8 @@ const toSafeContent = (content: unknown): string =>
typeof content === "string" ? content : safeStringify(content);
/**
- * Maps Langfuse `ChatMessage[]` to AI SDK `ModelMessage[]`, mirroring the
- * LangChain mapping in `fetchLLMCompletion`:
+ * Maps persisted/playground Langfuse `ChatMessage[]` to AI SDK
+ * `ModelMessage[]`:
* - 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
@@ -32,8 +32,7 @@ const toSafeContent = (content: unknown): string =>
* tool-call messages; orphan tool results fail fast as a non-retryable
* error instead of a provider-side 400
* - for providers that require at least one user message, a lone message
- * becomes a user message regardless of its role (LangChain-parity:
- * `transformSystemMessageToUserMessage`)
+ * becomes a user message regardless of its role (provider compatibility)
*/
export function mapChatMessagesToModelMessages(
messages: ChatMessage[],
diff --git a/packages/shared/src/server/llm/ai-sdk/providers/anthropic.test.ts b/packages/shared/src/server/llm/ai-sdk/providers/anthropic.test.ts
index ace166360b..bf99d80f2a 100644
--- a/packages/shared/src/server/llm/ai-sdk/providers/anthropic.test.ts
+++ b/packages/shared/src/server/llm/ai-sdk/providers/anthropic.test.ts
@@ -12,7 +12,7 @@ describe("toAnthropicBaseURL", () => {
expect(toAnthropicBaseURL("")).toBeUndefined();
});
- it("appends /v1 to the origin-style URL LangChain expects", () => {
+ it("appends /v1 to an origin-style stored URL", () => {
expect(toAnthropicBaseURL("https://api.anthropic.com")).toBe(
"https://api.anthropic.com/v1",
);
diff --git a/packages/shared/src/server/llm/ai-sdk/providers/anthropic.ts b/packages/shared/src/server/llm/ai-sdk/providers/anthropic.ts
index 779e3a7e4d..e98ddf1fd6 100644
--- a/packages/shared/src/server/llm/ai-sdk/providers/anthropic.ts
+++ b/packages/shared/src/server/llm/ai-sdk/providers/anthropic.ts
@@ -1,14 +1,12 @@
import { createAnthropic } from "@ai-sdk/anthropic";
import type { LanguageModel } from "ai";
-import type { ModelParams } from "../../types";
import type { TranslatedProviderOptions } from "./types";
import { ensureBaseURLSuffix, isPlainObject } from "./utils";
/**
- * LangChain's `anthropicApiUrl` is the API origin — the underlying
- * @anthropic-ai/sdk appends `/v1/messages` itself. The AI SDK instead expects
- * the `/v1` prefix to be part of `baseURL` (default
+ * The stored Anthropic base URL is the API origin, without `/v1/messages`.
+ * The AI SDK expects the `/v1` prefix to be part of `baseURL` (default
* `https://api.anthropic.com/v1`) and appends only `/messages`.
*/
export function toAnthropicBaseURL(
@@ -18,7 +16,7 @@ export function toAnthropicBaseURL(
}
export function buildAnthropicModel(params: {
- modelParams: ModelParams;
+ modelId: string;
apiKey: string;
baseURL?: string | null;
extraHeaders?: Record<string, string>;
@@ -31,7 +29,7 @@ export function buildAnthropicModel(params: {
fetch: params.fetch,
});
- return provider(params.modelParams.model);
+ return provider(params.modelId);
}
// Keys the AI SDK Anthropic provider accepts verbatim (camelCase, already
@@ -51,29 +49,26 @@ const ANTHROPIC_THINKING_TYPES = new Set(["adaptive", "enabled", "disabled"]);
* Translation of Langfuse `modelParams.providerOptions` to AI SDK Anthropic
* provider options.
*
- * The LangChain engine merges `providerOptions` verbatim into the Anthropic
- * request body (`invocationKwargs`), so users configured snake_case Anthropic
- * body params — most importantly `thinking: { type, budget_tokens }`. The AI
+ * Persisted provider options contain snake_case Anthropic request-body fields,
+ * most importantly `thinking: { type, budget_tokens }`. The AI
* SDK accepts a typed camelCase whitelist under `providerOptions.anthropic`
- * and silently drops unknown keys; any key we cannot translate makes the
- * dispatcher decline to LangChain instead.
+ * and silently drops unknown keys; the compatibility boundary rejects any key
+ * it cannot translate.
*
- * Note the Claude Fable/Mythos guard from the LangChain path is unnecessary
- * here: the AI SDK only serializes `thinking` when it is explicitly enabled
- * or adaptive, so an omitted config never sends `{ type: "disabled" }`.
+ * The AI SDK only serializes `thinking` when it is explicitly enabled or
+ * adaptive, so an omitted config never sends `{ type: "disabled" }` for
+ * Claude Fable/Mythos.
*
- * Known engine difference (accepted): with `thinking` enabled the AI SDK
- * sends `max_tokens = maxOutputTokens + budgetTokens` (the budget counts
- * toward the limit), where LangChain sent `max_tokens` verbatim and Anthropic
- * rejected configs whose budget met or exceeded it. Strictly more permissive;
- * pinned in requestShape.test.ts.
+ * With `thinking` enabled the AI SDK sends
+ * `max_tokens = maxOutputTokens + budgetTokens` because the budget counts
+ * toward the limit. This behavior is pinned in requestShape.test.ts.
*/
export function translateAnthropicProviderOptions(
providerOptions: Record<string, unknown> | undefined,
options?: {
/**
- * The LangChain Vertex-Claude path silently strips a `model` override from
- * `invocationKwargs`; mirror that instead of declining.
+ * Vertex-Claude connections historically ignore a provider-level `model`
+ * override in favor of the selected Vertex model ID.
*/
dropModelOverride?: boolean;
},
diff --git a/packages/shared/src/server/llm/ai-sdk/providers/azure.ts b/packages/shared/src/server/llm/ai-sdk/providers/azure.ts
index 5f2a2dc66a..660dda3166 100644
--- a/packages/shared/src/server/llm/ai-sdk/providers/azure.ts
+++ b/packages/shared/src/server/llm/ai-sdk/providers/azure.ts
@@ -1,12 +1,9 @@
import { createAzure } from "@ai-sdk/azure";
import type { LanguageModel } from "ai";
-import type { ModelParams } from "../../types";
import { trimTrailingSlashes } from "./utils";
-// Pinned to the version the LangChain engine sends
-// (`AzureChatOpenAI.azureOpenAIApiVersion`) so both engines hit the identical
-// Azure API surface.
+// Pinned to the API version used by existing Langfuse Azure connections.
const AZURE_OPENAI_API_VERSION = "2025-02-01-preview";
export type AzureBaseURLTranslation =
@@ -14,13 +11,13 @@ export type AzureBaseURLTranslation =
| { ok: false; reason: string };
/**
- * Langfuse stores the LangChain `azureOpenAIBasePath`, documented as
- * `https://{instance}.openai.azure.com/openai/deployments`; LangChain appends
- * `/{deployment}/chat/completions?api-version=...`. The AI SDK's
+ * Langfuse stores the Azure base path as
+ * `https://{instance}.openai.azure.com/openai/deployments`, with the
+ * deployment and chat-completions path appended at request time. The AI SDK's
* `useDeploymentBasedUrls` mode appends `/deployments/{deployment}{path}` to
* its `baseURL`, so the stored URL maps by stripping the trailing
- * `/deployments` segment. Any other shape has no AI SDK equivalent (the
- * request URL would silently change), so the dispatcher declines to LangChain.
+ * `/deployments` segment. Any other shape has no AI SDK equivalent and is
+ * rejected rather than silently changing the request URL.
*/
export function translateAzureBaseURL(
baseURL: string | null | undefined,
@@ -41,7 +38,7 @@ export function translateAzureBaseURL(
}
export function buildAzureModel(params: {
- modelParams: ModelParams;
+ modelId: string;
apiKey: string;
baseURL?: string | null;
extraHeaders?: Record<string, string>;
@@ -49,8 +46,8 @@ export function buildAzureModel(params: {
}): LanguageModel {
const baseUrlTranslation = translateAzureBaseURL(params.baseURL);
if (!baseUrlTranslation.ok) {
- // The dispatcher only selects the AI SDK engine for translatable base
- // URLs, so this is a defensive guard against drift.
+ // Configuration validation runs before model construction; keep this
+ // defensive guard so the provider cannot be built from an invalid URL.
throw new Error(baseUrlTranslation.reason);
}
@@ -63,7 +60,6 @@ export function buildAzureModel(params: {
fetch: params.fetch,
});
- // Chat Completions to match `AzureChatOpenAI`; the model name is the Azure
- // deployment name.
- return provider.chat(params.modelParams.model);
+ // Azure connections use Chat Completions; the model name is the deployment.
+ return provider.chat(params.modelId);
}
diff --git a/packages/shared/src/server/llm/ai-sdk/providers/bedrock.ts b/packages/shared/src/server/llm/ai-sdk/providers/bedrock.ts
index dd8281d414..84f234b669 100644
--- a/packages/shared/src/server/llm/ai-sdk/providers/bedrock.ts
+++ b/packages/shared/src/server/llm/ai-sdk/providers/bedrock.ts
@@ -9,16 +9,15 @@ import {
BedrockCredentialSchema,
type LLMConnectionConfig,
} from "../../../../interfaces/customLLMProviderConfigSchemas";
-import type { ModelParams } from "../../types";
-import type { TranslatedProviderOptions } from "./types";
+import type { LLMCredentialSource, TranslatedProviderOptions } from "./types";
import { isPlainObject } from "./utils";
// AWS region identifiers are lowercase alphanumerics plus hyphens
// (e.g. "us-east-1", "eu-central-1"). The region flows into the Bedrock host
// the AI SDK builds (https://bedrock-runtime.${region}.amazonaws.com) and this
// path intentionally skips the secure LLM fetch, so reject anything that
-// could reshape that host — the LangChain engine got the equivalent guard
-// from the AWS SDK's own host-label validation.
+// could reshape that host. The AWS SDK applies equivalent host-label
+// validation, but this provider builds its own endpoint.
const AWS_REGION_PATTERN = /^[a-z0-9-]+$/;
export function assertValidBedrockRegion(region: string | undefined): void {
@@ -33,8 +32,8 @@ export function assertValidBedrockRegion(region: string | undefined): void {
* Translation of Langfuse `modelParams.providerOptions` to AI SDK Bedrock
* provider options.
*
- * The LangChain engine passes `providerOptions` verbatim as the Converse API's
- * `additionalModelRequestFields`; the AI SDK exposes the identical escape
+ * Persisted provider options pass through as the Converse API's
+ * `additionalModelRequestFields`; the AI SDK exposes that escape
* hatch under `providerOptions.bedrock.additionalModelRequestFields`, so the
* translation is lossless and never declines. A nested `bedrock` object is
* treated as already AI SDK-shaped (e.g. `reasoningConfig`) and merged at the
@@ -49,8 +48,8 @@ export function translateBedrockProviderOptions(
const { bedrock: nested, ...rest } = providerOptions;
- // A non-object `bedrock` key is not an escape hatch — keep it in the
- // verbatim passthrough like LangChain would.
+ // A non-object `bedrock` key is not an escape hatch; keep it in the
+ // verbatim request-field passthrough.
const passthrough = isPlainObject(nested)
? rest
: { ...rest, ...(nested !== undefined ? { bedrock: nested } : {}) };
@@ -77,13 +76,12 @@ export function translateBedrockProviderOptions(
// authenticate as the server. An empty string suppresses the fallback
// (`loadOptionalSetting` returns any string verbatim; the provider treats
// empty as unset and proceeds with SigV4) so auth only ever comes from the
-// resolved Langfuse connection credential, exactly like the LangChain engine
-// (which never honored AWS_BEARER_TOKEN_BEDROCK). Pinned by a regression
-// test in requestShape.test.ts.
+// resolved Langfuse connection credential. Pinned by a regression test in
+// requestShape.test.ts.
const SUPPRESS_BEARER_TOKEN_ENV_FALLBACK = { apiKey: "" };
/**
- * Mirrors `resolveBedrockAuth` on the LangChain path: the decrypted secret is
+ * Resolves the persisted Bedrock credential contract: the decrypted secret is
* either the default-credentials sentinel (allowed only self-hosted or for
* Langfuse-internal AI features), AWS access key JSON, or a Bedrock API key
* used as a bearer token.
@@ -102,8 +100,7 @@ export function resolveBedrockProviderAuth(params: {
allowDefaultCredentials
) {
// Unlike the AI SDK's built-in env-only fallback, the node provider chain
- // matches the AWS SDK default chain the LangChain engine used (env,
- // profile, IMDS, IRSA, ...).
+ // includes env, profile, IMDS, IRSA, and the remaining AWS defaults.
return {
credentialProvider: fromNodeProviderChain(),
...SUPPRESS_BEARER_TOKEN_ENV_FALLBACK,
@@ -138,16 +135,16 @@ export function resolveBedrockProviderAuth(params: {
* No custom fetch is used: Bedrock has no user-controlled base URL (the host
* is derived from the region), and self-hosted deployments commonly reach
* Bedrock through VPC endpoints resolving to private IPs, which the secure
- * LLM fetch would block. This matches the LangChain engine, which also issued
- * plain SDK requests.
+ * LLM fetch would block. Requests therefore use the provider's AWS transport.
*/
export function buildBedrockModel(params: {
- modelParams: ModelParams;
+ modelId: string;
apiKey: string;
config?: LLMConnectionConfig | null;
- shouldUseLangfuseAPIKey: boolean;
+ credentialSource: LLMCredentialSource;
}): LanguageModel {
- const { modelParams, apiKey, config, shouldUseLangfuseAPIKey } = params;
+ const { modelId, apiKey, config, credentialSource } = params;
+ const shouldUseLangfuseAPIKey = credentialSource === "langfuse";
const { region } = shouldUseLangfuseAPIKey
? { region: env.LANGFUSE_AWS_BEDROCK_REGION }
@@ -165,5 +162,5 @@ export function buildBedrockModel(params: {
...auth,
});
- return provider(modelParams.model);
+ return provider(modelId);
}
diff --git a/packages/shared/src/server/llm/ai-sdk/providers/google.test.ts b/packages/shared/src/server/llm/ai-sdk/providers/google.test.ts
index d8afdde9ff..9d4d22010c 100644
--- a/packages/shared/src/server/llm/ai-sdk/providers/google.test.ts
+++ b/packages/shared/src/server/llm/ai-sdk/providers/google.test.ts
@@ -11,7 +11,7 @@ describe("toGoogleAIStudioBaseURL", () => {
expect(toGoogleAIStudioBaseURL(null)).toBeUndefined();
});
- it("appends /v1beta to the origin-style URL LangChain expects", () => {
+ it("appends /v1beta to an origin-style stored URL", () => {
expect(toGoogleAIStudioBaseURL("https://proxy.example.com/google")).toBe(
"https://proxy.example.com/google/v1beta",
);
@@ -39,7 +39,7 @@ describe("translateGoogleProviderOptions", () => {
).toEqual({ ok: true, value: undefined });
});
- it("silently strips unknown keys like LangChain's non-strict schema", () => {
+ it("silently strips unknown keys from the non-strict persisted shape", () => {
expect(
translateGoogleProviderOptions({
providerOptions: { customField: 1, thinkingBudget: 1024 },
@@ -88,7 +88,7 @@ describe("translateGoogleProviderOptions", () => {
});
});
- it("prefers maxReasoningTokens over thinkingBudget like LangChain", () => {
+ it("prefers maxReasoningTokens over thinkingBudget", () => {
expect(
translateGoogleProviderOptions({
providerOptions: { thinkingBudget: 1024 },
@@ -153,7 +153,7 @@ describe("translateGoogleProviderOptions", () => {
});
});
- it("declines representation conversions LangChain does via model tables", () => {
+ it("rejects representation conversions that require model tables", () => {
// level-only on a budget-family model
expect(
translateGoogleProviderOptions({
@@ -170,7 +170,7 @@ describe("translateGoogleProviderOptions", () => {
).toBe(false);
});
- it("declines wrong types so LangChain surfaces the parse error", () => {
+ it("rejects provider options with wrong types", () => {
expect(
translateGoogleProviderOptions({
providerOptions: { thinkingBudget: "lots" },
diff --git a/packages/shared/src/server/llm/ai-sdk/providers/google.ts b/packages/shared/src/server/llm/ai-sdk/providers/google.ts
index b507d7d1e1..55a2c8cf98 100644
--- a/packages/shared/src/server/llm/ai-sdk/providers/google.ts
+++ b/packages/shared/src/server/llm/ai-sdk/providers/google.ts
@@ -1,15 +1,13 @@
import { createGoogleGenerativeAI } from "@ai-sdk/google";
import type { LanguageModel } from "ai";
-import type { ModelParams } from "../../types";
import type { TranslatedProviderOptions } from "./types";
import { ensureBaseURLSuffix, isPlainObject } from "./utils";
/**
- * LangChain's secure Google AI Studio client appends the SDK-generated path
- * (`/v1beta/models/...`) to the stored base URL, so the stored value is an
- * origin-style prefix without the API version. The AI SDK's `baseURL` includes
- * the version (default `https://generativelanguage.googleapis.com/v1beta`).
+ * The stored Google AI Studio base URL is an origin-style prefix without the
+ * generated `/v1beta/models/...` path. The AI SDK's `baseURL` includes the
+ * version (default `https://generativelanguage.googleapis.com/v1beta`).
*/
export function toGoogleAIStudioBaseURL(
baseURL: string | null | undefined,
@@ -18,7 +16,7 @@ export function toGoogleAIStudioBaseURL(
}
export function buildGoogleAIStudioModel(params: {
- modelParams: ModelParams;
+ modelId: string;
apiKey: string;
baseURL?: string | null;
fetch: typeof fetch;
@@ -29,9 +27,9 @@ export function buildGoogleAIStudioModel(params: {
fetch: params.fetch,
});
- // Note: extra headers are intentionally not sent — the LangChain engine's
- // Google AI Studio client only injects the API key header.
- return provider(params.modelParams.model);
+ // Extra headers are intentionally not sent; only the API key header belongs
+ // on this request path.
+ return provider(params.modelId);
}
const GOOGLE_THINKING_LEVELS = new Set(["minimal", "low", "medium", "high"]);
@@ -40,17 +38,17 @@ const GOOGLE_THINKING_LEVELS = new Set(["minimal", "low", "medium", "high"]);
* Translation of Langfuse `modelParams.providerOptions` (plus the Vertex-only
* `modelParams.maxReasoningTokens`) to AI SDK Google provider options.
*
- * The LangChain engine parses `providerOptions` with a non-strict zod schema
- * ({ thinkingBudget?, thinkingLevel? }) — unknown keys are silently stripped,
- * never sent — so stripping them here is exact parity, unlike the other
- * adapters where unknown keys reach the request body.
+ * Persisted Google options use a non-strict shape
+ * ({ thinkingBudget?, thinkingLevel? }); unknown keys were never sent and are
+ * intentionally stripped here, unlike adapters whose stored options are
+ * request-body passthroughs.
*
- * LangChain then derives a wire `thinkingConfig` from the model family:
+ * The compatibility mapper derives wire `thinkingConfig` from the model family:
* `gemini-2.5*` gets `thinkingBudget`, everything else gets `thinkingLevel`,
* converting between the two representations when needed. We mirror the
- * direct cases and decline the conversion cases (budget-only on a
- * level-family model or vice versa), since replicating LangChain's
- * model-specific conversion tables would silently drift.
+ * direct cases and reject the conversion cases (budget-only on a
+ * level-family model or vice versa), since guessing a model-specific
+ * conversion would silently drift.
*/
export function translateGoogleProviderOptions(params: {
providerOptions: Record<string, unknown> | undefined;
@@ -74,14 +72,14 @@ export function translateGoogleProviderOptions(params: {
rawThinkingBudget !== undefined &&
typeof rawThinkingBudget !== "number"
) {
- // LangChain's schema parse would throw; decline so it does.
+ // The persisted schema rejected this shape; keep it a configuration error.
return { ok: false, unknownKeys: ["thinkingBudget"] };
}
if (rawThinkingLevel !== undefined && typeof rawThinkingLevel !== "string") {
return { ok: false, unknownKeys: ["thinkingLevel"] };
}
- // LangChain precedence: maxReasoningTokens ?? thinkingBudget.
+ // Persisted precedence: maxReasoningTokens ?? thinkingBudget.
const thinkingBudget = maxReasoningTokens ?? rawThinkingBudget;
const thinkingLevel = rawThinkingLevel?.toLowerCase();
@@ -118,14 +116,14 @@ function buildThinkingConfig(params: {
let { thinkingBudget, thinkingLevel } = params;
if (model.startsWith("gemini-2.5")) {
- // Budget-family model. LangChain converts a lone thinkingLevel into a
- // token budget via model-specific tables; decline instead of guessing.
+ // Budget-family model. A lone thinkingLevel would require a model-specific
+ // conversion table; reject instead of guessing.
if (thinkingBudget === undefined) {
return { ok: false, unknownKeys: ["thinkingLevel"] };
}
- // Mirror LangChain exactly, quirks included, so flipping the engine flag
- // never changes what a given config sends: `includeThoughts` is computed
+ // Preserve the established request shape, quirks included:
+ // `includeThoughts` is computed
// BEFORE the 2.5-pro 128-token clamp (an explicit budget of 128 hides
// thoughts while 1-127 gets clamped to 128 with thoughts visible), the
// `>= 0` bound intentionally exempts negative budgets from clamping, and
@@ -158,7 +156,7 @@ function buildThinkingConfig(params: {
const includeThoughts = thinkingLevel !== "minimal";
- // LangChain remaps unsupported levels for the pro families.
+ // Remap unsupported levels for the pro families.
if (model.startsWith("gemini-3-pro")) {
if (thinkingLevel === "minimal") thinkingLevel = "low";
else if (thinkingLevel === "medium") thinkingLevel = "high";
diff --git a/packages/shared/src/server/llm/ai-sdk/providers/index.ts b/packages/shared/src/server/llm/ai-sdk/providers/index.ts
index 9a7e219dce..cdc9a0f4f6 100644
--- a/packages/shared/src/server/llm/ai-sdk/providers/index.ts
+++ b/packages/shared/src/server/llm/ai-sdk/providers/index.ts
@@ -1,13 +1,14 @@
import type { LanguageModel } from "ai";
import type { LLMConnectionConfig } from "../../../../interfaces/customLLMProviderConfigSchemas";
-import { LLMAdapter, type ModelParams } from "../../types";
-import type { AiSdkEngineDecision } from "../resolveLlmExecutionDecision";
+import { LLMAdapter } from "../../types";
+import type { AiSdkModelConfig } from "../resolveAiSdkModelConfig";
import { buildAnthropicModel } from "./anthropic";
import { buildAzureModel } from "./azure";
import { buildBedrockModel } from "./bedrock";
import { buildGoogleAIStudioModel } from "./google";
import { buildOpenAIModel } from "./openai";
+import type { LLMCredentialSource } from "./types";
import { buildVertexModel, isClaudeModel } from "./vertex";
const AZURE_OPENAI_API_KEY_HEADER = "api-key";
@@ -26,45 +27,45 @@ export type CreateSecureFetch = (
) => typeof fetch;
/**
- * Builds the AI SDK `LanguageModel` for a dispatched completion. Credential
- * parsing and endpoint construction mirror the LangChain engine per adapter;
- * see the per-provider modules for the parity notes.
+ * Builds the AI SDK `LanguageModel` for a completion. Credential parsing and
+ * endpoint construction preserve the persisted connection contract; see the
+ * per-provider modules for adapter-specific details.
*/
export async function buildAiSdkModel(params: {
- decision: AiSdkEngineDecision;
- modelParams: ModelParams;
+ model: { adapter: LLMAdapter; id: string };
+ modelConfig: AiSdkModelConfig;
apiKey: string;
baseURL?: string | null;
extraHeaders?: Record<string, string>;
config?: LLMConnectionConfig | null;
- shouldUseLangfuseAPIKey: boolean;
+ credentialSource: LLMCredentialSource;
createFetch: CreateSecureFetch;
}): Promise<LanguageModel> {
const {
- decision,
- modelParams,
+ model,
+ modelConfig,
apiKey,
baseURL,
extraHeaders,
config,
- shouldUseLangfuseAPIKey,
+ credentialSource,
createFetch,
} = params;
- switch (decision.adapter) {
+ switch (model.adapter) {
case LLMAdapter.OpenAI:
return buildOpenAIModel({
- modelParams,
+ modelId: model.id,
apiKey,
baseURL,
extraHeaders,
- apiMode: decision.openAIApiMode ?? "chat-completions",
+ apiMode: modelConfig.openAIApiMode ?? "chat-completions",
fetch: createFetch("OpenAI LLM base URL"),
});
case LLMAdapter.Azure:
return buildAzureModel({
- modelParams,
+ modelId: model.id,
apiKey,
baseURL,
extraHeaders,
@@ -75,7 +76,7 @@ export async function buildAiSdkModel(params: {
case LLMAdapter.Anthropic:
return buildAnthropicModel({
- modelParams,
+ modelId: model.id,
apiKey,
baseURL,
extraHeaders,
@@ -86,15 +87,15 @@ export async function buildAiSdkModel(params: {
case LLMAdapter.Bedrock:
return buildBedrockModel({
- modelParams,
+ modelId: model.id,
apiKey,
config,
- shouldUseLangfuseAPIKey,
+ credentialSource,
});
case LLMAdapter.GoogleAIStudio:
return buildGoogleAIStudioModel({
- modelParams,
+ modelId: model.id,
apiKey,
baseURL,
fetch: createFetch("Google AI Studio LLM base URL", [
@@ -104,12 +105,12 @@ export async function buildAiSdkModel(params: {
case LLMAdapter.VertexAI:
return buildVertexModel({
- modelParams,
+ modelId: model.id,
apiKey,
config,
extraHeaders,
fetch: createFetch(
- isClaudeModel(modelParams.model)
+ isClaudeModel(model.id)
? "Anthropic Vertex AI endpoint"
: "Vertex AI LLM endpoint",
[VERTEX_AI_AUTH_HEADER],
@@ -117,7 +118,7 @@ export async function buildAiSdkModel(params: {
});
default: {
- const _exhaustiveCheck: never = decision.adapter;
+ const _exhaustiveCheck: never = model.adapter;
throw new Error(`AI SDK adapter is not supported: ${_exhaustiveCheck}`);
}
}
diff --git a/packages/shared/src/server/llm/ai-sdk/providers/openai.ts b/packages/shared/src/server/llm/ai-sdk/providers/openai.ts
index f650b20237..c4031be26c 100644
--- a/packages/shared/src/server/llm/ai-sdk/providers/openai.ts
+++ b/packages/shared/src/server/llm/ai-sdk/providers/openai.ts
@@ -1,7 +1,6 @@
import { createOpenAI } from "@ai-sdk/openai";
import type { LanguageModel } from "ai";
-import type { ModelParams } from "../../types";
import { processOpenAIBaseURL } from "../../utils";
import type { TranslatedProviderOptions } from "./types";
import { isPlainObject } from "./utils";
@@ -9,18 +8,18 @@ import { isPlainObject } from "./utils";
export type OpenAIApiMode = "responses" | "chat-completions";
export function buildOpenAIModel(params: {
- modelParams: ModelParams;
+ modelId: string;
apiKey: string;
baseURL?: string | null;
extraHeaders?: Record<string, string>;
apiMode: OpenAIApiMode;
fetch: typeof fetch;
}): LanguageModel {
- const { apiKey, baseURL, extraHeaders, apiMode, modelParams } = params;
+ const { apiKey, baseURL, extraHeaders, apiMode, modelId } = params;
const processedBaseURL = processOpenAIBaseURL({
url: baseURL,
- modelName: modelParams.model,
+ modelName: modelId,
});
const provider = createOpenAI({
@@ -34,23 +33,22 @@ export function buildOpenAIModel(params: {
// 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);
+ ? provider.responses(modelId)
+ : provider.chat(modelId);
}
/**
* 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
+ * Persisted provider options contain snake_case OpenAI request-body fields.
+ * 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.
+ * unacceptable: the compatibility boundary rejects any key it cannot
+ * translate.
*/
const OPENAI_PROVIDER_OPTION_KEY_MAP: Record<string, string> = {
- // snake_case (OpenAI request body, as used with LangChain modelKwargs)
+ // snake_case persisted OpenAI request-body fields
reasoning_effort: "reasoningEffort",
service_tier: "serviceTier",
parallel_tool_calls: "parallelToolCalls",
diff --git a/packages/shared/src/server/llm/ai-sdk/providers/types.ts b/packages/shared/src/server/llm/ai-sdk/providers/types.ts
index 12353501c4..dfe5125b6f 100644
--- a/packages/shared/src/server/llm/ai-sdk/providers/types.ts
+++ b/packages/shared/src/server/llm/ai-sdk/providers/types.ts
@@ -1,10 +1,11 @@
/**
- * Result of translating Langfuse `modelParams.providerOptions` (whose shape is
- * owned by the LangChain engine's per-adapter passthrough semantics) into AI
- * SDK provider options. Silent dropping is unacceptable: any key an adapter
- * cannot translate makes the dispatcher decline to LangChain (with a recorded
- * reason) instead.
+ * Result of translating persisted Langfuse `modelParams.providerOptions` into
+ * AI SDK provider options. Silent dropping is unacceptable: the compatibility
+ * boundary turns a failed translation into an explicit non-retryable
+ * configuration error.
*/
export type TranslatedProviderOptions =
| { ok: true; value: Record<string, unknown> | undefined }
| { ok: false; unknownKeys: string[] };
+
+export type LLMCredentialSource = "user" | "langfuse";
diff --git a/packages/shared/src/server/llm/ai-sdk/providers/utils.ts b/packages/shared/src/server/llm/ai-sdk/providers/utils.ts
index df44a41345..d72b222761 100644
--- a/packages/shared/src/server/llm/ai-sdk/providers/utils.ts
+++ b/packages/shared/src/server/llm/ai-sdk/providers/utils.ts
@@ -10,8 +10,7 @@ export function trimTrailingSlashes(url: string): string {
}
/**
- * Normalizes a stored LangChain-era base URL (an origin-style prefix the
- * underlying SDK appended a version segment to) into the AI SDK shape, where
+ * Normalizes a stored origin-style base URL into the AI SDK shape, where
* the version segment is part of `baseURL`. Keeps an already-suffixed URL
* unchanged.
*/
diff --git a/packages/shared/src/server/llm/ai-sdk/providers/vertex.ts b/packages/shared/src/server/llm/ai-sdk/providers/vertex.ts
index ce479ccc37..61f3a0a2e9 100644
--- a/packages/shared/src/server/llm/ai-sdk/providers/vertex.ts
+++ b/packages/shared/src/server/llm/ai-sdk/providers/vertex.ts
@@ -9,7 +9,6 @@ import GCPServiceAccountKeySchema, {
VERTEXAI_USE_DEFAULT_CREDENTIALS,
VertexAIConfigSchema,
} from "../../../../interfaces/customLLMProviderConfigSchemas";
-import type { ModelParams } from "../../types";
const VERTEX_AI_AUTH_SCOPES = [
"https://www.googleapis.com/auth/cloud-platform",
@@ -51,24 +50,21 @@ export function assertValidVertexLocation(location: string | undefined): void {
/**
* Builds a Vertex AI model: Gemini via `@ai-sdk/google-vertex`, Claude via its
- * `/anthropic` entry point (Anthropic Messages over Vertex `rawPredict`),
- * mirroring the LangChain split between `ChatGoogle` and
- * `ChatAnthropic`+`AnthropicVertex`.
+ * `/anthropic` entry point (Anthropic Messages over Vertex `rawPredict`).
*
- * Credentials mirror the LangChain path: the decrypted secret is either a GCP
- * service account key (project taken from the key; user-supplied project IDs
- * are never honored) or the ADC sentinel, allowed only in self-hosted
- * deployments, in which case the project is resolved from the default
- * credential chain.
+ * The decrypted secret is either a GCP service account key (project taken from
+ * the key; user-supplied project IDs are never honored) or the ADC sentinel,
+ * allowed only in self-hosted deployments, in which case the project is
+ * resolved from the default credential chain.
*/
export async function buildVertexModel(params: {
- modelParams: ModelParams;
+ modelId: string;
apiKey: string;
config?: LLMConnectionConfig | null;
extraHeaders?: Record<string, string>;
fetch: typeof fetch;
}): Promise<LanguageModel> {
- const { modelParams, apiKey, config, extraHeaders } = params;
+ const { modelId, apiKey, config, extraHeaders } = params;
const { location } = config
? VertexAIConfigSchema.parse(config)
@@ -97,11 +93,11 @@ export async function buildVertexModel(params: {
serviceAccountKey?.project_id ??
(await new GoogleAuth({ scopes: VERTEX_AI_AUTH_SCOPES }).getProjectId());
- // LangChain defaults the location to "global" for both model families.
+ // Existing connections default the location to "global" for both families.
const resolvedLocation = location ?? "global";
- if (isClaudeModel(modelParams.model)) {
- assertValidAnthropicVertexModelName(modelParams.model);
+ if (isClaudeModel(modelId)) {
+ assertValidAnthropicVertexModelName(modelId);
const provider = createVertexAnthropic({
project,
@@ -111,11 +107,11 @@ export async function buildVertexModel(params: {
fetch: params.fetch,
});
- return provider(modelParams.model);
+ return provider(modelId);
}
- // Note: extra headers are intentionally not sent for Gemini — the LangChain
- // engine's Vertex client only injects the OAuth headers.
+ // Extra headers are intentionally not sent for Gemini; only the OAuth
+ // headers belong on this request path.
const provider = createVertex({
project,
location: resolvedLocation,
@@ -123,5 +119,5 @@ export async function buildVertexModel(params: {
fetch: params.fetch,
});
- return provider(modelParams.model);
+ return provider(modelId);
}
diff --git a/packages/shared/src/server/llm/ai-sdk/requestShape.test.ts b/packages/shared/src/server/llm/ai-sdk/requestShape.test.ts
index 3c54646fa7..ed6fdf2930 100644
--- a/packages/shared/src/server/llm/ai-sdk/requestShape.test.ts
+++ b/packages/shared/src/server/llm/ai-sdk/requestShape.test.ts
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
+import { encrypt } from "../../../encryption";
import {
type ChatMessage,
ChatMessageRole,
@@ -7,8 +8,13 @@ import {
LLMAdapter,
type ModelParams,
} from "../types";
-import { executeAiSdkCompletion } from "./executeAiSdkCompletion";
-import { resolveLlmExecutionDecision } from "./resolveLlmExecutionDecision";
+import { generateLLMText, mapLegacyLLMCompletionParams } from "../llmText";
+
+// Request-shape coverage exercises the real provider packages while replacing
+// the separately tested secure transport with a capture fetch.
+vi.mock("../secureLlmFetch", () => ({
+ createSecureLlmFetch: () => globalThis.fetch,
+}));
// The Vertex provider exchanges service-account credentials for an OAuth
// token via google-auth-library before issuing the model request; both the
@@ -23,8 +29,6 @@ vi.mock("google-auth-library", () => ({
},
}));
-const ALL_ADAPTERS = Object.values(LLMAdapter);
-
const messages: ChatMessage[] = [
{
type: ChatMessageType.System,
@@ -158,28 +162,22 @@ async function runCompletion(params: {
llmConnectionConfig?: Record<string, string | boolean>;
response: unknown;
}) {
- const decision = resolveLlmExecutionDecision({
- modelParams: params.modelParams,
- llmConnectionConfig: params.llmConnectionConfig,
- baseURL: params.baseURL,
- enabledAdapters: ALL_ADAPTERS,
- });
- if (decision.engine !== "ai-sdk") {
- throw new Error("Expected the AI SDK engine to be selected");
- }
-
const { calls, fetch } = createCaptureFetch(params.response);
- const result = await executeAiSdkCompletion({
- messages,
- modelParams: params.modelParams,
- streaming: false,
- apiKey: params.apiKey,
- baseURL: params.baseURL,
- extraHeaders: params.extraHeaders,
- llmConnectionConfig: params.llmConnectionConfig,
- timeoutMs: 10_000,
- createFetch: () => fetch,
- decision,
+ vi.stubGlobal("fetch", fetch);
+ const result = await generateLLMText({
+ ...mapLegacyLLMCompletionParams({
+ messages,
+ modelParams: params.modelParams,
+ connection: {
+ secretKey: encrypt(params.apiKey),
+ baseURL: params.baseURL,
+ extraHeaders: params.extraHeaders
+ ? encrypt(JSON.stringify(params.extraHeaders))
+ : undefined,
+ config: params.llmConnectionConfig,
+ },
+ }),
+ timeout: 10_000,
});
expect(calls).toHaveLength(1);
@@ -206,7 +204,7 @@ describe("AI SDK request shapes", () => {
response: OPENAI_CHAT_RESPONSE,
});
- expect(result).toBe("ok");
+ expect(result.text).toBe("ok");
expect(request.url).toBe("https://api.openai.com/v1/chat/completions");
expect(request.headers.get("authorization")).toBe("Bearer sk-test");
expect(request.body.model).toBe("gpt-4o");
@@ -236,13 +234,14 @@ describe("AI SDK request shapes", () => {
expect(request.body.model).toBe("gpt-4o");
});
- it("Azure: LangChain deployment URL with pinned api-version and api-key header", async () => {
+ it("Azure: stored deployment URL with pinned api-version and api-key header", async () => {
const { request } = await runCompletion({
modelParams: {
provider: "azure",
adapter: LLMAdapter.Azure,
model: "gpt4o-deployment",
max_tokens: 64,
+ providerOptions: { logit_bias: { "42": 1 } },
},
apiKey: "azure-key",
baseURL: "https://my-instance.openai.azure.com/openai/deployments",
@@ -255,6 +254,28 @@ describe("AI SDK request shapes", () => {
);
expect(request.headers.get("api-key")).toBe("azure-key");
expect(request.headers.get("x-custom")).toBe("1");
+ expect(request.body.logit_bias).toEqual({ "42": 1 });
+ expect(request.body.max_tokens).toBe(64);
+ });
+
+ it("OpenAI chat completions: gpt-5.4 mini keeps non-reasoning request params", async () => {
+ const { request } = await runCompletion({
+ modelParams: {
+ provider: "openai",
+ adapter: LLMAdapter.OpenAI,
+ model: "gpt-5.4-mini",
+ max_tokens: 64,
+ temperature: 0.2,
+ top_p: 0.9,
+ },
+ apiKey: "openai-key",
+ response: OPENAI_CHAT_RESPONSE,
+ });
+
+ expect(request.body.max_tokens).toBe(64);
+ expect(request.body.max_completion_tokens).toBeUndefined();
+ expect(request.body.temperature).toBe(0.2);
+ expect(request.body.top_p).toBe(0.9);
});
it("Anthropic: /v1/messages on a custom origin with snake_case thinking body", async () => {
@@ -275,10 +296,8 @@ describe("AI SDK request shapes", () => {
expect(request.headers.get("x-api-key")).toBe("anthropic-key");
expect(request.headers.get("anthropic-version")).toBeTruthy();
expect(request.body.model).toBe("claude-sonnet-5");
- // Known engine difference: with thinking enabled the AI SDK sends
- // maxOutputTokens + budgetTokens as max_tokens (the budget counts toward
- // the limit), where LangChain sent max_tokens verbatim and Anthropic
- // rejected configs with max_tokens <= budget_tokens.
+ // With thinking enabled, the budget counts toward Anthropic's max_tokens,
+ // so the provider adds maxOutputTokens and budgetTokens.
expect(request.body.max_tokens).toBe(256 + 1024);
expect(request.body.thinking).toEqual({
type: "enabled",
@@ -329,8 +348,7 @@ describe("AI SDK request shapes", () => {
response: GOOGLE_RESPONSE,
});
- // Known engine difference: the AI SDK targets the v1beta1 Vertex API
- // (LangChain used v1); both serve generateContent with the same contract.
+ // The Google Vertex provider targets the v1beta1 generateContent API.
expect(request.url).toBe(
"https://us-east5-aiplatform.googleapis.com/v1beta1/projects/sa-project-123/locations/us-east5/publishers/google/models/gemini-2.5-flash:generateContent",
);
@@ -380,33 +398,27 @@ describe("AI SDK request shapes", () => {
};
const llmConnectionConfig = { region: "us-east-1" };
- const decision = resolveLlmExecutionDecision({
- modelParams,
- llmConnectionConfig,
- enabledAdapters: ALL_ADAPTERS,
- });
- if (decision.engine !== "ai-sdk") {
- throw new Error("Expected the AI SDK engine to be selected");
- }
-
const { calls, fetch } = createCaptureFetch(BEDROCK_RESPONSE);
vi.stubGlobal("fetch", fetch);
- const result = await executeAiSdkCompletion({
- messages,
- modelParams,
- streaming: false,
- apiKey: JSON.stringify({
- accessKeyId: "AKIA123",
- secretAccessKey: "secret",
+ const result = await generateLLMText({
+ ...mapLegacyLLMCompletionParams({
+ messages,
+ modelParams,
+ connection: {
+ secretKey: encrypt(
+ JSON.stringify({
+ accessKeyId: "AKIA123",
+ secretAccessKey: "secret",
+ }),
+ ),
+ config: llmConnectionConfig,
+ },
}),
- llmConnectionConfig,
- timeoutMs: 10_000,
- createFetch: () => fetch,
- decision,
+ timeout: 10_000,
});
- expect(result).toBe("ok");
+ expect(result.text).toBe("ok");
expect(calls).toHaveLength(1);
return calls[0];
}
diff --git a/packages/shared/src/server/llm/ai-sdk/resolveAiSdkModelConfig.ts b/packages/shared/src/server/llm/ai-sdk/resolveAiSdkModelConfig.ts
new file mode 100644
index 0000000000..a91e9b63aa
--- /dev/null
+++ b/packages/shared/src/server/llm/ai-sdk/resolveAiSdkModelConfig.ts
@@ -0,0 +1,135 @@
+import { getCurrentSpan } from "../../instrumentation";
+import {
+ BedrockConfigSchema,
+ OpenAIConfigSchema,
+ VertexAIConfigSchema,
+ type LLMConnectionConfig,
+} from "../../../interfaces/customLLMProviderConfigSchemas";
+import { LLMCompletionError } from "../errors";
+import { LLMAdapter } from "../types";
+import { translateAzureBaseURL } from "./providers/azure";
+import { assertValidBedrockRegion } from "./providers/bedrock";
+import type { OpenAIApiMode } from "./providers/openai";
+import {
+ assertValidAnthropicVertexModelName,
+ assertValidVertexLocation,
+ isClaudeModel,
+} from "./providers/vertex";
+import type { LLMCredentialSource } from "./providers/types";
+
+export type AiSdkModelConfig = {
+ adapter: LLMAdapter;
+ /** Only set for the OpenAI adapter. */
+ openAIApiMode?: OpenAIApiMode;
+};
+
+/**
+ * Validates connection configuration before model construction. Every adapter
+ * now runs on AI SDK, so unsupported configuration is a terminal caller error
+ * rather than a reason to fall back to a second execution engine.
+ */
+export function resolveAiSdkModelConfig(params: {
+ model: { adapter: LLMAdapter; id: string };
+ connectionConfig?: LLMConnectionConfig | null;
+ baseURL?: string | null;
+ credentialSource: LLMCredentialSource;
+}): AiSdkModelConfig {
+ const { model, connectionConfig, baseURL, credentialSource } = params;
+
+ try {
+ if (
+ credentialSource === "langfuse" &&
+ model.adapter !== LLMAdapter.Bedrock
+ ) {
+ throw new LLMCompletionError({
+ message: "Langfuse credentials are only supported for Amazon Bedrock",
+ responseStatusCode: 400,
+ isRetryable: false,
+ });
+ }
+
+ switch (model.adapter) {
+ case LLMAdapter.OpenAI: {
+ const openAIConfig = OpenAIConfigSchema.parse(connectionConfig ?? {});
+
+ return {
+ adapter: model.adapter,
+ // Chat Completions remains the default for OpenAI-compatible custom
+ // base URLs. The Responses API is an explicit connection setting.
+ openAIApiMode: openAIConfig.useResponsesApi
+ ? "responses"
+ : "chat-completions",
+ };
+ }
+
+ case LLMAdapter.Azure: {
+ const translatedBaseURL = translateAzureBaseURL(baseURL);
+ if (!translatedBaseURL.ok) {
+ throw new Error(translatedBaseURL.reason);
+ }
+
+ return { adapter: model.adapter };
+ }
+
+ case LLMAdapter.Bedrock: {
+ if (credentialSource === "user") {
+ const { region } = BedrockConfigSchema.parse(connectionConfig);
+ assertValidBedrockRegion(region);
+ }
+
+ return { adapter: model.adapter };
+ }
+
+ case LLMAdapter.VertexAI: {
+ const parsedConfig = connectionConfig
+ ? VertexAIConfigSchema.parse(connectionConfig)
+ : undefined;
+ assertValidVertexLocation(parsedConfig?.location);
+ if (isClaudeModel(model.id)) {
+ assertValidAnthropicVertexModelName(model.id);
+ }
+
+ return { adapter: model.adapter };
+ }
+
+ case LLMAdapter.Anthropic:
+ case LLMAdapter.GoogleAIStudio:
+ return { adapter: model.adapter };
+
+ default: {
+ const _exhaustiveCheck: never = model.adapter;
+ throw new Error(`Unsupported LLM adapter: ${_exhaustiveCheck}`);
+ }
+ }
+ } catch (cause) {
+ if (cause instanceof LLMCompletionError) throw cause;
+
+ throw new LLMCompletionError({
+ message:
+ cause instanceof Error
+ ? cause.message
+ : `Invalid ${model.adapter} connection configuration`,
+ responseStatusCode: 400,
+ isRetryable: false,
+ cause,
+ });
+ }
+}
+
+/** Records the now-unconditional AI SDK execution path on the active span. */
+export function recordAiSdkExecution(params: {
+ model: { adapter: LLMAdapter; id: string };
+ modelConfig: AiSdkModelConfig;
+}): void {
+ const span = getCurrentSpan();
+ if (!span) return;
+
+ span.setAttribute("langfuse.llm.execution_engine", "ai-sdk");
+ span.setAttribute("langfuse.llm.ai_sdk.adapter", params.model.adapter);
+ if (params.modelConfig.openAIApiMode) {
+ span.setAttribute(
+ "langfuse.llm.openai.api_mode",
+ params.modelConfig.openAIApiMode,
+ );
+ }
+}
diff --git a/packages/shared/src/server/llm/ai-sdk/resolveLlmExecutionDecision.test.ts b/packages/shared/src/server/llm/ai-sdk/resolveLlmExecutionDecision.test.ts
deleted file mode 100644
index ae19c13e88..0000000000
--- a/packages/shared/src/server/llm/ai-sdk/resolveLlmExecutionDecision.test.ts
+++ /dev/null
@@ -1,219 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import { LLMAdapter, type ModelParams } from "../types";
-import { resolveLlmExecutionDecision } from "./resolveLlmExecutionDecision";
-
-const ALL_ADAPTERS = Object.values(LLMAdapter);
-
-const makeModelParams = (
- adapter: LLMAdapter,
- model: string,
- overrides?: Partial<ModelParams>,
-): ModelParams => ({
- provider: adapter,
- adapter,
- model,
- ...overrides,
-});
-
-describe("resolveLlmExecutionDecision", () => {
- it("declines adapters that are not rolled out", () => {
- expect(
- resolveLlmExecutionDecision({
- modelParams: makeModelParams(LLMAdapter.Anthropic, "claude-sonnet-5"),
- enabledAdapters: ["openai"],
- }),
- ).toEqual({ engine: "langchain-js" });
- });
-
- it("selects the AI SDK per adapter with the right providerOptions namespace", () => {
- const cases: Array<{
- adapter: LLMAdapter;
- model: string;
- baseURL?: string;
- config?: Record<string, string>;
- expectedNamespace: string;
- }> = [
- {
- adapter: LLMAdapter.OpenAI,
- model: "gpt-4o",
- expectedNamespace: "openai",
- },
- {
- adapter: LLMAdapter.Azure,
- model: "my-deployment",
- baseURL: "https://instance.openai.azure.com/openai/deployments",
- expectedNamespace: "azure",
- },
- {
- adapter: LLMAdapter.Anthropic,
- model: "claude-sonnet-5",
- expectedNamespace: "anthropic",
- },
- {
- adapter: LLMAdapter.Bedrock,
- model: "anthropic.claude-3-5-sonnet",
- config: { region: "us-east-1" },
- expectedNamespace: "bedrock",
- },
- {
- adapter: LLMAdapter.GoogleAIStudio,
- model: "gemini-2.5-flash",
- expectedNamespace: "google",
- },
- {
- adapter: LLMAdapter.VertexAI,
- model: "gemini-2.5-flash",
- config: { location: "us-east5" },
- expectedNamespace: "google",
- },
- {
- adapter: LLMAdapter.VertexAI,
- model: "claude-sonnet-4-5@20250929",
- config: { location: "us-east5" },
- expectedNamespace: "anthropic",
- },
- ];
-
- for (const testCase of cases) {
- const decision = resolveLlmExecutionDecision({
- modelParams: makeModelParams(testCase.adapter, testCase.model),
- baseURL: testCase.baseURL,
- llmConnectionConfig: testCase.config,
- enabledAdapters: ALL_ADAPTERS,
- });
-
- expect(decision).toMatchObject({
- engine: "ai-sdk",
- adapter: testCase.adapter,
- providerOptionsName: testCase.expectedNamespace,
- });
- }
- });
-
- it("keeps chat-completions as the OpenAI default and honors useResponsesApi", () => {
- expect(
- resolveLlmExecutionDecision({
- modelParams: makeModelParams(LLMAdapter.OpenAI, "gpt-4o"),
- enabledAdapters: ALL_ADAPTERS,
- }),
- ).toMatchObject({ openAIApiMode: "chat-completions" });
-
- expect(
- resolveLlmExecutionDecision({
- modelParams: makeModelParams(LLMAdapter.OpenAI, "gpt-4o"),
- llmConnectionConfig: { useResponsesApi: true },
- enabledAdapters: ALL_ADAPTERS,
- }),
- ).toMatchObject({ openAIApiMode: "responses" });
- });
-
- it("declines on untranslatable provider options", () => {
- expect(
- resolveLlmExecutionDecision({
- modelParams: makeModelParams(LLMAdapter.Anthropic, "claude-sonnet-5", {
- providerOptions: { some_custom_param: 1 },
- }),
- enabledAdapters: ALL_ADAPTERS,
- }),
- ).toEqual({ engine: "langchain-js" });
- });
-
- it("declines Azure connections without a deployments base URL", () => {
- expect(
- resolveLlmExecutionDecision({
- modelParams: makeModelParams(LLMAdapter.Azure, "my-deployment"),
- baseURL: "https://proxy.example.com/openai",
- enabledAdapters: ALL_ADAPTERS,
- }),
- ).toEqual({ engine: "langchain-js" });
- expect(
- resolveLlmExecutionDecision({
- modelParams: makeModelParams(LLMAdapter.Azure, "my-deployment"),
- enabledAdapters: ALL_ADAPTERS,
- }),
- ).toEqual({ engine: "langchain-js" });
- });
-
- it("declines Bedrock without region config unless internal keys are used", () => {
- expect(
- resolveLlmExecutionDecision({
- modelParams: makeModelParams(LLMAdapter.Bedrock, "some-model"),
- enabledAdapters: ALL_ADAPTERS,
- }),
- ).toEqual({ engine: "langchain-js" });
-
- expect(
- resolveLlmExecutionDecision({
- modelParams: makeModelParams(LLMAdapter.Bedrock, "some-model"),
- shouldUseLangfuseAPIKey: true,
- enabledAdapters: ALL_ADAPTERS,
- }),
- ).toMatchObject({ engine: "ai-sdk" });
- });
-
- it("declines invalid Vertex locations and Claude model names", () => {
- expect(
- resolveLlmExecutionDecision({
- modelParams: makeModelParams(LLMAdapter.VertexAI, "gemini-2.5-flash"),
- llmConnectionConfig: { location: "evil.example.com/" },
- enabledAdapters: ALL_ADAPTERS,
- }),
- ).toEqual({ engine: "langchain-js" });
-
- expect(
- resolveLlmExecutionDecision({
- modelParams: makeModelParams(LLMAdapter.VertexAI, "claude/../other"),
- enabledAdapters: ALL_ADAPTERS,
- }),
- ).toEqual({ engine: "langchain-js" });
- });
-
- it("passes Vertex maxReasoningTokens into the google translation", () => {
- expect(
- resolveLlmExecutionDecision({
- modelParams: makeModelParams(LLMAdapter.VertexAI, "gemini-2.5-flash", {
- maxReasoningTokens: 2048,
- }),
- enabledAdapters: ALL_ADAPTERS,
- }),
- ).toMatchObject({
- engine: "ai-sdk",
- translatedProviderOptions: {
- thinkingConfig: { thinkingBudget: 2048, includeThoughts: true },
- },
- });
-
- // Google AI Studio ignores maxReasoningTokens, like LangChain.
- expect(
- resolveLlmExecutionDecision({
- modelParams: makeModelParams(
- LLMAdapter.GoogleAIStudio,
- "gemini-2.5-flash",
- { maxReasoningTokens: 2048 },
- ),
- enabledAdapters: ALL_ADAPTERS,
- }),
- ).toMatchObject({
- engine: "ai-sdk",
- translatedProviderOptions: undefined,
- });
- });
-
- it("drops the Vertex-Claude model override instead of declining", () => {
- expect(
- resolveLlmExecutionDecision({
- modelParams: makeModelParams(
- LLMAdapter.VertexAI,
- "claude-sonnet-4-5@20250929",
- { providerOptions: { model: "other-model" } },
- ),
- enabledAdapters: ALL_ADAPTERS,
- }),
- ).toMatchObject({
- engine: "ai-sdk",
- providerOptionsName: "anthropic",
- translatedProviderOptions: undefined,
- });
- });
-});
diff --git a/packages/shared/src/server/llm/ai-sdk/resolveLlmExecutionDecision.ts b/packages/shared/src/server/llm/ai-sdk/resolveLlmExecutionDecision.ts
deleted file mode 100644
index 2cf0e965b6..0000000000
--- a/packages/shared/src/server/llm/ai-sdk/resolveLlmExecutionDecision.ts
+++ /dev/null
@@ -1,230 +0,0 @@
-import { getCurrentSpan } from "../../instrumentation";
-import {
- BedrockConfigSchema,
- OpenAIConfigSchema,
- VertexAIConfigSchema,
-} from "../../../interfaces/customLLMProviderConfigSchemas";
-import type { LLMConnectionConfig } from "../../../interfaces/customLLMProviderConfigSchemas";
-import { logger } from "../../logger";
-import { LLMAdapter, type ModelParams } from "../types";
-import { translateAnthropicProviderOptions } from "./providers/anthropic";
-import { translateAzureBaseURL } from "./providers/azure";
-import { translateBedrockProviderOptions } from "./providers/bedrock";
-import { translateGoogleProviderOptions } from "./providers/google";
-import {
- translateOpenAIProviderOptions,
- type OpenAIApiMode,
-} from "./providers/openai";
-import type { TranslatedProviderOptions } from "./providers/types";
-import {
- assertValidAnthropicVertexModelName,
- assertValidVertexLocation,
- isClaudeModel,
-} from "./providers/vertex";
-
-export type AiSdkEngineDecision = {
- engine: "ai-sdk";
- adapter: LLMAdapter;
- /** Key under `providerOptions` the AI SDK model reads its options from. */
- providerOptionsName: string;
- translatedProviderOptions?: Record<string, unknown>;
- /** Only set for the OpenAI adapter. */
- openAIApiMode?: OpenAIApiMode;
-};
-
-export type LlmExecutionDecision =
- | AiSdkEngineDecision
- | {
- engine: "langchain-js";
- };
-
-const LANGCHAIN_DECISION = { engine: "langchain-js" } as const;
-
-/**
- * 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` (values are `LLMAdapter` enum
- * strings) 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.
- *
- * Declines also cover config shapes the LangChain path rejects with its
- * canonical errors (invalid Vertex locations, malformed Bedrock config, ...)
- * so misconfigurations keep surfacing identically.
- */
-export function resolveLlmExecutionDecision(params: {
- modelParams: ModelParams;
- llmConnectionConfig?: LLMConnectionConfig | null;
- baseURL?: string | null;
- shouldUseLangfuseAPIKey?: boolean;
- enabledAdapters: readonly string[];
-}): LlmExecutionDecision {
- const {
- modelParams,
- llmConnectionConfig,
- baseURL,
- shouldUseLangfuseAPIKey,
- enabledAdapters,
- } = params;
- const { adapter, model, providerOptions } = modelParams;
-
- if (!enabledAdapters.includes(adapter)) {
- return LANGCHAIN_DECISION;
- }
-
- const decline = (reason: string): typeof LANGCHAIN_DECISION => {
- logger.warn(`AI SDK engine declined for adapter ${adapter}: ${reason}`);
- return LANGCHAIN_DECISION;
- };
- const declineForOptions = (
- translated: Extract<TranslatedProviderOptions, { ok: false }>,
- ) =>
- decline(
- `cannot translate provider options: ${translated.unknownKeys.join(",")}`,
- );
-
- switch (adapter) {
- case LLMAdapter.OpenAI: {
- const translated = translateOpenAIProviderOptions(providerOptions);
- if (!translated.ok) return declineForOptions(translated);
-
- const openAIConfig = OpenAIConfigSchema.parse(llmConnectionConfig ?? {});
-
- return {
- engine: "ai-sdk",
- adapter,
- providerOptionsName: "openai",
- translatedProviderOptions: translated.value,
- // 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",
- };
- }
-
- case LLMAdapter.Azure: {
- const baseUrlTranslation = translateAzureBaseURL(baseURL);
- if (!baseUrlTranslation.ok) return decline(baseUrlTranslation.reason);
-
- // Azure deployments speak the OpenAI Chat Completions body, so provider
- // options share the OpenAI translation (namespaced under `azure`).
- const translated = translateOpenAIProviderOptions(providerOptions);
- if (!translated.ok) return declineForOptions(translated);
-
- return {
- engine: "ai-sdk",
- adapter,
- providerOptionsName: "azure",
- translatedProviderOptions: translated.value,
- };
- }
-
- case LLMAdapter.Anthropic: {
- const translated = translateAnthropicProviderOptions(providerOptions);
- if (!translated.ok) return declineForOptions(translated);
-
- return {
- engine: "ai-sdk",
- adapter,
- providerOptionsName: "anthropic",
- translatedProviderOptions: translated.value,
- };
- }
-
- case LLMAdapter.Bedrock: {
- if (
- !shouldUseLangfuseAPIKey &&
- !BedrockConfigSchema.safeParse(llmConnectionConfig).success
- ) {
- return decline("missing or invalid Bedrock region config");
- }
-
- const translated = translateBedrockProviderOptions(providerOptions);
- if (!translated.ok) return declineForOptions(translated);
-
- return {
- engine: "ai-sdk",
- adapter,
- providerOptionsName: "bedrock",
- translatedProviderOptions: translated.value,
- };
- }
-
- case LLMAdapter.GoogleAIStudio: {
- // Note: `maxReasoningTokens` is intentionally not passed — the LangChain
- // engine only forwards it for Vertex AI.
- const translated = translateGoogleProviderOptions({
- providerOptions,
- model,
- });
- if (!translated.ok) return declineForOptions(translated);
-
- return {
- engine: "ai-sdk",
- adapter,
- providerOptionsName: "google",
- translatedProviderOptions: translated.value,
- };
- }
-
- case LLMAdapter.VertexAI: {
- const parsedConfig = llmConnectionConfig
- ? VertexAIConfigSchema.safeParse(llmConnectionConfig)
- : undefined;
- if (parsedConfig && !parsedConfig.success) {
- return decline("invalid Vertex AI config");
- }
- try {
- assertValidVertexLocation(parsedConfig?.data.location);
- if (isClaudeModel(model)) assertValidAnthropicVertexModelName(model);
- } catch (e) {
- return decline(e instanceof Error ? e.message : String(e));
- }
-
- const translated = isClaudeModel(model)
- ? translateAnthropicProviderOptions(providerOptions, {
- dropModelOverride: true,
- })
- : translateGoogleProviderOptions({
- providerOptions,
- model,
- maxReasoningTokens: modelParams.maxReasoningTokens,
- });
- if (!translated.ok) return declineForOptions(translated);
-
- return {
- engine: "ai-sdk",
- adapter,
- providerOptionsName: isClaudeModel(model) ? "anthropic" : "google",
- translatedProviderOptions: translated.value,
- };
- }
-
- default: {
- const _exhaustiveCheck: never = adapter;
- logger.warn(`Unknown adapter for engine dispatch: ${_exhaustiveCheck}`);
- return LANGCHAIN_DECISION;
- }
- }
-}
-
-/**
- * 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.adapter);
- if (decision.openAIApiMode) {
- span.setAttribute("langfuse.llm.openai.api_mode", decision.openAIApiMode);
- }
- }
-}
diff --git a/packages/shared/src/server/llm/ai-sdk/telemetry.ts b/packages/shared/src/server/llm/ai-sdk/telemetry.ts
index 8c1a7bc64b..fcd7d73baf 100644
--- a/packages/shared/src/server/llm/ai-sdk/telemetry.ts
+++ b/packages/shared/src/server/llm/ai-sdk/telemetry.ts
@@ -43,8 +43,7 @@ export type AiSdkTelemetryCapture = {
/**
* 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.
+ * variable mapping for experiment run items.
*/
setRootOutput: (output: unknown) => void;
/**
@@ -75,13 +74,12 @@ export type AiSdkTelemetryCapture = {
* 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
+ * pipeline materializes the linkage required for 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.
+ * langfuse-prefixed (the eval-loop safeguard) or when the trace ID is not a
+ * valid W3C trace ID.
*/
export function createAiSdkTelemetryCapture(params: {
traceSinkParams: TraceSinkParams;
@@ -178,8 +176,7 @@ export function createAiSdkTelemetryCapture(params: {
const promptAttributes = traceSinkParams.prompt
? {
- // Link the LLM generation spans to the resolved Langfuse prompt,
- // mirroring prepareInternalTraceEvents on the LangChain path.
+ // Link the LLM generation spans to the resolved Langfuse prompt.
[LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_NAME]:
traceSinkParams.prompt.name,
[LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_VERSION]:
@@ -190,8 +187,8 @@ export function createAiSdkTelemetryCapture(params: {
const otelIntegration = createGenerationSpanTelemetry({
tracer,
attributes: {
- // Experiment linkage goes on every span, matching the LangChain path
- // where buildInternalTraceEventInputs tags all event records.
+ // Experiment linkage goes on every span so every materialized event
+ // remains associated with the run item root.
...(experimentAttributes ?? {}),
...(promptAttributes ?? {}),
[LangfuseOtelSpanAttributes.TRACE_NAME]: traceSinkParams.traceName,
@@ -400,9 +397,8 @@ function safeJsonStringify(value: unknown): string {
}
/**
* 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`.
+ * attributes that `OtelIngestionProcessor.extractExperimentFields` reads to
+ * produce experiment-linked event records.
*/
function buildExperimentAttributes(
experimentContext: InternalTraceExperimentContext,
diff --git a/packages/shared/src/server/llm/ai-sdk/telemetryIntegration.test.ts b/packages/shared/src/server/llm/ai-sdk/telemetryIntegration.test.ts
index 0fd316a76b..5097e473ca 100644
--- a/packages/shared/src/server/llm/ai-sdk/telemetryIntegration.test.ts
+++ b/packages/shared/src/server/llm/ai-sdk/telemetryIntegration.test.ts
@@ -13,6 +13,7 @@ import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-ho
import { MockLanguageModelV4 } from "ai/test";
import { createOpenAI } from "@ai-sdk/openai";
+import { encrypt } from "../../../encryption";
import {
ChatMessage,
ChatMessageRole,
@@ -21,8 +22,7 @@ import {
type ModelParams,
type TraceSinkParams,
} from "../types";
-import { executeAiSdkCompletion } from "./executeAiSdkCompletion";
-import type { AiSdkEngineDecision } from "./resolveLlmExecutionDecision";
+import { generateLLMText, mapLegacyLLMCompletionParams } from "../llmText";
const publishToOtelIngestionQueue = vi.fn().mockResolvedValue(undefined);
@@ -57,13 +57,6 @@ const modelParams: ModelParams = {
max_tokens: 128,
};
-const decision: AiSdkEngineDecision = {
- engine: "ai-sdk",
- adapter: LLMAdapter.OpenAI,
- providerOptionsName: "openai",
- openAIApiMode: "chat-completions",
-};
-
// 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
@@ -118,18 +111,17 @@ beforeEach(() => {
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,
- createFetch: () => globalThis.fetch,
- decision,
- traceSinkParams,
+ const result = await generateLLMText({
+ ...mapLegacyLLMCompletionParams({
+ messages,
+ modelParams,
+ connection: { secretKey: encrypt("sk-test") },
+ }),
+ timeout: 10_000,
+ trace: traceSinkParams,
});
- expect(result).toBe("Hello there");
+ expect(result.text).toBe("Hello there");
expect(publishToOtelIngestionQueue).toHaveBeenCalledTimes(1);
const resourceSpans = publishToOtelIngestionQueue.mock.calls[0][0];
@@ -218,15 +210,14 @@ describe("AI SDK telemetry integration", () => {
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,
- createFetch: () => globalThis.fetch,
- decision,
- traceSinkParams: {
+ const result = await generateLLMText({
+ ...mapLegacyLLMCompletionParams({
+ messages,
+ modelParams,
+ connection: { secretKey: encrypt("sk-test") },
+ }),
+ timeout: 10_000,
+ trace: {
targetProjectId: "project-1",
traceId: experimentTraceId,
traceName: "dataset-run-item-abc12",
@@ -246,7 +237,7 @@ describe("AI SDK telemetry integration", () => {
},
});
- expect(result).toBe("Hello there");
+ expect(result.text).toBe("Hello there");
expect(publishToOtelIngestionQueue).toHaveBeenCalledTimes(1);
const resourceSpans = publishToOtelIngestionQueue.mock.calls[0][0];
diff --git a/packages/shared/src/server/llm/completionErrorMapping.ts b/packages/shared/src/server/llm/completionErrorMapping.ts
index 166df92a15..803f1287d5 100644
--- a/packages/shared/src/server/llm/completionErrorMapping.ts
+++ b/packages/shared/src/server/llm/completionErrorMapping.ts
@@ -1,5 +1,3 @@
-import { ContextOverflowError } from "@langchain/core/errors";
-
import { LLMCompletionError } from "./errors";
const NON_RETRYABLE_LLM_ERROR_PATTERNS = [
@@ -121,10 +119,9 @@ function extractCleanErrorMessage(rawMessage: string): string {
}
/**
- * 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.
+ * Maps any error thrown during an AI SDK LLM completion to an
+ * `LLMCompletionError` with a clean user-visible message and the shared
+ * retryability classification used by eval retry budgets.
*/
export function mapToLLMCompletionError(e: unknown): LLMCompletionError {
if (e instanceof LLMCompletionError) return e;
@@ -150,9 +147,7 @@ export function mapToLLMCompletionError(e: unknown): LLMCompletionError {
// - Non-retryable patterns: not retryable
let isRetryable = false;
- if (ContextOverflowError.isInstance(e)) {
- isRetryable = false;
- } else if (
+ if (
e instanceof Error &&
(e.name === "InsufficientQuotaError" || e.name === "ThrottlingException")
) {
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.ts
deleted file mode 100644
index 2afe7ba1ab..0000000000
--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts
+++ /dev/null
@@ -1,956 +0,0 @@
-import { type ZodType, z } from "zod";
-
-import {
- AnthropicVertex,
- type ClientOptions as AnthropicVertexClientOptions,
-} from "@anthropic-ai/vertex-sdk";
-import { ChatAnthropic, ChatAnthropicInput } from "@langchain/anthropic";
-import { ChatGoogle } from "@langchain/google";
-import { ChatBedrockConverse } from "@langchain/aws";
-import {
- AIMessage,
- AIMessageChunk,
- BaseMessage,
- ContentBlock,
- HumanMessage,
- SystemMessage,
- ToolMessage,
-} from "@langchain/core/messages";
-import {
- BytesOutputParser,
- StringOutputParser,
-} from "@langchain/core/output_parsers";
-import { IterableReadableStream } from "@langchain/core/utils/stream";
-import { ChatOpenAI, AzureChatOpenAI } from "@langchain/openai";
-import { env } from "../../env";
-import GCPServiceAccountKeySchema, {
- BedrockAccessKeysSchema,
- BedrockConfigSchema,
- BedrockCredentialSchema,
- LLMConnectionConfig,
- OpenAIConfigSchema,
- VertexAIConfigSchema,
- BEDROCK_USE_DEFAULT_CREDENTIALS,
- VERTEXAI_USE_DEFAULT_CREDENTIALS,
-} from "../../interfaces/customLLMProviderConfigSchemas";
-import {
- ChatMessage,
- ChatMessageRole,
- ChatMessageType,
- isOpenAIReasoningModel,
- LLMAdapter,
- LLMJSONSchema,
- LLMToolDefinition,
- ModelParams,
- OpenAIModel,
- PROVIDERS_WITH_REQUIRED_USER_MESSAGE,
- ToolCallResponse,
- ToolCallResponseSchema,
- TraceSinkParams,
-} from "./types";
-import type { BaseCallbackHandler } from "@langchain/core/callbacks/base";
-import { ProxyAgent } from "undici";
-import { GoogleAuth, type GoogleAuthOptions } from "google-auth-library";
-import { getInternalTracingHandler } from "./getInternalTracingHandler";
-import { decrypt } from "../../encryption";
-import {
- decryptAndParseExtraHeaders,
- executeWithRuntimeTimeout,
- processOpenAIBaseURL,
- RUNTIME_TIMEOUT_ADAPTERS,
-} from "./utils";
-import { logger } from "../logger";
-import { executeAiSdkCompletion } from "./ai-sdk/executeAiSdkCompletion";
-import {
- assertValidAnthropicVertexModelName,
- assertValidVertexLocation,
- isClaudeModel,
-} from "./ai-sdk/providers/vertex";
-import {
- recordLlmExecutionDecision,
- resolveLlmExecutionDecision,
-} from "./ai-sdk/resolveLlmExecutionDecision";
-import { mapToLLMCompletionError } from "./completionErrorMapping";
-import {
- createSecureGoogleAIStudioApiClient,
- createSecureVertexAIApiClient,
-} from "./googleSecureApiClient";
-import { createSecureLlmFetch } from "./secureLlmFetch";
-
-export type CompletionWithReasoning = { text: string; reasoning?: string };
-type SplitAIMessageContent = {
- text: string;
- // Standard `ContentBlock` shape exposed by `AIMessage#contentBlocks`, stripped
- // of `tool_call` and `reasoning` blocks. A plain string is preserved when the
- // upstream message carried plain-string content.
- contentWithoutThinking: string | Array<ContentBlock.Standard>;
- reasoning?: string;
-};
-
-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";
-const VERTEX_AI_AUTH_HEADER = "authorization";
-const VERTEX_AI_AUTH_SCOPES = [
- "https://www.googleapis.com/auth/cloud-platform",
-];
-
-// Adapters whose models can return separate reasoning content. We route their
-// responses through `AIMessage#contentBlocks`, which normalizes provider-specific
-// shapes (Bedrock `reasoning_content`, Gemini `{ thought: true }` text parts, etc.)
-// into the documented `{ type: "reasoning", reasoning: string }` standard block.
-const ADAPTERS_WITH_REASONING_SUPPORT = new Set<LLMAdapter>([
- LLMAdapter.Bedrock,
- LLMAdapter.VertexAI,
- LLMAdapter.GoogleAIStudio,
-]);
-
-function adapterSupportsReasoning(adapter: LLMAdapter): boolean {
- return ADAPTERS_WITH_REASONING_SUPPORT.has(adapter);
-}
-
-const ANTHROPIC_ALWAYS_ADAPTIVE_THINKING_MODELS = [
- "claude-fable-5",
- "claude-mythos-5",
-] as const;
-
-const ANTHROPIC_SAMPLING_PARAM_NORMALIZATION_MODELS = [
- "claude-sonnet-5",
- "claude-fable-5",
- "claude-mythos-5",
- "claude-opus-4-8",
- "claude-opus-4-7",
- "claude-sonnet-4-6",
- "claude-sonnet-4-5",
- "claude-opus-4-1",
- "claude-opus-4-5",
- "claude-opus-4-6",
- "claude-haiku-4-5",
-] as const;
-
-function isAnthropicAlwaysAdaptiveThinkingModel(modelName: string): boolean {
- return ANTHROPIC_ALWAYS_ADAPTIVE_THINKING_MODELS.some((model) =>
- modelName.includes(model),
- );
-}
-
-function shouldNormalizeAnthropicSamplingParams(modelName: string): boolean {
- return ANTHROPIC_SAMPLING_PARAM_NORMALIZATION_MODELS.some((model) =>
- modelName.includes(model),
- );
-}
-
-function getAnthropicInvocationKwargs(modelParams: ModelParams) {
- if (!isAnthropicAlwaysAdaptiveThinkingModel(modelParams.model)) {
- return modelParams.providerOptions;
- }
-
- return {
- // @langchain/anthropic currently defaults ChatAnthropic.thinking to
- // { type: "disabled" } and serializes it into every request.
- // Claude Fable 5 and Claude Mythos 5 reject that explicit disabled
- // mode because thinking defaults to adaptive when the field is
- // omitted. Newer ChatAnthropic versions might fix this default, but
- // remove this guard only after a developer has verified that the
- // pinned/newer version no longer sends thinking.disabled by default.
- thinking: undefined,
- ...modelParams.providerOptions,
- };
-}
-
-function normalizeAnthropicSamplingParams(
- chatModel: ChatAnthropic,
- modelParams: ModelParams,
-) {
- if (!shouldNormalizeAnthropicSamplingParams(modelParams.model)) {
- return;
- }
-
- if (chatModel.topP === -1) {
- chatModel.topP = undefined;
- }
-
- // TopP and temperature cannot be specified both,
- // but Langchain is setting placeholder values despite that.
- if (
- modelParams.temperature !== undefined &&
- modelParams.top_p === undefined
- ) {
- chatModel.topP = undefined;
- }
-
- if (
- modelParams.top_p !== undefined &&
- modelParams.temperature === undefined
- ) {
- chatModel.temperature = undefined;
- }
-}
-
-function shouldNormalizeContentBlocks(modelParams: ModelParams): boolean {
- return (
- adapterSupportsReasoning(modelParams.adapter) ||
- (modelParams.adapter === LLMAdapter.Anthropic &&
- isAnthropicAlwaysAdaptiveThinkingModel(modelParams.model))
- );
-}
-
-const transformSystemMessageToUserMessage = (
- messages: ChatMessage[],
-): BaseMessage[] => {
- const safeContent =
- typeof messages[0].content === "string"
- ? messages[0].content
- : JSON.stringify(messages[0].content);
- return [new HumanMessage(safeContent)];
-};
-
-const googleProviderOptionsSchema = z
- .object({
- thinkingBudget: z.number().optional(),
- thinkingLevel: z.string().optional(), // intentionally loose as types differ / may be extended in the future and are passed through to API
- })
- .optional();
-
-// For using Bedrock API key in Bearer token format
-const createBedrockBearerAuth = (token: string) => ({
- clientOptions: {
- token: { token },
- authSchemePreference: ["httpBearerAuth"],
- },
-});
-
-export function resolveBedrockAuth(params: {
- secretKey: string;
- allowDefaultCredentials: boolean;
-}): {
- credentials?: z.infer<typeof BedrockAccessKeysSchema>;
- clientOptions?: {
- token: { token: string };
- authSchemePreference: string[];
- };
-} {
- const { secretKey, allowDefaultCredentials } = params;
-
- if (
- secretKey === BEDROCK_USE_DEFAULT_CREDENTIALS &&
- allowDefaultCredentials
- ) {
- return {};
- }
-
- try {
- const parsedCredential = BedrockCredentialSchema.parse(
- JSON.parse(secretKey),
- );
-
- if ("apiKey" in parsedCredential) {
- return createBedrockBearerAuth(parsedCredential.apiKey);
- }
-
- return {
- credentials: parsedCredential,
- };
- } catch {
- throw new Error(
- "Invalid Bedrock credentials. Expected AWS access key JSON or a Bedrock API key.",
- );
- }
-}
-
-type ProcessTracedEvents = () => Promise<void>;
-
-type LLMCompletionParams = {
- messages: ChatMessage[];
- modelParams: ModelParams;
- llmConnection: {
- secretKey: string;
- extraHeaders?: string | null;
- baseURL?: string | null;
- config?: LLMConnectionConfig | null;
- };
- structuredOutputSchema?: ZodType | LLMJSONSchema;
- callbacks?: BaseCallbackHandler[];
- maxRetries?: number;
- traceSinkParams?: TraceSinkParams;
- shouldUseLangfuseAPIKey?: boolean;
-};
-
-type FetchLLMCompletionParams = LLMCompletionParams & {
- streaming: boolean;
- tools?: LLMToolDefinition[];
-};
-
-export async function fetchLLMCompletion(
- params: LLMCompletionParams & {
- streaming: true;
- },
-): Promise<IterableReadableStream<Uint8Array>>;
-
-export async function fetchLLMCompletion(
- params: LLMCompletionParams & {
- streaming: false;
- },
-): Promise<string | CompletionWithReasoning>;
-
-export async function fetchLLMCompletion(
- params: LLMCompletionParams & {
- streaming: false;
- structuredOutputSchema: ZodType;
- },
-): Promise<Record<string, unknown>>;
-
-export async function fetchLLMCompletion(
- params: LLMCompletionParams & {
- streaming: false;
- tools: LLMToolDefinition[];
- },
-): Promise<ToolCallResponse & { reasoning?: string }>;
-
-export async function fetchLLMCompletion(
- params: FetchLLMCompletionParams,
-): Promise<
- | string
- | CompletionWithReasoning
- | IterableReadableStream<Uint8Array>
- | Record<string, unknown>
- | ToolCallResponse
-> {
- const {
- messages,
- tools,
- modelParams,
- streaming,
- callbacks,
- llmConnection,
- maxRetries,
- traceSinkParams,
- shouldUseLangfuseAPIKey = false,
- } = params;
-
- const { baseURL, config } = llmConnection;
- const apiKey = decrypt(llmConnection.secretKey); // the apiKey must never be printed to the console
- const 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({
- modelParams,
- llmConnectionConfig: config,
- baseURL,
- shouldUseLangfuseAPIKey,
- 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,
- llmConnectionConfig: config,
- shouldUseLangfuseAPIKey,
- maxRetries,
- timeoutMs,
- createFetch: secureLlmFetch,
- decision: executionDecision,
- traceSinkParams,
- });
- }
-
- let finalCallbacks: BaseCallbackHandler[] | undefined = callbacks ?? [];
- let processTracedEvents: ProcessTracedEvents = () => Promise.resolve();
-
- if (traceSinkParams) {
- // 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,
- },
- );
- } else {
- const internalTracingHandler = getInternalTracingHandler(traceSinkParams);
- processTracedEvents = internalTracingHandler.processTracedEvents;
-
- finalCallbacks.push(internalTracingHandler.handler);
- }
- }
-
- finalCallbacks = finalCallbacks.length > 0 ? finalCallbacks : undefined;
-
- // Helper function to safely stringify content
- const safeStringify = (content: any): string => {
- try {
- return JSON.stringify(content);
- } catch {
- return "[Unserializable content]";
- }
- };
-
- let finalMessages: BaseMessage[];
- // Some providers require at least 1 user message
- if (
- messages.length === 1 &&
- PROVIDERS_WITH_REQUIRED_USER_MESSAGE.includes(modelParams.adapter)
- ) {
- // Ensure provider schema compliance
- finalMessages = transformSystemMessageToUserMessage(messages);
- } else {
- finalMessages = messages.map((message, idx) => {
- // For arbitrary content types, convert to string safely
- const safeContent =
- typeof message.content === "string"
- ? message.content
- : safeStringify(message.content);
-
- if (message.role === ChatMessageRole.User)
- return new HumanMessage(safeContent);
- if (
- message.role === ChatMessageRole.System ||
- message.role === ChatMessageRole.Developer
- )
- return idx === 0
- ? new SystemMessage(safeContent)
- : new HumanMessage(safeContent);
-
- if (message.type === ChatMessageType.ToolResult) {
- return new ToolMessage({
- content: safeContent,
- tool_call_id: message.toolCallId,
- });
- }
-
- return new AIMessage({
- content: safeContent,
- tool_calls:
- message.type === ChatMessageType.AssistantToolCall
- ? (message.toolCalls as any)
- : undefined,
- });
- });
- }
-
- finalMessages = finalMessages.filter(
- (m) => m.content.length > 0 || "tool_calls" in m,
- );
-
- let chatModel: ChatOpenAI | ChatAnthropic | ChatBedrockConverse | ChatGoogle;
- let usesOpenAIResponsesApi = false;
- if (modelParams.adapter === LLMAdapter.Anthropic) {
- const chatOptions: ChatAnthropicInput = {
- anthropicApiKey: apiKey,
- anthropicApiUrl: baseURL ?? undefined,
- model: modelParams.model,
- maxTokens: modelParams.max_tokens,
- callbacks: finalCallbacks,
- clientOptions: {
- maxRetries,
- defaultHeaders: extraHeaders,
- timeout: timeoutMs,
- fetch: secureLlmFetch("Anthropic LLM base URL", [
- ANTHROPIC_API_KEY_HEADER,
- ]),
- },
- temperature: modelParams.temperature,
- topP: modelParams.top_p,
- invocationKwargs: getAnthropicInvocationKwargs(modelParams),
- };
-
- chatModel = new ChatAnthropic(chatOptions);
- normalizeAnthropicSamplingParams(chatModel, modelParams);
- } else if (modelParams.adapter === LLMAdapter.OpenAI) {
- const processedBaseURL = processOpenAIBaseURL({
- url: baseURL,
- modelName: modelParams.model,
- });
- const openAIConfig = OpenAIConfigSchema.parse(config ?? {});
- usesOpenAIResponsesApi = openAIConfig.useResponsesApi;
-
- chatModel = new ChatOpenAI({
- apiKey,
- model: modelParams.model,
- temperature: modelParams.temperature,
- ...(isOpenAIReasoningModel(modelParams.model as OpenAIModel)
- ? { maxCompletionTokens: modelParams.max_tokens }
- : { maxTokens: modelParams.max_tokens }),
- topP: modelParams.top_p,
- streamUsage: false, // https://github.com/langchain-ai/langchainjs/issues/6533
- callbacks: finalCallbacks,
- maxRetries,
- configuration: {
- baseURL: processedBaseURL,
- timeout: timeoutMs,
- defaultHeaders: extraHeaders,
- fetch: secureLlmFetch("OpenAI LLM base URL"),
- },
- useResponsesApi: openAIConfig.useResponsesApi,
- modelKwargs: modelParams.providerOptions,
- timeout: timeoutMs,
- });
- } else if (modelParams.adapter === LLMAdapter.Azure) {
- chatModel = new AzureChatOpenAI({
- azureOpenAIApiKey: apiKey,
- azureOpenAIBasePath: baseURL ?? undefined,
- azureOpenAIApiDeploymentName: modelParams.model,
- azureOpenAIApiVersion: "2025-02-01-preview",
- temperature: modelParams.temperature,
- maxTokens: modelParams.max_tokens,
- topP: modelParams.top_p,
- callbacks: finalCallbacks,
- maxRetries,
- timeout: timeoutMs,
- configuration: {
- timeout: timeoutMs,
- defaultHeaders: extraHeaders,
- fetch: secureLlmFetch("Azure OpenAI LLM base URL", [
- AZURE_OPENAI_API_KEY_HEADER,
- ]),
- },
- modelKwargs: modelParams.providerOptions,
- });
- } else if (modelParams.adapter === LLMAdapter.Bedrock) {
- const { region } = shouldUseLangfuseAPIKey
- ? { region: env.LANGFUSE_AWS_BEDROCK_REGION }
- : BedrockConfigSchema.parse(config);
-
- // Handle both explicit credentials and default provider chain
- // Only allow default provider chain in self-hosted or internal AI features
- const isSelfHosted = !isLangfuseCloud;
- const { credentials, clientOptions } = resolveBedrockAuth({
- secretKey: apiKey,
- allowDefaultCredentials: isSelfHosted || shouldUseLangfuseAPIKey,
- });
-
- chatModel = new ChatBedrockConverse({
- model: modelParams.model,
- region,
- credentials,
- clientOptions,
- temperature: modelParams.temperature,
- maxTokens: modelParams.max_tokens,
- topP: modelParams.top_p,
- callbacks: finalCallbacks,
- maxRetries,
- timeout: timeoutMs,
- additionalModelRequestFields: modelParams.providerOptions as any,
- });
- } else if (modelParams.adapter === LLMAdapter.VertexAI) {
- const { location } = config
- ? VertexAIConfigSchema.parse(config)
- : { location: undefined };
-
- // location flows into the Vertex host both SDKs build from it
- // (https://${location}-aiplatform.googleapis.com), so reject anything that
- // could reshape that host and exfiltrate the Google OAuth bearer token.
- assertValidVertexLocation(location);
-
- // Handle both explicit credentials and default provider chain (ADC)
- // Only allow default provider chain in self-hosted or internal AI features
- const shouldUseDefaultCredentials =
- apiKey === VERTEXAI_USE_DEFAULT_CREDENTIALS && !isLangfuseCloud;
-
- // When using ADC, authOptions must be undefined to use google-auth-library's default credential chain
- // This supports: GKE Workload Identity, Cloud Run service accounts, GCE metadata service, gcloud auth
- // Security: We intentionally ignore user-provided projectId when using ADC to prevent
- // privilege escalation attacks where users could access other GCP projects via the server's credentials
- const serviceAccountKey = shouldUseDefaultCredentials
- ? undefined
- : GCPServiceAccountKeySchema.parse(JSON.parse(apiKey));
- const authOptions: GoogleAuthOptions | undefined = serviceAccountKey
- ? {
- credentials: serviceAccountKey,
- projectId: serviceAccountKey.project_id,
- }
- : undefined; // Always use ADC auto-detection, never allow user-specified projectId
-
- // Requests time out after 60 seconds for both public and private endpoints by default
- // Reference: https://cloud.google.com/vertex-ai/docs/predictions/get-online-predictions#send-request
- if (isClaudeModel(modelParams.model)) {
- assertValidAnthropicVertexModelName(modelParams.model);
- const anthropicVertexGoogleAuth = new GoogleAuth({
- ...authOptions,
- scopes: authOptions?.scopes ?? VERTEX_AI_AUTH_SCOPES,
- });
- const anthropicVertexRegion = location ?? "global";
-
- // LangChain keeps Claude-on-Vertex on ChatAnthropic + AnthropicVertex
- // while @langchain/google is still focused on Gemini/Gemma.
- // https://github.com/langchain-ai/langchain-google/discussions/1422
- chatModel = new ChatAnthropic({
- model: modelParams.model,
- temperature: modelParams.temperature,
- maxTokens: modelParams.max_tokens,
- topP: modelParams.top_p,
- callbacks: finalCallbacks,
- maxRetries,
- invocationKwargs: (() => {
- const { model: _ignoredModelOverride, ...sanitized } =
- (getAnthropicInvocationKwargs(modelParams) ?? {}) as Record<
- string,
- unknown
- >;
- return sanitized;
- })(),
- clientOptions: {
- timeout: timeoutMs,
- defaultHeaders: extraHeaders,
- fetch: secureLlmFetch("Anthropic Vertex AI endpoint", [
- VERTEX_AI_AUTH_HEADER,
- ]),
- },
- createClient: (options) =>
- new AnthropicVertex({
- ...options,
- // The base Anthropic SDK defaults apiKey/authToken from
- // ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN when undefined, which on
- // Vertex would ship as headers that win over Google's OAuth token
- // and leak the operator's Anthropic credentials. Force both null so
- // auth comes only from googleAuth (the vertex-sdk type omits these
- // fields though the base client still honors them).
- ...({ apiKey: null, authToken: null } as {
- apiKey: null;
- authToken: null;
- }),
- region: anthropicVertexRegion,
- projectId: serviceAccountKey?.project_id,
- // @anthropic-ai/vertex-sdk depends on its own google-auth-library
- // copy, so the structurally compatible GoogleAuth instance needs an
- // explicit cast across duplicate private class declarations.
- googleAuth: anthropicVertexGoogleAuth as unknown as NonNullable<
- AnthropicVertexClientOptions["googleAuth"]
- >,
- maxRetries: 0,
- }),
- });
- normalizeAnthropicSamplingParams(chatModel, modelParams);
- } else {
- const googleProviderOptions = googleProviderOptionsSchema.parse(
- modelParams.providerOptions,
- );
-
- chatModel = new ChatGoogle({
- model: modelParams.model,
- temperature: modelParams.temperature,
- maxOutputTokens: modelParams.max_tokens,
- topP: modelParams.top_p,
- callbacks: finalCallbacks,
- maxRetries,
- location,
- vertexai: true,
- apiClient: createSecureVertexAIApiClient({
- authOptions,
- dispatcher: proxyDispatcher,
- }),
- ...(modelParams.maxReasoningTokens !== undefined && {
- maxReasoningTokens: modelParams.maxReasoningTokens,
- }),
- ...((googleProviderOptions as any) ?? {}), // Typecast as thinkingLevel is intentionally looser typed
- });
- }
- } else if (modelParams.adapter === LLMAdapter.GoogleAIStudio) {
- const googleProviderOptions = googleProviderOptionsSchema.parse(
- modelParams.providerOptions,
- );
-
- chatModel = new ChatGoogle({
- model: modelParams.model,
- temperature: modelParams.temperature,
- maxOutputTokens: modelParams.max_tokens,
- topP: modelParams.top_p,
- callbacks: finalCallbacks,
- maxRetries,
- apiKey,
- apiClient: createSecureGoogleAIStudioApiClient({
- apiKey,
- baseURL,
- dispatcher: proxyDispatcher,
- }),
- ...((googleProviderOptions as any) ?? {}), // Typecast as thinkingLevel is intentionally looser typed
- });
- } else {
- const _exhaustiveCheck: never = modelParams.adapter;
- throw new Error(
- `This model provider is not supported: ${_exhaustiveCheck}`,
- );
- }
-
- const runConfig = {
- callbacks: finalCallbacks,
- runId: traceSinkParams?.traceId,
- runName: traceSinkParams?.traceName,
- metadata: traceSinkParams?.metadata,
- };
-
- const runtimeTimeoutEnabled = RUNTIME_TIMEOUT_ADAPTERS.has(
- modelParams.adapter,
- );
- const runtimeTimeoutController = runtimeTimeoutEnabled
- ? new AbortController()
- : undefined;
- const runConfigWithTimeout = runtimeTimeoutController
- ? {
- ...runConfig,
- signal: runtimeTimeoutController.signal,
- }
- : runConfig;
-
- const supportsReasoning = adapterSupportsReasoning(modelParams.adapter);
- const shouldNormalizeModelContentBlocks =
- shouldNormalizeContentBlocks(modelParams);
- const shouldNormalizeStreamingContentBlocks =
- shouldNormalizeModelContentBlocks || usesOpenAIResponsesApi;
-
- try {
- // Important: await all generations in the try block as otherwise `processTracedEvents` will run too early in finally block
- if (params.structuredOutputSchema) {
- // Thinking-capable adapters may produce reasoning blocks that corrupt JSON schema
- // parsing. Force function calling so the parser reads from tool_calls instead.
- const structuredOutputSchema = params.structuredOutputSchema;
- const structuredOutputConfig = supportsReasoning
- ? { method: "functionCalling" as const }
- : undefined;
- const createStructuredOutputModel = () => {
- const isAnthropicChatModel =
- modelParams.adapter === LLMAdapter.Anthropic ||
- (modelParams.adapter === LLMAdapter.VertexAI &&
- isClaudeModel(modelParams.model));
-
- if (
- !isAnthropicChatModel ||
- !isAnthropicAlwaysAdaptiveThinkingModel(modelParams.model)
- ) {
- return (chatModel as ChatOpenAI).withStructuredOutput(
- structuredOutputSchema,
- structuredOutputConfig,
- );
- }
-
- const anthropicChatModel = chatModel as ChatAnthropic & {
- thinking: ChatAnthropicInput["thinking"];
- };
- const originalThinking = anthropicChatModel.thinking;
-
- try {
- // Keep LangChain's structured-output decision in sync with
- // Anthropic's Fable/Mythos semantics. In @langchain/anthropic 1.3.26,
- // ChatAnthropic defaults this internal field to { type: "disabled" }.
- // withStructuredOutput() reads that field before request serialization:
- // disabled thinking makes it force tool_choice, while adaptive
- // thinking avoids forced tool use. Fable/Mythos treat an omitted
- // thinking field as always-on adaptive thinking, and Anthropic rejects
- // adaptive thinking combined with forced tool use. Temporarily mirror
- // the adaptive state only while constructing the structured-output
- // runnable; the actual request still omits the thinking field via
- // anthropicInvocationKwargs above.
- anthropicChatModel.thinking = { type: "adaptive" };
-
- return anthropicChatModel.withStructuredOutput(
- structuredOutputSchema,
- structuredOutputConfig,
- );
- } finally {
- anthropicChatModel.thinking = originalThinking;
- }
- };
- const structuredOutputModel = createStructuredOutputModel();
-
- const structuredOutput = await executeWithRuntimeTimeout({
- enabled: runtimeTimeoutEnabled,
- timeoutMs,
- abortController: runtimeTimeoutController,
- operation: () =>
- structuredOutputModel.invoke(finalMessages, runConfigWithTimeout),
- });
-
- return structuredOutput;
- }
-
- if (tools && tools.length > 0) {
- const langchainTools = tools.map((tool) => ({
- type: "function",
- function: tool,
- }));
-
- const result = await executeWithRuntimeTimeout({
- enabled: runtimeTimeoutEnabled,
- timeoutMs,
- abortController: runtimeTimeoutController,
- operation: () =>
- chatModel
- .bindTools(langchainTools)
- .invoke(finalMessages, runConfigWithTimeout),
- });
-
- // Always normalize through `splitAIMessage` so we feed the schema the
- // standard `contentBlocks` shape regardless of provider, instead of the
- // raw, provider-specific message content.
- const { contentWithoutThinking, reasoning } = splitAIMessage(result);
- const parsed = ToolCallResponseSchema.safeParse({
- content: contentWithoutThinking,
- tool_calls: result.tool_calls,
- });
- if (!parsed.success) throw Error("Failed to parse LLM tool call result");
-
- return {
- ...parsed.data,
- ...(reasoning ? { reasoning } : {}),
- };
- }
-
- if (streaming)
- return await executeWithRuntimeTimeout({
- enabled: runtimeTimeoutEnabled,
- timeoutMs,
- abortController: runtimeTimeoutController,
- operation: () =>
- chatModel
- .pipe(
- createBytesOutputParser(shouldNormalizeStreamingContentBlocks),
- )
- .stream(finalMessages, runConfigWithTimeout),
- });
-
- // content with thinking blocks can't be handled by StringOutputParser
- // Invoke model directly and extract text + reasoning separately.
- if (shouldNormalizeModelContentBlocks) {
- const aiMessage = await executeWithRuntimeTimeout({
- enabled: runtimeTimeoutEnabled,
- timeoutMs,
- abortController: runtimeTimeoutController,
- operation: () => chatModel.invoke(finalMessages, runConfigWithTimeout),
- });
- const completion = extractCompletionWithReasoning(aiMessage);
-
- // Bedrock only returns reasoning blocks for selected models. Preserve the
- // historical plain-string shape when the response contains no reasoning.
- if (
- modelParams.adapter === LLMAdapter.Bedrock &&
- completion.reasoning == null
- ) {
- return completion.text;
- }
-
- return completion;
- }
-
- const completion = await executeWithRuntimeTimeout({
- enabled: runtimeTimeoutEnabled,
- timeoutMs,
- abortController: runtimeTimeoutController,
- operation: () =>
- chatModel
- .pipe(new StringOutputParser())
- .invoke(finalMessages, runConfigWithTimeout),
- });
-
- return completion;
- } catch (e) {
- throw mapToLLMCompletionError(e);
- } finally {
- await processTracedEvents();
- }
-}
-
-function extractCompletionWithReasoning(
- message: AIMessage,
-): CompletionWithReasoning {
- const { text, reasoning } = splitAIMessage(message);
-
- return {
- text,
- ...(reasoning ? { reasoning } : {}),
- };
-}
-
-function createBytesOutputParser(
- normalizeContentBlocks: boolean,
-): BytesOutputParser {
- return normalizeContentBlocks
- ? new ContentBlockBytesOutputParser()
- : new BytesOutputParser();
-}
-
-class ContentBlockBytesOutputParser extends BytesOutputParser {
- // Override `_baseMessageToString` (not `_baseMessageContentToString`) so we
- // have the whole AIMessage(Chunk) and can read `contentBlocks`, which the
- // langchain provider translator normalizes into standard blocks. This strips
- // reasoning blocks and also avoids serializing OpenAI Responses API lifecycle
- // chunks such as empty `final_answer` phase markers.
- protected _baseMessageToString(message: BaseMessage): string {
- if (AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) {
- return splitAIMessage(message).text;
- }
- return typeof message.content === "string"
- ? message.content
- : super._baseMessageToString(message);
- }
-}
-
-// Reads the standard `contentBlocks` view of an AIMessage(Chunk) and splits it
-// into displayable text, reasoning, and a content array stripped of reasoning
-// and tool_call blocks (tool calls live on `message.tool_calls`).
-function splitAIMessage(
- message: AIMessage | AIMessageChunk,
-): SplitAIMessageContent {
- if (typeof message.content === "string") {
- return { text: message.content, contentWithoutThinking: message.content };
- }
-
- const textParts: string[] = [];
- const reasoningParts: string[] = [];
- const contentWithoutThinking: Array<ContentBlock.Standard> = [];
-
- for (const block of message.contentBlocks) {
- if (block.type === "reasoning") {
- if (typeof block.reasoning === "string")
- reasoningParts.push(block.reasoning);
- continue;
- }
- if (block.type === "tool_call") {
- // Already represented in `message.tool_calls`; omit to avoid duplicates.
- continue;
- }
- if (block.type === "text" && typeof block.text === "string") {
- textParts.push(block.text);
- }
- contentWithoutThinking.push(block);
- }
-
- return {
- text: textParts.join(""),
- contentWithoutThinking,
- ...(reasoningParts.length > 0
- ? { reasoning: reasoningParts.join("") }
- : {}),
- };
-}
diff --git a/packages/shared/src/server/llm/googleSecureApiClient.ts b/packages/shared/src/server/llm/googleSecureApiClient.ts
deleted file mode 100644
index 5042ade01b..0000000000
--- a/packages/shared/src/server/llm/googleSecureApiClient.ts
+++ /dev/null
@@ -1,144 +0,0 @@
-import { type OutboundUrlValidationWhitelist } from "../outbound-url";
-import { type ChatGoogleParams } from "@langchain/google";
-import { GoogleAuth, type GoogleAuthOptions } from "google-auth-library";
-import { llmBaseUrlWhitelistFromEnv } from "./baseUrlValidation";
-import { fetchSecureLlmUrl } from "./secureLlmFetch";
-
-const GOOGLE_AI_STUDIO_ORIGIN = "https://generativelanguage.googleapis.com";
-const GOOGLE_API_KEY_HEADER = "X-Goog-Api-Key";
-const VERTEX_AI_AUTH_HEADER = "authorization";
-const VERTEX_AI_AUTH_SCOPES = [
- "https://www.googleapis.com/auth/cloud-platform",
-];
-
-type GoogleApiClient = NonNullable<ChatGoogleParams["apiClient"]>;
-
-type SecureGoogleAIStudioApiClientParams = {
- apiKey: string;
- baseURL?: string | null;
- whitelist?: OutboundUrlValidationWhitelist;
- dispatcher?: unknown;
-};
-
-type SecureVertexAIApiClientParams = {
- authOptions?: GoogleAuthOptions;
- whitelist?: OutboundUrlValidationWhitelist;
- dispatcher?: unknown;
-};
-
-export function createSecureGoogleAIStudioApiClient({
- apiKey,
- baseURL,
- whitelist = llmBaseUrlWhitelistFromEnv(),
- dispatcher,
-}: SecureGoogleAIStudioApiClientParams): GoogleApiClient {
- return {
- hasApiKey: () => true,
- getProjectId: async () => "unknown-project-id",
- fetch: async (request: Request) => {
- const url = rewriteGoogleAIStudioUrl(request.url, baseURL);
-
- const headers = new Headers(request.headers);
- headers.set(GOOGLE_API_KEY_HEADER, apiKey);
-
- return fetchGoogleLlmRequest({
- url,
- request,
- headers,
- whitelist,
- logContext: "Google AI Studio LLM base URL",
- additionalSensitiveHeaders: [GOOGLE_API_KEY_HEADER],
- dispatcher,
- });
- },
- };
-}
-
-export function createSecureVertexAIApiClient({
- authOptions,
- whitelist = llmBaseUrlWhitelistFromEnv(),
- dispatcher,
-}: SecureVertexAIApiClientParams): GoogleApiClient {
- const googleAuth = new GoogleAuth({
- ...authOptions,
- scopes: authOptions?.scopes ?? VERTEX_AI_AUTH_SCOPES,
- });
-
- return {
- hasApiKey: () => false,
- getProjectId: () => googleAuth.getProjectId(),
- fetch: async (request: Request) => {
- const headers = new Headers(request.headers);
- (await googleAuth.getRequestHeaders(request.url)).forEach(
- (value, key) => {
- if (value !== null) headers.set(key, value);
- },
- );
-
- return fetchGoogleLlmRequest({
- url: request.url,
- request,
- headers,
- whitelist,
- logContext: "Vertex AI LLM endpoint",
- additionalSensitiveHeaders: [VERTEX_AI_AUTH_HEADER],
- dispatcher,
- });
- },
- };
-}
-
-export function rewriteGoogleAIStudioUrl(
- requestUrl: string,
- baseURL?: string | null,
-): string {
- if (!baseURL) return requestUrl;
-
- const parsedRequestUrl = new URL(requestUrl);
-
- if (parsedRequestUrl.origin !== GOOGLE_AI_STUDIO_ORIGIN) {
- return requestUrl;
- }
-
- // Match the previous @google/generative-ai baseUrl behavior: append the
- // generated Google path to the configured baseURL as-is.
- return `${baseURL}${parsedRequestUrl.pathname}${parsedRequestUrl.search}`;
-}
-
-async function fetchGoogleLlmRequest({
- url,
- request,
- headers,
- whitelist,
- logContext,
- additionalSensitiveHeaders,
- dispatcher,
-}: {
- url: string;
- request: Request;
- headers: Headers;
- whitelist: OutboundUrlValidationWhitelist;
- logContext: string;
- additionalSensitiveHeaders?: string[];
- dispatcher?: unknown;
-}): Promise<Response> {
- const body = ["GET", "HEAD"].includes(request.method)
- ? undefined
- : await request.text();
-
- return fetchSecureLlmUrl(
- url,
- {
- method: request.method,
- headers,
- body,
- signal: request.signal,
- },
- {
- whitelist,
- logContext,
- additionalSensitiveHeaders,
- dispatcher,
- },
- );
-}
diff --git a/packages/shared/src/server/llm/llmText.test.ts b/packages/shared/src/server/llm/llmText.test.ts
new file mode 100644
index 0000000000..d9dd5147ce
--- /dev/null
+++ b/packages/shared/src/server/llm/llmText.test.ts
@@ -0,0 +1,468 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { z } from "zod";
+
+import { createOpenAI } from "@ai-sdk/openai";
+import { tool } from "ai";
+import { MockLanguageModelV4 } from "ai/test";
+
+import { encrypt } from "../../encryption";
+import { LLMCompletionError } from "./errors";
+import {
+ createLLMOutput,
+ createLLMToolSet,
+ generateLLMText,
+ mapLegacyLLMCompletionParams,
+ streamLLMText,
+} from "./llmText";
+import {
+ ChatMessageRole,
+ ChatMessageType,
+ LLMAdapter,
+ type ChatMessage,
+} from "./types";
+
+vi.mock("@ai-sdk/openai", () => ({ createOpenAI: vi.fn() }));
+
+const messages = [{ role: "user", content: "Hello" }] as const;
+const encryptedConnection = { secretKey: encrypt("sk-test") };
+
+const usage = {
+ inputTokens: {
+ total: 1,
+ noCache: 1,
+ cacheRead: undefined,
+ cacheWrite: undefined,
+ },
+ outputTokens: { total: 1, text: 1, reasoning: undefined },
+};
+
+const finishReason = { unified: "stop" as const, raw: "stop" };
+
+function useModel(model: MockLanguageModelV4): void {
+ vi.mocked(createOpenAI).mockReturnValue({
+ chat: () => model,
+ responses: () => model,
+ } as never);
+}
+
+function openAIOptions() {
+ return {
+ model: { adapter: LLMAdapter.OpenAI, id: "gpt-4o" },
+ connection: encryptedConnection,
+ messages: [...messages],
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("generateLLMText", () => {
+ it("returns the native text and reasoning result", async () => {
+ useModel(
+ new MockLanguageModelV4({
+ provider: "openai",
+ modelId: "gpt-4o",
+ doGenerate: {
+ content: [
+ { type: "reasoning", text: "Think first." },
+ { type: "text", text: "Hello there" },
+ ],
+ finishReason,
+ usage: {
+ ...usage,
+ outputTokens: { total: 3, text: 2, reasoning: 1 },
+ },
+ warnings: [],
+ },
+ }),
+ );
+
+ const result = await generateLLMText(openAIOptions());
+
+ expect(result.text).toBe("Hello there");
+ expect(result.finalStep.reasoningText).toBe("Think first.");
+ expect(result.usage).toMatchObject({
+ inputTokens: 1,
+ outputTokens: 3,
+ });
+ });
+
+ it("preserves structured-output inference on the native result", async () => {
+ useModel(
+ new MockLanguageModelV4({
+ doGenerate: {
+ content: [{ type: "text", text: '{"score":5,"reason":"clear"}' }],
+ finishReason,
+ usage,
+ warnings: [],
+ },
+ }),
+ );
+ const output = createLLMOutput(
+ z.object({ score: z.number(), reason: z.string() }),
+ );
+
+ const result = await generateLLMText({
+ ...openAIOptions(),
+ output,
+ });
+
+ const score: number = result.output.score;
+ expect(score).toBe(5);
+ expect(result.output.reason).toBe("clear");
+ });
+
+ it("returns native typed tool calls without executing tools", async () => {
+ useModel(
+ new MockLanguageModelV4({
+ doGenerate: {
+ content: [
+ {
+ type: "tool-call",
+ toolCallId: "call-1",
+ toolName: "get_weather",
+ input: '{"city":"Berlin"}',
+ },
+ ],
+ finishReason: { unified: "tool-calls", raw: "tool_calls" },
+ usage,
+ warnings: [],
+ },
+ }),
+ );
+ const tools = createLLMToolSet([
+ {
+ name: "get_weather",
+ description: "Get the weather",
+ parameters: {
+ type: "object",
+ properties: { city: { type: "string" } },
+ required: ["city"],
+ },
+ },
+ ]);
+
+ const result = await generateLLMText({
+ ...openAIOptions(),
+ tools,
+ });
+
+ expect(result.toolCalls).toEqual([
+ expect.objectContaining({
+ toolCallId: "call-1",
+ toolName: "get_weather",
+ input: { city: "Berlin" },
+ }),
+ ]);
+ expect(result.toolResults).toEqual([]);
+ });
+
+ it("rejects executable tools instead of running an agent loop", async () => {
+ const execute = vi.fn();
+
+ await expect(
+ generateLLMText({
+ ...openAIOptions(),
+ tools: {
+ dangerous: tool({
+ inputSchema: z.object({}),
+ execute,
+ }),
+ },
+ }),
+ ).rejects.toMatchObject({
+ name: "LLMCompletionError",
+ responseStatusCode: 400,
+ isRetryable: false,
+ });
+ expect(execute).not.toHaveBeenCalled();
+ expect(createOpenAI).not.toHaveBeenCalled();
+ });
+
+ it("does not download media URLs", async () => {
+ const model = new MockLanguageModelV4({
+ supportedUrls: {},
+ doGenerate: {
+ content: [{ type: "text", text: "should not run" }],
+ finishReason,
+ usage,
+ warnings: [],
+ },
+ });
+ useModel(model);
+ const fetchSpy = vi.spyOn(globalThis, "fetch");
+
+ await expect(
+ generateLLMText({
+ ...openAIOptions(),
+ messages: [
+ {
+ role: "user",
+ content: [
+ {
+ type: "file",
+ data: new URL(
+ "http://dns-rebind.attacker.example/metadata?token=secret",
+ ),
+ mediaType: "image/png",
+ },
+ ],
+ },
+ ],
+ }),
+ ).rejects.toMatchObject({
+ name: "LLMCompletionError",
+ message:
+ "Remote media downloads are not supported on the Langfuse server; use provider-supported URLs or inline data instead",
+ responseStatusCode: 400,
+ isRetryable: false,
+ });
+
+ expect(fetchSpy).not.toHaveBeenCalled();
+ expect(model.doGenerateCalls).toHaveLength(0);
+ });
+
+ it("rejects model-supported media URLs when AI SDK would download them", async () => {
+ const model = new MockLanguageModelV4({
+ supportedUrls: { "image/*": [/^https:\/\/cdn\.example\.com\//] },
+ doGenerate: {
+ content: [{ type: "text", text: "should not run" }],
+ finishReason,
+ usage,
+ warnings: [],
+ },
+ });
+ useModel(model);
+ const fetchSpy = vi.spyOn(globalThis, "fetch");
+
+ await expect(
+ generateLLMText({
+ ...openAIOptions(),
+ messages: [
+ {
+ role: "user",
+ content: [
+ {
+ type: "file",
+ data: new URL("https://cdn.example.com/image.png"),
+ mediaType: "image/png",
+ },
+ ],
+ },
+ ],
+ }),
+ ).rejects.toMatchObject({
+ name: "LLMCompletionError",
+ message:
+ "Remote media downloads are not supported on the Langfuse server; use provider-supported URLs or inline data instead",
+ responseStatusCode: 400,
+ isRetryable: false,
+ });
+
+ expect(fetchSpy).not.toHaveBeenCalled();
+ expect(model.doGenerateCalls).toHaveLength(0);
+ });
+});
+
+describe("streamLLMText", () => {
+ it("returns the native AI SDK stream result", async () => {
+ useModel(
+ new MockLanguageModelV4({
+ doStream: {
+ stream: new ReadableStream({
+ start(controller) {
+ controller.enqueue({ type: "stream-start", warnings: [] });
+ controller.enqueue({ type: "text-start", id: "text-1" });
+ controller.enqueue({
+ type: "text-delta",
+ id: "text-1",
+ delta: "Hello ",
+ });
+ controller.enqueue({
+ type: "text-delta",
+ id: "text-1",
+ delta: "there",
+ });
+ controller.enqueue({ type: "text-end", id: "text-1" });
+ controller.enqueue({
+ type: "finish",
+ finishReason,
+ usage,
+ });
+ controller.close();
+ },
+ }),
+ },
+ }),
+ );
+
+ const result = await streamLLMText(openAIOptions());
+ let streamedText = "";
+ for await (const chunk of result.textStream) streamedText += chunk;
+
+ expect(streamedText).toBe("Hello there");
+ expect(await result.text).toBe("Hello there");
+ });
+
+ it("maps asynchronous timeout errors before exposing them to consumers", async () => {
+ const timeoutError = new DOMException(
+ "The operation timed out",
+ "TimeoutError",
+ );
+ useModel(
+ new MockLanguageModelV4({
+ doStream: {
+ stream: new ReadableStream({
+ start(controller) {
+ controller.enqueue({ type: "error", error: timeoutError });
+ controller.close();
+ },
+ }),
+ },
+ }),
+ );
+ const onError = vi.fn();
+ const result = await streamLLMText({
+ ...openAIOptions(),
+ timeout: 25,
+ onError,
+ });
+
+ const parts = [];
+ for await (const part of result.stream) parts.push(part);
+ const errorPart = parts.find((part) => part.type === "error");
+
+ expect(errorPart).toMatchObject({
+ type: "error",
+ error: {
+ name: "LLMCompletionError",
+ message: "Request timed out after 25ms",
+ isRetryable: false,
+ },
+ });
+ expect(onError).toHaveBeenCalledWith({
+ error: expect.objectContaining({
+ name: "LLMCompletionError",
+ message: "Request timed out after 25ms",
+ }),
+ });
+ });
+});
+
+describe("legacy compatibility boundary", () => {
+ const legacyMessages: ChatMessage[] = [
+ {
+ type: ChatMessageType.User,
+ role: ChatMessageRole.User,
+ content: "Hello",
+ },
+ ];
+
+ it("translates persisted options into namespaced AI SDK options", () => {
+ const mapped = mapLegacyLLMCompletionParams({
+ messages: legacyMessages,
+ modelParams: {
+ provider: "openai",
+ adapter: LLMAdapter.OpenAI,
+ model: "gpt-4o",
+ max_tokens: 123,
+ top_p: 0.8,
+ providerOptions: { reasoning_effort: "high" },
+ },
+ connection: encryptedConnection,
+ });
+
+ expect(mapped).toMatchObject({
+ model: { adapter: LLMAdapter.OpenAI, id: "gpt-4o" },
+ maxOutputTokens: 123,
+ topP: 0.8,
+ providerOptions: { openai: { reasoningEffort: "high" } },
+ });
+ expect(mapped.messages).toEqual([{ role: "user", content: "Hello" }]);
+ });
+
+ it("maps Azure OpenAI provider options to the OpenAI namespace", () => {
+ const mapped = mapLegacyLLMCompletionParams({
+ messages: legacyMessages,
+ modelParams: {
+ provider: "azure",
+ adapter: LLMAdapter.Azure,
+ model: "gpt-4o-deployment",
+ providerOptions: { reasoning_effort: "high" },
+ },
+ connection: encryptedConnection,
+ });
+
+ expect(mapped.providerOptions).toEqual({
+ openai: { reasoningEffort: "high" },
+ });
+ });
+
+ it("preserves explicit non-reasoning OpenAI gpt-5.4 mini/nano handling", () => {
+ const mapped = mapLegacyLLMCompletionParams({
+ messages: legacyMessages,
+ modelParams: {
+ provider: "openai",
+ adapter: LLMAdapter.OpenAI,
+ model: "gpt-5.4-mini",
+ providerOptions: { service_tier: "flex" },
+ },
+ connection: encryptedConnection,
+ });
+
+ expect(mapped.providerOptions).toEqual({
+ openai: { serviceTier: "flex", forceReasoning: false },
+ });
+ });
+
+ it("rejects options that cannot be translated instead of falling back", () => {
+ expect(() =>
+ mapLegacyLLMCompletionParams({
+ messages: legacyMessages,
+ modelParams: {
+ provider: "anthropic",
+ adapter: LLMAdapter.Anthropic,
+ model: "claude-sonnet-5",
+ providerOptions: { unknown_parameter: true },
+ },
+ connection: encryptedConnection,
+ }),
+ ).toThrow(
+ expect.objectContaining<Partial<LLMCompletionError>>({
+ name: "LLMCompletionError",
+ responseStatusCode: 400,
+ isRetryable: false,
+ }),
+ );
+ });
+
+ it("rejects invalid connections and unsupported managed credentials", async () => {
+ await expect(
+ generateLLMText({
+ model: { adapter: LLMAdapter.Azure, id: "deployment" },
+ connection: {
+ ...encryptedConnection,
+ baseURL: "https://example.com/openai",
+ },
+ messages: [...messages],
+ }),
+ ).rejects.toMatchObject({
+ name: "LLMCompletionError",
+ responseStatusCode: 400,
+ isRetryable: false,
+ });
+
+ await expect(
+ generateLLMText({
+ ...openAIOptions(),
+ credentialSource: "langfuse",
+ }),
+ ).rejects.toMatchObject({
+ name: "LLMCompletionError",
+ message: "Langfuse credentials are only supported for Amazon Bedrock",
+ responseStatusCode: 400,
+ isRetryable: false,
+ });
+ });
+});
diff --git a/packages/shared/src/server/llm/llmText.ts b/packages/shared/src/server/llm/llmText.ts
new file mode 100644
index 0000000000..f02741328f
--- /dev/null
+++ b/packages/shared/src/server/llm/llmText.ts
@@ -0,0 +1,625 @@
+import { type ZodType } from "zod";
+
+import { ProxyAgent } from "undici";
+import {
+ Output,
+ generateText,
+ getChunkTimeoutMs,
+ getStepTimeoutMs,
+ getTotalTimeoutMs,
+ jsonSchema,
+ streamText,
+ tool,
+ type GenerateTextAbortEvent,
+ type GenerateTextOnAbortCallback,
+ type GenerateTextOnEndCallback,
+ type GenerateTextResult,
+ type Experimental_DownloadFunction,
+ type JSONValue,
+ type ModelMessage,
+ type StreamTextOnErrorCallback,
+ type StreamTextResult,
+ type StreamTextTransform,
+ type TimeoutConfiguration,
+ type ToolSet,
+} from "ai";
+
+import { decrypt } from "../../encryption";
+import { env } from "../../env";
+import type { LLMConnectionConfig } from "../../interfaces/customLLMProviderConfigSchemas";
+import {
+ hasTimeoutAbortInCauseChain,
+ mapToLLMCompletionError,
+} from "./completionErrorMapping";
+import { LLMCompletionError } from "./errors";
+import { mapChatMessagesToModelMessages } from "./ai-sdk/messages";
+import { buildAiSdkModel } from "./ai-sdk/providers";
+import { translateAnthropicProviderOptions } from "./ai-sdk/providers/anthropic";
+import { translateBedrockProviderOptions } from "./ai-sdk/providers/bedrock";
+import { translateGoogleProviderOptions } from "./ai-sdk/providers/google";
+import { translateOpenAIProviderOptions } from "./ai-sdk/providers/openai";
+import type {
+ LLMCredentialSource,
+ TranslatedProviderOptions,
+} from "./ai-sdk/providers/types";
+import { isClaudeModel } from "./ai-sdk/providers/vertex";
+import {
+ recordAiSdkExecution,
+ resolveAiSdkModelConfig,
+} from "./ai-sdk/resolveAiSdkModelConfig";
+import {
+ createAiSdkTelemetryCapture,
+ type AiSdkTelemetryCapture,
+} from "./ai-sdk/telemetry";
+import { createSecureLlmFetch } from "./secureLlmFetch";
+import type {
+ ChatMessage,
+ LLMJSONSchema,
+ LLMToolDefinition,
+ ModelParams,
+ TraceSinkParams,
+} from "./types";
+import { LLMAdapter } from "./types";
+import { decryptAndParseExtraHeaders } from "./utils";
+
+type RuntimeContext = Record<string, unknown>;
+type ProviderOptions = Record<string, Record<string, JSONValue>>;
+
+export type LLMModelRef = {
+ adapter: LLMAdapter;
+ id: string;
+};
+
+export type LLMConnection = {
+ /** Encrypted credential. It is decrypted only inside the execution boundary. */
+ secretKey: string;
+ /** Encrypted JSON object of additional headers. */
+ extraHeaders?: string | null;
+ baseURL?: string | null;
+ config?: LLMConnectionConfig | null;
+};
+
+export type LLMModelMessage = ModelMessage;
+export type LLMToolSet = ToolSet;
+export type LLMProviderOptions = ProviderOptions;
+export type LLMOutput<
+ OUTPUT = unknown,
+ PARTIAL = unknown,
+ ELEMENT = never,
+> = Output.Output<OUTPUT, PARTIAL, ELEMENT>;
+
+export type StreamLLMTextOnAbortCallback<TOOLS extends ToolSet = ToolSet> =
+ GenerateTextOnAbortCallback<TOOLS, RuntimeContext>;
+
+type BaseLLMTextOptions<TOOLS extends ToolSet, OUTPUT extends Output.Output> = {
+ model: LLMModelRef;
+ connection: LLMConnection;
+ messages: ModelMessage[];
+ /**
+ * Tool definitions only. Supplying an `execute` function is rejected so a
+ * completion cannot silently become an agent loop inside this boundary.
+ */
+ tools?: TOOLS;
+ output?: OUTPUT;
+ maxOutputTokens?: number;
+ temperature?: number;
+ topP?: number;
+ /** Canonical, provider-namespaced AI SDK options. */
+ providerOptions?: ProviderOptions;
+ maxRetries?: number;
+ timeout?: TimeoutConfiguration<TOOLS>;
+ abortSignal?: AbortSignal;
+ trace?: TraceSinkParams;
+ credentialSource?: LLMCredentialSource;
+ onEnd?: GenerateTextOnEndCallback<TOOLS, RuntimeContext>;
+};
+
+export type GenerateLLMTextOptions<
+ TOOLS extends ToolSet = {},
+ OUTPUT extends Output.Output = Output.Output<string, string, never>,
+> = BaseLLMTextOptions<TOOLS, OUTPUT>;
+
+export type StreamLLMTextOptions<
+ TOOLS extends ToolSet = {},
+ OUTPUT extends Output.Output = Output.Output<string, string, never>,
+> = BaseLLMTextOptions<TOOLS, OUTPUT> & {
+ onError?: StreamTextOnErrorCallback;
+ onAbort?: StreamLLMTextOnAbortCallback<TOOLS>;
+};
+
+export type GenerateLLMTextResult<
+ TOOLS extends ToolSet = {},
+ OUTPUT extends Output.Output = Output.Output<string, string, never>,
+> = GenerateTextResult<TOOLS, RuntimeContext, OUTPUT>;
+
+export type StreamLLMTextResult<
+ TOOLS extends ToolSet = {},
+ OUTPUT extends Output.Output = Output.Output<string, string, never>,
+> = StreamTextResult<TOOLS, RuntimeContext, OUTPUT>;
+
+type PreparedLLMTextCall<TOOLS extends ToolSet> = {
+ languageModel: Awaited<ReturnType<typeof buildAiSdkModel>>;
+ capture?: AiSdkTelemetryCapture;
+ runInTraceContext: <T>(fn: () => T) => T;
+ callOptions: {
+ messages: ModelMessage[];
+ allowSystemInMessages: true;
+ tools?: TOOLS;
+ maxOutputTokens?: number;
+ temperature?: number;
+ topP?: number;
+ providerOptions?: ProviderOptions;
+ maxRetries?: number;
+ timeout: TimeoutConfiguration<TOOLS>;
+ abortSignal?: AbortSignal;
+ experimental_download: Experimental_DownloadFunction;
+ telemetry?: AiSdkTelemetryCapture["telemetry"];
+ };
+};
+
+/** Executes one non-streaming LLM call and returns the native AI SDK result. */
+export async function generateLLMText<
+ TOOLS extends ToolSet = {},
+ OUTPUT extends Output.Output = Output.Output<string, string, never>,
+>(
+ options: GenerateLLMTextOptions<TOOLS, OUTPUT>,
+): Promise<GenerateLLMTextResult<TOOLS, OUTPUT>> {
+ const prepared = await prepareLLMTextCall(options);
+ const { capture, runInTraceContext } = prepared;
+
+ try {
+ const result = await runInTraceContext(() =>
+ generateText<TOOLS, RuntimeContext, OUTPUT>({
+ model: prepared.languageModel,
+ ...prepared.callOptions,
+ output: options.output,
+ onEnd: options.onEnd,
+ }),
+ );
+
+ capture?.setRootOutput(
+ options.output
+ ? result.output
+ : toTraceOutput({
+ text: result.text,
+ reasoningText: result.finalStep.reasoningText,
+ toolCalls: result.toolCalls,
+ }),
+ );
+
+ return result;
+ } catch (error) {
+ const completionError = toCompletionError(
+ error,
+ prepared.callOptions.timeout,
+ );
+ capture?.setRootError(completionError);
+ throw completionError;
+ } finally {
+ await capture?.flush();
+ }
+}
+
+/**
+ * Starts one streaming LLM call and returns the native AI SDK stream result.
+ * Model construction can be asynchronous (notably Vertex ADC), so callers
+ * await this function before consuming `textStream`, `stream`, or result
+ * promises.
+ */
+export async function streamLLMText<
+ TOOLS extends ToolSet = {},
+ OUTPUT extends Output.Output = Output.Output<string, string, never>,
+>(
+ options: StreamLLMTextOptions<TOOLS, OUTPUT>,
+): Promise<StreamLLMTextResult<TOOLS, OUTPUT>> {
+ const prepared = await prepareLLMTextCall(options);
+ const { capture, runInTraceContext } = prepared;
+ const timeout = prepared.callOptions.timeout;
+
+ try {
+ return runInTraceContext(() =>
+ streamText<TOOLS, RuntimeContext, OUTPUT>({
+ model: prepared.languageModel,
+ ...prepared.callOptions,
+ output: options.output,
+ // Map asynchronous provider and timeout failures before AI SDK's
+ // event processor exposes them through streams, promises, callbacks,
+ // and `consumeStream`.
+ experimental_transform: createCompletionErrorTransform(timeout),
+ onEnd: async (event) => {
+ capture?.setRootOutput(
+ toTraceOutput({
+ text: event.text,
+ reasoningText: event.finalStep.reasoningText,
+ toolCalls: event.toolCalls,
+ }),
+ );
+ try {
+ await options.onEnd?.(event);
+ } finally {
+ await capture?.flush();
+ }
+ },
+ onError: async (event) => {
+ // `event.error` has already passed through the transform above.
+ capture?.setRootError(event.error);
+ try {
+ await options.onError?.(event);
+ } finally {
+ await capture?.flush();
+ }
+ },
+ onAbort: async (event) => {
+ capture?.setRootError(
+ new LLMCompletionError({
+ message: "LLM completion aborted",
+ responseStatusCode: 499,
+ isRetryable: false,
+ }),
+ );
+ try {
+ // streamText's public callback type currently omits callId/reason,
+ // although its runtime event includes the full native abort event.
+ await options.onAbort?.(
+ event as GenerateTextAbortEvent<TOOLS, RuntimeContext>,
+ );
+ } finally {
+ await capture?.flush();
+ }
+ },
+ }),
+ );
+ } catch (error) {
+ const completionError = toCompletionError(error, timeout);
+ capture?.setRootError(completionError);
+ await capture?.flush();
+ throw completionError;
+ }
+}
+
+async function prepareLLMTextCall<
+ TOOLS extends ToolSet,
+ OUTPUT extends Output.Output,
+>(
+ options: BaseLLMTextOptions<TOOLS, OUTPUT>,
+): Promise<PreparedLLMTextCall<TOOLS>> {
+ assertDefinitionOnlyTools(options.tools);
+
+ const credentialSource = options.credentialSource ?? "user";
+ const timeout =
+ options.timeout ?? env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS;
+
+ try {
+ const modelConfig = resolveAiSdkModelConfig({
+ model: options.model,
+ connectionConfig: options.connection.config,
+ baseURL: options.connection.baseURL,
+ credentialSource,
+ });
+ recordAiSdkExecution({ model: options.model, modelConfig });
+
+ const apiKey = decrypt(options.connection.secretKey);
+ const extraHeaders = decryptAndParseExtraHeaders(
+ options.connection.extraHeaders,
+ );
+
+ const proxyDispatcher = env.HTTPS_PROXY
+ ? new ProxyAgent(env.HTTPS_PROXY)
+ : undefined;
+ const createFetch = (
+ logContext: string,
+ additionalSensitiveHeaders?: string[],
+ ) =>
+ createSecureLlmFetch({
+ logContext,
+ // Connection-specific headers are encrypted at rest and can contain
+ // gateway credentials. Keep them on same-origin redirects, but strip
+ // them alongside provider auth headers when the origin changes.
+ additionalSensitiveHeaders: (additionalSensitiveHeaders ?? []).concat(
+ Object.keys(extraHeaders ?? {}),
+ ),
+ dispatcher: proxyDispatcher,
+ });
+
+ const languageModel = await buildAiSdkModel({
+ model: options.model,
+ modelConfig,
+ apiKey,
+ baseURL: options.connection.baseURL,
+ extraHeaders,
+ config: options.connection.config,
+ credentialSource,
+ createFetch,
+ });
+
+ const capture = options.trace
+ ? createAiSdkTelemetryCapture({
+ traceSinkParams: options.trace,
+ rootInput: options.messages,
+ })
+ : undefined;
+
+ return {
+ languageModel,
+ capture,
+ runInTraceContext: <T>(fn: () => T): T =>
+ capture ? capture.run(fn) : fn(),
+ callOptions: {
+ messages: options.messages,
+ allowSystemInMessages: true,
+ tools: options.tools,
+ maxOutputTokens: options.maxOutputTokens,
+ temperature: options.temperature,
+ topP: options.topP,
+ providerOptions: options.providerOptions,
+ maxRetries: options.maxRetries,
+ timeout,
+ abortSignal: options.abortSignal,
+ // Do not let AI SDK download remote media on the Langfuse server.
+ // Callers must use provider-supported URLs or inline data.
+ experimental_download: rejectRemoteMediaDownloads,
+ ...(capture ? { telemetry: capture.telemetry } : {}),
+ },
+ };
+ } catch (error) {
+ throw toCompletionError(error, timeout);
+ }
+}
+
+const rejectRemoteMediaDownloads: Experimental_DownloadFunction = async (
+ downloads,
+) => {
+ if (downloads.length > 0) {
+ throw new LLMCompletionError({
+ message:
+ "Remote media downloads are not supported on the Langfuse server; use provider-supported URLs or inline data instead",
+ responseStatusCode: 400,
+ isRetryable: false,
+ });
+ }
+ return [];
+};
+
+function assertDefinitionOnlyTools(tools: ToolSet | undefined): void {
+ if (!tools) return;
+
+ const executableTool = Object.entries(tools).find(
+ ([, definition]) =>
+ typeof (definition as { execute?: unknown }).execute === "function",
+ );
+ if (!executableTool) return;
+
+ throw new LLMCompletionError({
+ message: `Tool "${executableTool[0]}" must not define execute; LLM text calls only accept tool definitions`,
+ responseStatusCode: 400,
+ isRetryable: false,
+ });
+}
+
+function createCompletionErrorTransform<TOOLS extends ToolSet>(
+ timeout: TimeoutConfiguration<TOOLS>,
+): StreamTextTransform<TOOLS> {
+ return () =>
+ new TransformStream({
+ transform(part, controller) {
+ controller.enqueue(
+ part.type === "error"
+ ? { ...part, error: toCompletionError(part.error, timeout) }
+ : part,
+ );
+ },
+ });
+}
+
+function toCompletionError<TOOLS extends ToolSet>(
+ error: unknown,
+ timeout: TimeoutConfiguration<TOOLS>,
+): LLMCompletionError {
+ if (hasTimeoutAbortInCauseChain(error)) {
+ return new LLMCompletionError({
+ message: `Request timed out after ${getTimeoutMs(timeout)}ms`,
+ responseStatusCode: 500,
+ isRetryable: false,
+ cause: error,
+ });
+ }
+
+ return mapToLLMCompletionError(error);
+}
+
+function getTimeoutMs<TOOLS extends ToolSet>(
+ timeout: TimeoutConfiguration<TOOLS>,
+): number {
+ return (
+ getTotalTimeoutMs(timeout) ??
+ getStepTimeoutMs(timeout) ??
+ getChunkTimeoutMs(timeout) ??
+ env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS
+ );
+}
+
+function toTraceOutput(params: {
+ text: string;
+ reasoningText?: string;
+ toolCalls: readonly unknown[];
+}): unknown {
+ const { text, reasoningText, toolCalls } = params;
+
+ if (toolCalls.length > 0) {
+ return {
+ text,
+ toolCalls,
+ ...(reasoningText ? { reasoningText } : {}),
+ };
+ }
+ if (reasoningText) return { text, reasoningText };
+
+ return text;
+}
+
+/** Creates definition-only AI SDK tools from the persisted playground shape. */
+export function createLLMToolSet(tools: LLMToolDefinition[]): ToolSet {
+ return Object.fromEntries(
+ tools.map((definition) => [
+ definition.name,
+ tool({
+ description: definition.description,
+ inputSchema: jsonSchema(
+ definition.parameters as Parameters<typeof jsonSchema>[0],
+ ),
+ }),
+ ]),
+ );
+}
+
+/** Creates a typed AI SDK object output from Zod or persisted JSON Schema. */
+export function createLLMOutput<OUTPUT>(
+ schema: ZodType<OUTPUT>,
+): Output.Output<OUTPUT, unknown, never>;
+export function createLLMOutput(
+ schema: LLMJSONSchema,
+): Output.Output<Record<string, unknown>, unknown, never>;
+export function createLLMOutput(
+ schema: ZodType | LLMJSONSchema,
+): Output.Output<unknown, unknown, never>;
+export function createLLMOutput(
+ schema: ZodType | LLMJSONSchema,
+): Output.Output<unknown, unknown, never> {
+ const isStandardSchema =
+ schema instanceof Object && "~standard" in (schema as object);
+ const flexibleSchema = isStandardSchema
+ ? (schema as ZodType)
+ : jsonSchema(schema as Parameters<typeof jsonSchema>[0]);
+
+ return Output.object({ schema: flexibleSchema }) as Output.Output<
+ unknown,
+ unknown,
+ never
+ >;
+}
+
+export type LegacyLLMTextOptions = {
+ model: LLMModelRef;
+ connection: LLMConnection;
+ messages: ModelMessage[];
+ maxOutputTokens?: number;
+ temperature?: number;
+ topP?: number;
+ providerOptions?: ProviderOptions;
+ credentialSource: LLMCredentialSource;
+};
+
+/**
+ * Compatibility boundary for persisted/UI Langfuse shapes. New runtime code
+ * should pass native messages and namespaced provider options directly.
+ */
+export function mapLegacyLLMCompletionParams(params: {
+ messages: ChatMessage[];
+ modelParams: ModelParams;
+ connection: LLMConnection;
+ credentialSource?: LLMCredentialSource;
+}): LegacyLLMTextOptions {
+ const { modelParams } = params;
+ const providerOptions = translateLegacyProviderOptions(modelParams);
+
+ return {
+ model: { adapter: modelParams.adapter, id: modelParams.model },
+ connection: params.connection,
+ messages: mapChatMessagesToModelMessages(params.messages, {
+ adapter: modelParams.adapter,
+ }),
+ maxOutputTokens: modelParams.max_tokens,
+ temperature: modelParams.temperature,
+ topP: modelParams.top_p,
+ providerOptions,
+ credentialSource: params.credentialSource ?? "user",
+ };
+}
+
+function translateLegacyProviderOptions(
+ modelParams: ModelParams,
+): ProviderOptions | undefined {
+ let namespace: string;
+ let translated: TranslatedProviderOptions;
+
+ switch (modelParams.adapter) {
+ case LLMAdapter.OpenAI: {
+ namespace = "openai";
+ translated = translateOpenAIProviderOptions(modelParams.providerOptions);
+ if (
+ translated.ok &&
+ isOpenAINonReasoningChatModel(modelParams.model) &&
+ translated.value?.forceReasoning === undefined
+ ) {
+ translated.value = {
+ ...(translated.value ?? {}),
+ forceReasoning: false,
+ };
+ }
+ break;
+ }
+ case LLMAdapter.Azure:
+ namespace = "openai";
+ translated = translateOpenAIProviderOptions(modelParams.providerOptions);
+ break;
+ case LLMAdapter.Anthropic:
+ namespace = "anthropic";
+ translated = translateAnthropicProviderOptions(
+ modelParams.providerOptions,
+ );
+ break;
+ case LLMAdapter.Bedrock:
+ namespace = "bedrock";
+ translated = translateBedrockProviderOptions(modelParams.providerOptions);
+ break;
+ case LLMAdapter.GoogleAIStudio:
+ namespace = "google";
+ translated = translateGoogleProviderOptions({
+ providerOptions: modelParams.providerOptions,
+ model: modelParams.model,
+ });
+ break;
+ case LLMAdapter.VertexAI: {
+ const isClaude = isClaudeModel(modelParams.model);
+ namespace = isClaude ? "anthropic" : "google";
+ translated = isClaude
+ ? translateAnthropicProviderOptions(modelParams.providerOptions, {
+ dropModelOverride: true,
+ })
+ : translateGoogleProviderOptions({
+ providerOptions: modelParams.providerOptions,
+ model: modelParams.model,
+ maxReasoningTokens: modelParams.maxReasoningTokens,
+ });
+ break;
+ }
+ default: {
+ const _exhaustiveCheck: never = modelParams.adapter;
+ throw new LLMCompletionError({
+ message: `Unsupported LLM adapter: ${_exhaustiveCheck}`,
+ responseStatusCode: 400,
+ isRetryable: false,
+ });
+ }
+ }
+
+ if (!translated.ok) {
+ throw new LLMCompletionError({
+ message: `Unsupported ${modelParams.adapter} provider options: ${translated.unknownKeys.join(", ")}`,
+ responseStatusCode: 400,
+ isRetryable: false,
+ });
+ }
+
+ return translated.value
+ ? ({ [namespace]: translated.value } as ProviderOptions)
+ : undefined;
+}
+
+function isOpenAINonReasoningChatModel(model: string): boolean {
+ return /^gpt-5\.4-(mini|nano)(-\d{4}-\d{2}-\d{2})?$/i.test(
+ model.replace(/^openai\//i, ""),
+ );
+}
+
+export { mapChatMessagesToModelMessages };
diff --git a/packages/shared/src/server/llm/testModelCall.ts b/packages/shared/src/server/llm/testModelCall.ts
index 74bd2d2b69..437f2270fd 100644
--- a/packages/shared/src/server/llm/testModelCall.ts
+++ b/packages/shared/src/server/llm/testModelCall.ts
@@ -2,14 +2,17 @@ import {
ChatMessageRole,
ChatMessageType,
LLMApiKeySchema,
+ type LLMJSONSchema,
type ModelConfig,
} from "./types";
-import { fetchLLMCompletion } from "./fetchLLMCompletion";
-import z from "zod";
+import {
+ createLLMOutput,
+ generateLLMText,
+ mapLegacyLLMCompletionParams,
+} from "./llmText";
+import z, { type ZodType } from "zod";
-type StructuredOutputSchema = NonNullable<
- Parameters<typeof fetchLLMCompletion>[0]["structuredOutputSchema"]
->;
+type StructuredOutputSchema = ZodType | LLMJSONSchema;
export const testModelCall = async ({
provider,
@@ -24,28 +27,31 @@ export const testModelCall = async ({
modelConfig?: ModelConfig | null;
structuredOutputSchema?: StructuredOutputSchema;
}) => {
- await fetchLLMCompletion({
- streaming: false,
- llmConnection: apiKey,
- messages: [
- {
- role: ChatMessageRole.User,
- content:
- 'Extract a score (1-5) and reasoning from this text: "This is a test. It worked perfectly because it matched all passing criteria."',
- type: ChatMessageType.User,
+ const schema =
+ structuredOutputSchema ??
+ z.object({
+ score: z.string(),
+ reasoning: z.string(),
+ });
+
+ await generateLLMText({
+ ...mapLegacyLLMCompletionParams({
+ connection: apiKey,
+ messages: [
+ {
+ role: ChatMessageRole.User,
+ content:
+ 'Extract a score (1-5) and reasoning from this text: "This is a test. It worked perfectly because it matched all passing criteria."',
+ type: ChatMessageType.User,
+ },
+ ],
+ modelParams: {
+ provider,
+ model,
+ adapter: apiKey.adapter,
+ ...modelConfig,
},
- ],
- modelParams: {
- provider: provider,
- model: model,
- adapter: apiKey.adapter,
- ...modelConfig,
- },
- structuredOutputSchema:
- structuredOutputSchema ??
- z.object({
- score: z.string(),
- reasoning: z.string(),
- }),
+ }),
+ output: createLLMOutput(schema),
});
};
diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.ts
index 1a258d28ff..cb82ec79b2 100644
--- a/packages/shared/src/server/llm/types.ts
+++ b/packages/shared/src/server/llm/types.ts
@@ -95,10 +95,9 @@ export const OpenAIResponseFormatSchema = z.object({
}),
});
-// Standard ContentBlock shape per @langchain/core. fetchLLMCompletion routes
-// every provider through `AIMessage#contentBlocks`, so every element in the
-// array variant carries a `type` discriminator and the well-known fields for
-// that type (e.g. `text` for "text", `value` for "non_standard").
+// Legacy playground tool-call content can be either text or an array of
+// provider-normalized blocks. Keep the discriminator loose while persisted
+// responses migrate to native AI SDK tool-call results.
const StandardContentBlockSchema = z
.object({
type: z.string(),
@@ -245,8 +244,8 @@ export enum LLMAdapter {
GoogleAIStudio = "google-ai-studio",
}
-// Some providers require at least 1 user message; both execution engines
-// convert a lone message into a user message for them.
+// Some providers require at least one user message. The persisted-message
+// conversion boundary turns a lone message into a user message for them.
export const PROVIDERS_WITH_REQUIRED_USER_MESSAGE: readonly LLMAdapter[] = [
LLMAdapter.VertexAI,
LLMAdapter.GoogleAIStudio,
@@ -367,75 +366,6 @@ export const openAIModels = [
"gpt-3.5-turbo",
] as const;
-type OpenAIReasoningMap = Record<OpenAIModel, boolean>;
-export const openAIModelToReasoning: OpenAIReasoningMap = {
- // reasoning models
- "gpt-5.6-sol": true,
- "gpt-5.6-terra": true,
- "gpt-5.6-luna": true,
- "gpt-5.5": true,
- "gpt-5.5-2026-04-23": true,
- "gpt-5.5-pro": true,
- "gpt-5.5-pro-2026-04-23": true,
- "gpt-5.4": true,
- "gpt-5.4-2026-03-05": true,
- "gpt-5.4-pro": true,
- "gpt-5.4-pro-2026-03-05": true,
- "gpt-5.2-2025-12-11": true,
- "gpt-5.1": true,
- "gpt-5.1-2025-11-13": true,
- "gpt-5": true,
- "gpt-5-2025-08-07": true,
- "gpt-5-mini": true,
- "gpt-5-mini-2025-08-07": true,
- "gpt-5-nano": true,
- "gpt-5-nano-2025-08-07": true,
- o3: true,
- "o3-2025-04-16": true,
- "o4-mini": true,
- "o4-mini-2025-04-16": true,
- "o3-mini": true,
- "o3-mini-2025-01-31": true,
- "o1-preview": true,
- "o1-preview-2024-09-12": true,
- "o1-mini": true,
- "o1-mini-2024-09-12": true,
- // non-reasoning models
- "gpt-4.5-preview": false,
- "gpt-4.5-preview-2025-02-27": false,
- "gpt-4-turbo-preview": false,
- "gpt-4-1106-preview": false,
- "gpt-4-0613": false,
- "gpt-4-0125-preview": false,
- "gpt-4": false,
- "gpt-3.5-turbo-16k-0613": false,
- "gpt-3.5-turbo-16k": false,
- "gpt-3.5-turbo-1106": false,
- "gpt-3.5-turbo-0613": false,
- "gpt-3.5-turbo-0301": false,
- "gpt-3.5-turbo-0125": false,
- "gpt-3.5-turbo": false,
- "gpt-4.1": false,
- "gpt-4.1-2025-04-14": false,
- "gpt-4.1-mini": false,
- "gpt-4.1-mini-2025-04-14": false,
- "gpt-4.1-nano": false,
- "gpt-4.1-nano-2025-04-14": false,
- "gpt-5.4-mini": false,
- "gpt-5.4-mini-2026-03-17": false,
- "gpt-5.4-nano": false,
- "gpt-5.4-nano-2026-03-17": false,
- "gpt-4o": false,
- "gpt-4o-2024-08-06": false,
- "gpt-4o-2024-05-13": false,
- "gpt-4o-mini": false,
- "gpt-4o-mini-2024-07-18": false,
-};
-
-export const isOpenAIReasoningModel = (model: OpenAIModel): boolean => {
- return openAIModelToReasoning[model];
-};
-
export type OpenAIModel = (typeof openAIModels)[number];
// NOTE: Update docs page when changing this! https://langfuse.com/docs/prompt-management/features/playground#openai-playground--anthropic-playground
diff --git a/packages/shared/src/server/llm/utils.ts b/packages/shared/src/server/llm/utils.ts
index d586a995fa..11f0072d3c 100644
--- a/packages/shared/src/server/llm/utils.ts
+++ b/packages/shared/src/server/llm/utils.ts
@@ -1,48 +1,9 @@
import { z } from "zod";
import { decrypt } from "../../encryption";
-import { LLMAdapter } from "./types";
const ExtraHeaderSchema = z.record(z.string(), z.string());
-export const RUNTIME_TIMEOUT_ADAPTERS = new Set<LLMAdapter>(
- Object.values(LLMAdapter),
-);
-
-export async function executeWithRuntimeTimeout<T>({
- enabled,
- timeoutMs,
- abortController,
- operation,
-}: {
- enabled: boolean;
- timeoutMs: number;
- abortController?: AbortController;
- operation: () => Promise<T>;
-}): Promise<T> {
- if (!enabled) {
- return operation();
- }
-
- const timeoutError = new Error(`Request timed out after ${timeoutMs}ms`);
-
- let timeoutId: ReturnType<typeof setTimeout> | undefined;
-
- try {
- return await Promise.race([
- operation(),
- new Promise<never>((_, reject) => {
- timeoutId = setTimeout(() => {
- abortController?.abort(timeoutError);
- reject(timeoutError);
- }, timeoutMs);
- }),
- ]);
- } finally {
- if (timeoutId) clearTimeout(timeoutId);
- }
-}
-
export function decryptAndParseExtraHeaders(
extraHeaders: string | null | undefined,
) {
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index 917e869c2f..1607857d5c 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -69,7 +69,7 @@ export const OtelIngestionEvent = z.object({
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
+ // executions published by the internal AI SDK LLM runtime). 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
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e9f6f70e26..6f100440d1 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -197,9 +197,6 @@ importers:
'@ai-sdk/openai':
specifier: ^4.0.0
version: 4.0.5([email protected])
- '@anthropic-ai/vertex-sdk':
- specifier: ^0.17.1
- version: 0.17.1([email protected])
'@aws-sdk/client-cloudwatch':
specifier: 'catalog:'
version: 3.1056.0
@@ -230,21 +227,6 @@ importers:
'@google-cloud/storage':
specifier: ^7.19.0
version: 7.19.0
- '@langchain/anthropic':
- specifier: ^1.3.26
- version: 1.3.26(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
- '@langchain/aws':
- specifier: ^1.3.4
- version: 1.3.4(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
- '@langchain/core':
- specifier: ^1.1.48
- version: 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
- '@langchain/google':
- specifier: ^0.1.11
- version: 0.1.11(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
- '@langchain/openai':
- specifier: ^1.4.2
'@opentelemetry/api':
specifier: '>=1.0.0 <1.10.0'
version: 1.9.1
@@ -317,9 +299,6 @@ importers:
jsonpath-plus:
specifier: 10.3.0
version: 10.3.0
- langchain:
- specifier: ^1.3.0
langfuse-langchain:
specifier: 3.38.20
@@ -477,9 +456,6 @@ importers:
'@hookform/resolvers':
specifier: ^5.2.2
- '@langchain/core':
- specifier: ^1.1.48
- version: 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
'@langfuse/shared':
specifier: workspace:*
version: link:../packages/shared
@@ -1354,30 +1330,9 @@ packages:
resolution: {integrity: sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ==}
- '@anthropic-ai/[email protected]':
- resolution: {integrity: sha512-gGACa/+IaiXzRRmF96aOhamoBgapKRBiFWbmmTFP8aMkpaEcuStF+Q61bjo4vPxBM7gqWJNZqsngslRdnLHv0Q==}
- hasBin: true
- peerDependencies:
- zod: 4.3.6
- peerDependenciesMeta:
- zod:
- optional: true
-
- '@anthropic-ai/[email protected]':
- resolution: {integrity: sha512-srbJV7JKsc5cQ6eVuFzjZO7UR3xEPJqPamHFIe29bs38Ij2IripoAhC0S5NslNbaFUYqBKypmmpzMTpqfHEUDw==}
- hasBin: true
- peerDependencies:
- zod: 4.3.6
- peerDependenciesMeta:
- zod:
- optional: true
-
'@anthropic-ai/[email protected]':
resolution: {integrity: sha512-EHRKbxlxlc8W4KCBEseByJ7YwyYCmgu9OyN59H9+IYIGPoKv8tXyQXinkeGDI+cI8Tiuz9wk2jZb/kK7AyvL7g==}
- '@anthropic-ai/[email protected]':
- resolution: {integrity: sha512-+am1LjqEpb7Qq/fKDdu0PTE2U9+XSPXSSr9Fa5dvJ8FtJ5L9XOroNBnr7iecT+6iGlbiV6BYgMIGkAwPuly/jA==}
-
'@apm-js-collab/[email protected]':
resolution: {integrity: sha512-YxLBY5nGlurL7QeJLq6e5g0ouBpAp0pwgyA/5rHXEXwhiPLn9ZHbT+Y2LlP90GT872cSocfjWRYu/fnpuBudNQ==}
engines: {node: '>=18.0.0'}
@@ -2744,12 +2699,6 @@ packages:
peerDependencies:
jsep: ^0.4.0||^1.0.0
- '@langchain/[email protected]':
- resolution: {integrity: sha512-8gfnM1MzZkb3HVD0WjWeb/HFdP4cNGWSokhBtrwW0qSJN+b1j9oBMwWZaVdd+VBKsx4hqzv0bdrMzWje0TMw+g==}
- engines: {node: '>=20'}
- peerDependencies:
- '@langchain/core': ^1.1.38
-
'@langchain/[email protected]':
resolution: {integrity: sha512-95gDgENjUoD2uvEFb2SrdY47u2W0hA/dgY1jLYSU7AXf5Nt+roVyl399c9WaBUyUalSETLGubBOhTZNG8IdGvQ==}
engines: {node: '>=20'}
@@ -2760,12 +2709,6 @@ packages:
resolution: {integrity: sha512-fQU6Guyb1pwc2fEplmA8FPbKfOMAofjnyJzExevro0FxEiuGHE18Ov/ZHmT9trWCDTZRI9eW1VIc6aChxV8pAQ==}
engines: {node: '>=20'}
- '@langchain/[email protected]':
- resolution: {integrity: sha512-c7E77jfRGGg8j2F/OGEfzsTBsA7UbzctnaqDHC9GHQdXosfTuAgsae2Z8wjp7DY4ikjCBk8kKEtKo2AjFEfgKw==}
- engines: {node: '>=20'}
- peerDependencies:
- '@langchain/core': ^1.0.0
-
'@langchain/[email protected]':
resolution: {integrity: sha512-HM0cJLRpIsSlWBQ/xuDC67l52SqZ62Bh2Y61DX+Xorqwoh5e1KxYvfCD7GnSTbWWhjBOutvnR0vPhu4orFkZfw==}
engines: {node: '>=18'}
@@ -5131,9 +5074,6 @@ packages:
resolution: {integrity: sha512-ZS7Y5X8mU9qRSsqwOeGKw86WWtPsRxa396kX2HyhYwADRqFHJ0cb3p2uFk6QnFF3BluUUBHTZJpPA9QuEl0tlg==}
engines: {node: '>=18.0.0'}
- '@stablelib/[email protected]':
- resolution: {integrity: sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==}
-
'@standard-community/[email protected]':
resolution: {integrity: sha512-4+ZPorwDRt47i+O7RjyuaxHRK/37QY/LmgxlGrRrSTLYoFatEOzvqIc85GTlM18SFZ5E91C+v0o/M37wZPpUHA==}
peerDependencies:
@@ -7798,9 +7738,6 @@ packages:
resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==}
- resolution: {integrity: sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==}
-
resolution: {integrity: sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==}
@@ -8694,10 +8631,6 @@ packages:
resolution: {integrity: sha512-IMF9QGFn/j7sys1LxgYpt/+0LUozFE8R/yUav4D7NqsHnh5L0mbJZOiU724nlJ3g+ZZo6NykVtTeJLoVcOP6Xw==}
hasBin: true
- resolution: {integrity: sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==}
- engines: {node: '>=16'}
-
resolution: {integrity: sha512-fRr1mHgZ7hboLKBUdR428gd9dIHUFGivUqOeiDcSmyXkNZCtB1uGaZLvsjZ4GaN5pwBIs+TGIOf6s+Rp5/R/zA==}
hasBin: true
@@ -10732,9 +10665,6 @@ packages:
resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==}
- resolution: {integrity: sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==}
-
resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==}
engines: {node: '>= 0.8'}
@@ -11095,9 +11025,6 @@ packages:
resolution: {integrity: sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==}
- resolution: {integrity: sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==}
-
resolution: {integrity: sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==}
engines: {node: '>=18.12'}
@@ -12038,33 +11965,11 @@ snapshots:
package-manager-detector: 1.6.0
tinyexec: 1.1.2
- dependencies:
- json-schema-to-ts: 3.1.1
- standardwebhooks: 1.0.0
- optionalDependencies:
- zod: 4.3.6
-
- dependencies:
- json-schema-to-ts: 3.1.1
- optionalDependencies:
- zod: 4.3.6
-
'@anthropic-ai/[email protected]':
dependencies:
'@types/node': 18.19.123
tiktoken: 1.0.20
- dependencies:
- '@anthropic-ai/sdk': 0.104.1([email protected])
- google-auth-library: 9.15.1
- transitivePeerDependencies:
- - encoding
- - supports-color
- - zod
-
'@apm-js-collab/[email protected]':
dependencies:
'@apm-js-collab/code-transformer': 0.15.0
@@ -12199,6 +12104,7 @@ snapshots:
tslib: 2.8.1
transitivePeerDependencies:
- aws-crt
+ optional: true
'@aws-sdk/[email protected]':
dependencies:
@@ -12251,6 +12157,7 @@ snapshots:
tslib: 2.8.1
transitivePeerDependencies:
- aws-crt
+ optional: true
'@aws-sdk/[email protected]':
dependencies:
@@ -12322,6 +12229,7 @@ snapshots:
tslib: 2.8.1
transitivePeerDependencies:
- aws-crt
+ optional: true
'@aws-sdk/[email protected]':
dependencies:
@@ -12500,6 +12408,7 @@ snapshots:
'@smithy/eventstream-codec': 4.4.5
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
'@aws-sdk/[email protected](@aws-sdk/[email protected])':
dependencies:
@@ -12522,6 +12431,7 @@ snapshots:
'@smithy/protocol-http': 5.4.0
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
'@aws-sdk/[email protected]':
dependencies:
@@ -12539,6 +12449,7 @@ snapshots:
'@smithy/core': 3.29.1
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
'@aws-sdk/[email protected]':
dependencies:
@@ -12550,6 +12461,7 @@ snapshots:
'@aws-sdk/types': 3.973.15
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
'@aws-sdk/[email protected]':
dependencies:
@@ -12558,6 +12470,7 @@ snapshots:
'@smithy/core': 3.29.1
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
'@aws-sdk/[email protected]':
dependencies:
@@ -12581,6 +12494,7 @@ snapshots:
'@smithy/core': 3.29.1
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
'@aws-sdk/[email protected]':
dependencies:
@@ -12596,6 +12510,7 @@ snapshots:
'@smithy/util-hex-encoding': 4.2.2
'@smithy/util-utf8': 4.4.5
tslib: 2.8.1
+ optional: true
'@aws-sdk/[email protected]':
dependencies:
@@ -12616,6 +12531,7 @@ snapshots:
'@smithy/core': 3.29.1
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
'@aws-sdk/[email protected]':
dependencies:
@@ -12642,6 +12558,7 @@ snapshots:
'@smithy/shared-ini-file-loader': 4.5.0
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
'@aws-sdk/[email protected]':
dependencies:
@@ -12663,6 +12580,7 @@ snapshots:
'@smithy/core': 3.29.1
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
'@aws-sdk/[email protected]':
dependencies:
@@ -12670,6 +12588,7 @@ snapshots:
'@smithy/querystring-builder': 4.2.12
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
'@aws-sdk/[email protected]':
dependencies:
@@ -12681,6 +12600,7 @@ snapshots:
'@smithy/types': 4.15.1
bowser: 2.14.1
tslib: 2.8.1
+ optional: true
'@aws-sdk/[email protected]':
dependencies:
@@ -12689,13 +12609,15 @@ snapshots:
'@smithy/core': 3.29.1
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
'@aws-sdk/[email protected]':
dependencies:
'@smithy/types': 4.15.1
tslib: 2.8.1
- '@aws/[email protected]': {}
+ optional: true
'@aws/[email protected]': {}
@@ -13882,12 +13804,6 @@ snapshots:
dependencies:
jsep: 1.4.0
- dependencies:
- '@anthropic-ai/sdk': 0.74.0([email protected])
- '@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
- zod: 4.3.6
-
dependencies:
'@aws-sdk/client-bedrock-agent-runtime': 3.1024.0
@@ -13897,6 +13813,7 @@ snapshots:
'@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
transitivePeerDependencies:
- aws-crt
+ optional: true
dependencies:
@@ -13914,15 +13831,6 @@ snapshots:
- openai
- ws
- dependencies:
- '@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
- eventsource-parser: 3.0.8
- google-auth-library: 10.6.2
- jose: 6.2.3
- transitivePeerDependencies:
- - supports-color
-
dependencies:
'@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
@@ -13975,6 +13883,7 @@ snapshots:
zod: 4.3.6
transitivePeerDependencies:
- ws
+ optional: true
'@langchain/[email protected]': {}
@@ -16121,6 +16030,7 @@ snapshots:
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
@@ -16143,23 +16053,27 @@ snapshots:
'@smithy/eventstream-serde-universal': 4.2.12
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
'@smithy/eventstream-serde-universal': 4.2.12
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
'@smithy/eventstream-codec': 4.4.5
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
@@ -16171,11 +16085,13 @@ snapshots:
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
@@ -16184,6 +16100,7 @@ snapshots:
'@smithy/[email protected]':
dependencies:
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
@@ -16196,31 +16113,37 @@ snapshots:
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
@@ -16239,6 +16162,7 @@ snapshots:
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
@@ -16255,6 +16179,7 @@ snapshots:
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
@@ -16267,6 +16192,7 @@ snapshots:
'@smithy/core': 3.29.1
'@smithy/types': 4.15.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
@@ -16276,20 +16202,24 @@ snapshots:
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
'@smithy/util-buffer-from': 4.2.2
'@smithy/util-utf8': 4.4.5
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
@@ -16300,40 +16230,48 @@ snapshots:
dependencies:
'@smithy/is-array-buffer': 4.2.2
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
'@smithy/core': 3.29.1
tslib: 2.8.1
+ optional: true
'@smithy/[email protected]':
dependencies:
@@ -16349,8 +16287,6 @@ snapshots:
'@smithy/core': 3.29.1
tslib: 2.8.1
- '@stablelib/[email protected]': {}
-
dependencies:
'@standard-schema/spec': 1.1.0
@@ -19357,8 +19293,6 @@ snapshots:
-
@@ -20348,11 +20282,6 @@ snapshots:
- dependencies:
- '@babel/runtime': 7.29.2
- ts-algebra: 2.0.0
-
@@ -21471,6 +21400,7 @@ snapshots:
optionalDependencies:
ws: 8.21.0
zod: 4.3.6
+ optional: true
@@ -22835,11 +22765,6 @@ snapshots:
- dependencies:
- '@stablelib/base64': 1.0.1
- fast-sha256: 1.3.0
-
@@ -23191,8 +23116,6 @@ snapshots:
-
dependencies:
typescript: 6.0.3
diff --git a/web/package.json b/web/package.json
index a15da39b10..5f60c7b312 100644
--- a/web/package.json
+++ b/web/package.json
@@ -52,7 +52,6 @@
"@dnd-kit/utilities": "^3.2.2",
"@ferrucc-io/emoji-picker": "^0.0.47",
"@hookform/resolvers": "^5.2.2",
- "@langchain/core": "^1.1.48",
"@langfuse/shared": "workspace:*",
"@lezer/highlight": "^1.2.3",
"@mastra/client-js": "1.21.1",
diff --git a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts b/web/src/__tests__/server/in-app-agent-persistence.servertest.ts
index 4302a0fe34..38b6b3b012 100644
--- a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-persistence.servertest.ts
@@ -2,7 +2,7 @@ vi.mock("@langfuse/shared/src/server", async () => {
const actual = await vi.importActual("@langfuse/shared/src/server");
return {
...actual,
- fetchLLMCompletion: vi.fn(),
+ generateLLMText: vi.fn(),
};
});
@@ -16,7 +16,7 @@ import type { Plan } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import {
createOrgProjectAndApiKey,
- fetchLLMCompletion,
+ generateLLMText,
} from "@langfuse/shared/src/server";
import { env } from "@/src/env.mjs";
import {
@@ -42,7 +42,7 @@ vi.mock("@/src/server/auth", () => ({
getServerAuthSession: vi.fn(),
}));
-const mockFetchLLMCompletion = vi.mocked(fetchLLMCompletion);
+const mockGenerateLLMText = vi.mocked(generateLLMText);
describe("in-app agent persistence", () => {
const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
@@ -53,7 +53,7 @@ describe("in-app agent persistence", () => {
afterEach(() => {
(env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;
- mockFetchLLMCompletion.mockReset();
+ mockGenerateLLMText.mockReset();
});
const createCaller = async (
@@ -478,7 +478,7 @@ describe("in-app agent persistence", () => {
title: "My custom title",
renamedByUserAt: expect.any(Date),
});
- expect(mockFetchLLMCompletion).not.toHaveBeenCalled();
+ expect(mockGenerateLLMText).not.toHaveBeenCalled();
} finally {
(env as any).LANGFUSE_AWS_BEDROCK_SMALL_MODEL = originalBedrockSmallModel;
}
@@ -504,7 +504,7 @@ describe("in-app agent persistence", () => {
try {
(env as any).LANGFUSE_AWS_BEDROCK_SMALL_MODEL = "small-title-model";
- mockFetchLLMCompletion.mockRejectedValue(new Error("Bedrock failed"));
+ mockGenerateLLMText.mockRejectedValue(new Error("Bedrock failed"));
await expect(
maybeInferAndPersistConversationTitle({
diff --git a/web/src/__tests__/server/llm-api-key.servertest.ts b/web/src/__tests__/server/llm-api-key.servertest.ts
index ae67b3d159..aa04be8941 100644
--- a/web/src/__tests__/server/llm-api-key.servertest.ts
+++ b/web/src/__tests__/server/llm-api-key.servertest.ts
@@ -2,7 +2,7 @@ vi.mock("@langfuse/shared/src/server", async () => {
const actual = await vi.importActual("@langfuse/shared/src/server");
return {
...actual,
- fetchLLMCompletion: vi.fn(),
+ generateLLMText: vi.fn(),
};
});
@@ -16,10 +16,10 @@ import { decrypt, encrypt } from "@langfuse/shared/encryption";
import { AuthMethod } from "@/src/features/llm-api-key/types";
import {
createOrgProjectAndApiKey,
- fetchLLMCompletion,
+ generateLLMText,
} from "@langfuse/shared/src/server";
-const mockFetchLLMCompletion = vi.mocked(fetchLLMCompletion);
+const mockGenerateLLMText = vi.mocked(generateLLMText);
describe("llmApiKey.all RPC", () => {
let projectId: string;
@@ -62,9 +62,7 @@ describe("llmApiKey.all RPC", () => {
const setup = await createOrgProjectAndApiKey();
projectId = setup.projectId;
orgId = setup.orgId;
- mockFetchLLMCompletion
- .mockReset()
- .mockResolvedValue({} as Awaited<ReturnType<typeof fetchLLMCompletion>>);
+ mockGenerateLLMText.mockReset().mockResolvedValue({} as never);
session = {
expires: "1",
@@ -487,7 +485,7 @@ describe("llmApiKey.all RPC", () => {
success: false,
error: "Secret key is required when changing the base URL",
});
- expect(mockFetchLLMCompletion).not.toHaveBeenCalled();
+ expect(mockGenerateLLMText).not.toHaveBeenCalled();
});
it("should allow testing an existing connection with an unchanged localhost base URL", async () => {
@@ -512,7 +510,7 @@ describe("llmApiKey.all RPC", () => {
});
expect(result).toEqual({ success: true });
- expect(mockFetchLLMCompletion).toHaveBeenCalledTimes(1);
+ expect(mockGenerateLLMText).toHaveBeenCalledTimes(1);
});
it("should allow testUpdate without a new secret key when the base URL is unchanged", async () => {
@@ -546,11 +544,16 @@ describe("llmApiKey.all RPC", () => {
});
expect(result).toEqual({ success: true });
- expect(mockFetchLLMCompletion).toHaveBeenCalledTimes(1);
- const llmConnection = mockFetchLLMCompletion.mock.calls[0][0].llmConnection;
- expect(llmConnection.baseURL).toBe("https://api.openai.com/v1");
- expect(decrypt(llmConnection.secretKey)).toBe("sk-original");
- expect(JSON.parse(decrypt(llmConnection.extraHeaders!))).toEqual(
+ expect(mockGenerateLLMText).toHaveBeenCalledTimes(1);
+ const connection = mockGenerateLLMText.mock.calls[0][0].connection;
+ expect(connection.baseURL).toBe("https://api.openai.com/v1");
+ expect(decrypt(connection.secretKey)).toBe("sk-original");
+ const encryptedExtraHeaders = connection.extraHeaders;
+ expect(encryptedExtraHeaders).toBeTruthy();
+ if (!encryptedExtraHeaders) {
+ throw new Error("Expected extra headers to be preserved");
+ }
+ expect(JSON.parse(decrypt(encryptedExtraHeaders))).toEqual(
existingExtraHeaders,
);
});
@@ -587,11 +590,11 @@ describe("llmApiKey.all RPC", () => {
});
expect(result).toEqual({ success: true });
- expect(mockFetchLLMCompletion).toHaveBeenCalledTimes(1);
- const llmConnection = mockFetchLLMCompletion.mock.calls[0][0].llmConnection;
- expect(llmConnection.baseURL).toBe("https://example.net/v1");
- expect(decrypt(llmConnection.secretKey)).toBe("sk-rotated");
- expect(llmConnection.extraHeaders).toBeUndefined();
+ expect(mockGenerateLLMText).toHaveBeenCalledTimes(1);
+ const connection = mockGenerateLLMText.mock.calls[0][0].connection;
+ expect(connection.baseURL).toBe("https://example.net/v1");
+ expect(decrypt(connection.secretKey)).toBe("sk-rotated");
+ expect(connection.extraHeaders).toBeUndefined();
});
it("should create and update an llm api key", async () => {
diff --git a/web/src/__tests__/server/unit/chat-completion-handler.servertest.ts b/web/src/__tests__/server/unit/chat-completion-handler.servertest.ts
new file mode 100644
index 0000000000..6da7b6383d
--- /dev/null
+++ b/web/src/__tests__/server/unit/chat-completion-handler.servertest.ts
@@ -0,0 +1,203 @@
+import { NextRequest } from "next/server";
+import type * as SharedServer from "@langfuse/shared/src/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ authorize: vi.fn(),
+ createOutput: vi.fn(),
+ createToolSet: vi.fn(),
+ findConnection: vi.fn(),
+ generate: vi.fn(),
+ mapLegacyParams: vi.fn(),
+ stream: vi.fn(),
+}));
+
+vi.mock("@/src/env.mjs", () => ({
+ env: { LANGFUSE_BLOCKED_USERIDS_CHATCOMPLETION: new Map() },
+}));
+
+vi.mock("@/src/features/playground/server/authorizeRequest", () => ({
+ authorizeRequestOrThrow: mocks.authorize,
+}));
+
+vi.mock("@langfuse/shared/src/db", () => ({
+ prisma: { llmApiKeys: { findFirst: mocks.findConnection } },
+}));
+
+vi.mock("@opentelemetry/api", () => ({
+ context: {
+ with: (_context: unknown, callback: () => unknown) => callback(),
+ },
+}));
+
+vi.mock("@langfuse/shared/src/server", async (importOriginal) => {
+ const actual = await importOriginal<typeof SharedServer>();
+
+ return {
+ ...actual,
+ LLMApiKeySchema: {
+ safeParse: (connection: unknown) => ({ success: true, data: connection }),
+ },
+ contextWithLangfuseProps: vi.fn(() => ({})),
+ createLLMOutput: mocks.createOutput,
+ createLLMToolSet: mocks.createToolSet,
+ generateLLMText: mocks.generate,
+ mapLegacyLLMCompletionParams: mocks.mapLegacyParams,
+ streamLLMText: mocks.stream,
+ };
+});
+
+import chatCompletionHandler from "@/src/features/playground/server/chatCompletionHandler";
+
+const baseBody = {
+ projectId: "project-1",
+ messages: [{ role: "user", type: "user", content: "Hello" }],
+ modelParams: {
+ provider: "openai",
+ adapter: "openai",
+ model: "gpt-4.1",
+ },
+ streaming: false,
+};
+
+function createRequest(body: Record<string, unknown>) {
+ return new NextRequest("http://localhost/api/chatCompletion", {
+ method: "POST",
+ body: JSON.stringify(body),
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+describe("chatCompletionHandler", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.authorize.mockResolvedValue({ userId: "user-1" });
+ mocks.findConnection.mockResolvedValue({
+ id: "connection-1",
+ secretKey: "encrypted-key",
+ });
+ mocks.mapLegacyParams.mockReturnValue({
+ model: { adapter: "openai", id: "gpt-4.1" },
+ connection: { secretKey: "encrypted-key" },
+ messages: [{ role: "user", content: "Hello" }],
+ });
+ });
+
+ it("maps a native text result to the existing playground JSON response", async () => {
+ mocks.generate.mockResolvedValue({
+ text: "Hello back",
+ finalStep: { reasoningText: "A short reason" },
+ });
+
+ const response = await chatCompletionHandler(createRequest(baseBody));
+
+ await expect(response.json()).resolves.toEqual({
+ content: "Hello back",
+ reasoning: "A short reason",
+ });
+ expect(mocks.generate).toHaveBeenCalledWith({
+ model: { adapter: "openai", id: "gpt-4.1" },
+ connection: { secretKey: "encrypted-key" },
+ messages: [{ role: "user", content: "Hello" }],
+ });
+ });
+
+ it("returns only the generated structured output", async () => {
+ const output = { kind: "object-output" };
+ mocks.createOutput.mockReturnValue(output);
+ mocks.generate.mockResolvedValue({ output: { answer: 42 } });
+
+ const response = await chatCompletionHandler(
+ createRequest({
+ ...baseBody,
+ structuredOutputSchema: {
+ type: "object",
+ properties: { answer: { type: "number" } },
+ required: ["answer"],
+ },
+ }),
+ );
+
+ await expect(response.json()).resolves.toEqual({ answer: 42 });
+ expect(mocks.generate).toHaveBeenCalledWith(
+ expect.objectContaining({ output }),
+ );
+ });
+
+ it("maps native tool calls to the legacy playground tool_calls shape", async () => {
+ const toolSet = { lookup: { description: "Look up a value" } };
+ mocks.createToolSet.mockReturnValue(toolSet);
+ mocks.generate.mockResolvedValue({
+ text: "",
+ finalStep: { reasoningText: "I need the tool" },
+ toolCalls: [
+ {
+ toolName: "lookup",
+ toolCallId: "call-1",
+ input: { key: "value" },
+ },
+ ],
+ });
+
+ const response = await chatCompletionHandler(
+ createRequest({
+ ...baseBody,
+ tools: [
+ {
+ name: "lookup",
+ description: "Look up a value",
+ parameters: {
+ type: "object",
+ properties: { key: { type: "string" } },
+ required: ["key"],
+ },
+ },
+ ],
+ }),
+ );
+
+ await expect(response.json()).resolves.toEqual({
+ content: "",
+ tool_calls: [{ name: "lookup", id: "call-1", args: { key: "value" } }],
+ reasoning: "I need the tool",
+ });
+ expect(mocks.generate).toHaveBeenCalledWith(
+ expect.objectContaining({ tools: toolSet }),
+ );
+ });
+
+ it("preserves the text/plain streaming response", async () => {
+ const textStream = new ReadableStream<string>({
+ start(controller) {
+ controller.enqueue("streamed text");
+ controller.close();
+ },
+ });
+ mocks.stream.mockResolvedValue({ textStream });
+
+ const response = await chatCompletionHandler(
+ createRequest({ ...baseBody, streaming: true }),
+ );
+
+ await expect(response.text()).resolves.toBe("streamed text");
+ expect(response.headers.get("content-type")).toBe(
+ "text/plain; charset=utf-8",
+ );
+ expect(mocks.generate).not.toHaveBeenCalled();
+ });
+
+ it("preserves terminal LLM configuration status codes", async () => {
+ const error = new Error("Unsupported provider options: unknown_parameter");
+ error.name = "LLMCompletionError";
+ Object.assign(error, { responseStatusCode: 400, isRetryable: false });
+ mocks.generate.mockRejectedValue(error);
+
+ const response = await chatCompletionHandler(createRequest(baseBody));
+
+ expect(response.status).toBe(400);
+ await expect(response.json()).resolves.toEqual({
+ error: "LLMCompletionError",
+ message: "Unsupported provider options: unknown_parameter",
+ });
+ });
+});
diff --git a/web/src/ee/features/in-app-agent/server/persistence.ts b/web/src/ee/features/in-app-agent/server/persistence.ts
index 9a1093070f..059d308a87 100644
--- a/web/src/ee/features/in-app-agent/server/persistence.ts
+++ b/web/src/ee/features/in-app-agent/server/persistence.ts
@@ -16,7 +16,7 @@ import type {
import { env } from "@/src/env.mjs";
import {
- fetchLangfuseAICompletion,
+ generateLangfuseAIText,
getLangfuseAITraceSinkParams,
} from "@/src/features/ai-features/server/bedrockCompletion";
import { truncate } from "@/src/utils/string";
@@ -368,7 +368,7 @@ export async function maybeInferAndPersistConversationTitle(params: {
return;
}
- const completion = await fetchLangfuseAICompletion({
+ const completion = await generateLangfuseAIText({
messages: [
{
role: ChatMessageRole.System,
@@ -438,14 +438,11 @@ ${JSON.stringify(transcript, null, 2)}
: undefined,
});
- const completionText =
- typeof completion === "string" ? completion : completion.text;
-
- if (!completionText) {
+ if (!completion) {
return;
}
- const title = completionText.trim();
+ const title = completion.trim();
if (!title) {
return;
diff --git a/web/src/features/ai-features/server/bedrockCompletion.ts b/web/src/features/ai-features/server/bedrockCompletion.ts
index d3b53a9391..9d61500764 100644
--- a/web/src/features/ai-features/server/bedrockCompletion.ts
+++ b/web/src/features/ai-features/server/bedrockCompletion.ts
@@ -2,9 +2,9 @@ import { BEDROCK_USE_DEFAULT_CREDENTIALS } from "@langfuse/shared";
import { encrypt } from "@langfuse/shared/encryption";
import {
type ChatMessage,
- type CompletionWithReasoning,
- fetchLLMCompletion,
+ generateLLMText,
LLMAdapter,
+ mapLegacyLLMCompletionParams,
type TraceSinkParams,
} from "@langfuse/shared/src/server";
import { randomBytes } from "crypto";
@@ -44,35 +44,38 @@ export function getLangfuseAITraceSinkParams(params: {
};
}
-export async function fetchLangfuseAICompletion(params: {
+export async function generateLangfuseAIText(params: {
messages: ChatMessage[];
model?: string;
maxTokens?: number;
traceSinkParams?: TraceSinkParams;
-}): Promise<string | CompletionWithReasoning> {
+}): Promise<string> {
const model = params.model ?? env.LANGFUSE_AWS_BEDROCK_MODEL;
if (!model) {
throw new Error("Langfuse AI completion model is not configured.");
}
- return fetchLLMCompletion({
- messages: params.messages,
- modelParams: {
- provider: "bedrock",
- adapter: LLMAdapter.Bedrock,
- model,
- // Intentionally omit temperature/top_p: newer Bedrock models reject these
- // inference params, while AI-feature generation works at model defaults.
- ...(params.maxTokens !== undefined
- ? { max_tokens: params.maxTokens }
- : {}),
- },
- llmConnection: {
- secretKey: encrypt(BEDROCK_USE_DEFAULT_CREDENTIALS),
- },
- streaming: false,
- traceSinkParams: params.traceSinkParams,
- shouldUseLangfuseAPIKey: true,
+ const result = await generateLLMText({
+ ...mapLegacyLLMCompletionParams({
+ messages: params.messages,
+ modelParams: {
+ provider: "bedrock",
+ adapter: LLMAdapter.Bedrock,
+ model,
+ // Intentionally omit temperature/top_p: newer Bedrock models reject these
+ // inference params, while AI-feature generation works at model defaults.
+ ...(params.maxTokens !== undefined
+ ? { max_tokens: params.maxTokens }
+ : {}),
+ },
+ connection: {
+ secretKey: encrypt(BEDROCK_USE_DEFAULT_CREDENTIALS),
+ },
+ credentialSource: "langfuse",
+ }),
+ trace: params.traceSinkParams,
});
+
+ return result.text;
}
diff --git a/web/src/features/llm-api-key/server/router.ts b/web/src/features/llm-api-key/server/router.ts
index 8dfb60de8c..be1a02e139 100644
--- a/web/src/features/llm-api-key/server/router.ts
+++ b/web/src/features/llm-api-key/server/router.ts
@@ -32,9 +32,10 @@ import { findDefaultModelEvalTemplateIds } from "@/src/features/evals/server/eva
import { encrypt, decrypt } from "@langfuse/shared/encryption";
import {
ChatMessageType,
- fetchLLMCompletion,
+ generateLLMText,
LLMAdapter,
logger,
+ mapLegacyLLMCompletionParams,
decryptAndParseExtraHeaders,
blockEvaluatorConfigsInTx,
EvaluatorBlockSource,
@@ -144,21 +145,22 @@ async function testLLMConnection(
: null;
}
- await fetchLLMCompletion({
- modelParams: {
- adapter: params.adapter,
- provider: params.provider,
- model,
- },
- llmConnection: {
- secretKey: encrypt(params.secretKey),
- extraHeaders:
- params.extraHeaders && encrypt(JSON.stringify(params.extraHeaders)),
- baseURL: params.baseURL || undefined,
- config: parsedConfig,
- },
- messages: testMessages,
- streaming: false,
+ await generateLLMText({
+ ...mapLegacyLLMCompletionParams({
+ modelParams: {
+ adapter: params.adapter,
+ provider: params.provider,
+ model,
+ },
+ connection: {
+ secretKey: encrypt(params.secretKey),
+ extraHeaders:
+ params.extraHeaders && encrypt(JSON.stringify(params.extraHeaders)),
+ baseURL: params.baseURL || undefined,
+ config: parsedConfig,
+ },
+ messages: testMessages,
+ }),
maxRetries: 1,
});
diff --git a/web/src/features/natural-language-filters/server/router.ts b/web/src/features/natural-language-filters/server/router.ts
index 46a46af92d..9b5643d704 100644
--- a/web/src/features/natural-language-filters/server/router.ts
+++ b/web/src/features/natural-language-filters/server/router.ts
@@ -14,7 +14,7 @@ import { CreateNaturalLanguageFilterCompletion } from "./validation";
import { parseFiltersFromCompletion, getLangfuseClient } from "./utils";
import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import {
- fetchLangfuseAICompletion,
+ generateLangfuseAIText,
getLangfuseAITraceSinkParams,
isLangfuseAITracingConfigured,
} from "@/src/features/ai-features/server/bedrockCompletion";
@@ -118,7 +118,7 @@ export const naturalLanguageFilterRouter = createTRPCRouter({
userPrompt: input.prompt,
currentDatetime,
});
- const llmCompletion = await fetchLangfuseAICompletion({
+ const llmCompletion = await generateLangfuseAIText({
messages: messages.map((m: ChatMessage) => ({
...m,
type: ChatMessageType.PublicAPICreated,
@@ -149,10 +149,6 @@ export const naturalLanguageFilterRouter = createTRPCRouter({
`LLM completion received: ${JSON.stringify(llmCompletion, null, 2)}`,
);
- if (typeof llmCompletion !== "string") {
- throw new Error("Expected LLM completion to be a string");
- }
-
const parsedFilters = parseFiltersFromCompletion(llmCompletion);
return {
diff --git a/web/src/features/playground/server/analytics/posthogCallback.ts b/web/src/features/playground/server/analytics/posthogCallback.ts
deleted file mode 100644
index 2aa2e1c657..0000000000
--- a/web/src/features/playground/server/analytics/posthogCallback.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-import type { ValidatedChatCompletionBody } from "@/src/features/playground/server/validateChatCompletionBody";
-import { ServerPosthog } from "@/src/features/posthog-analytics/ServerPosthog";
-import type { LLMResult } from "@langchain/core/outputs";
-import { BaseCallbackHandler } from "@langchain/core/callbacks/base";
-
-import type { ChatMessage, ModelParams } from "@langfuse/shared";
-
-export class PosthogCallbackHandler extends BaseCallbackHandler {
- public name = "PosthogCallbackHandler";
- private messages: ChatMessage[];
- private modelParams: ModelParams;
- private posthog: ServerPosthog;
-
- constructor(
- public eventPrefix: string,
- public body: ValidatedChatCompletionBody,
- private userId: string,
- ) {
- super();
- this.posthog = new ServerPosthog();
- this.messages = body.messages;
- this.modelParams = body.modelParams;
- }
-
- async handleLLMEnd(output: LLMResult) {
- const generation = output.generations[0][0];
-
- if (generation) {
- const outputString = output.generations[0][0].text;
- const properties = this.getEventProperties(outputString);
-
- this.captureEvent(properties);
- await this.posthog.flush();
- }
- }
-
- private getInputLength() {
- return this.messages.reduce(
- (acc, message) => acc + message.content.length,
- 0,
- );
- }
-
- private getEventProperties(output: string): ChatCompletionEventProperties {
- return {
- outputLength: output.length,
- inputLength: this.getInputLength(),
- modelProvider: this.modelParams.provider,
- modelName: this.modelParams.model,
- };
- }
-
- private captureEvent(properties: ChatCompletionEventProperties) {
- this.posthog.capture({
- event: this.eventPrefix + "_chat_completion",
- distinctId: this.userId,
- properties,
- });
- }
-
- public async flushAsync() {
- await this.posthog.flush();
- }
-}
-
-type ChatCompletionEventProperties = {
- outputLength: number;
- inputLength: number;
- modelProvider: string;
- modelName: string;
-};
diff --git a/web/src/features/playground/server/chatCompletionHandler.ts b/web/src/features/playground/server/chatCompletionHandler.ts
index b07fce9762..8b446de9a7 100644
--- a/web/src/features/playground/server/chatCompletionHandler.ts
+++ b/web/src/features/playground/server/chatCompletionHandler.ts
@@ -7,7 +7,6 @@ import {
InvalidRequestError,
} from "@langfuse/shared";
-import { PosthogCallbackHandler } from "./analytics/posthogCallback";
import { authorizeRequestOrThrow } from "./authorizeRequest";
import { validateChatCompletionBody } from "./validateChatCompletionBody";
@@ -15,9 +14,14 @@ import { env } from "@/src/env.mjs";
import { prisma } from "@langfuse/shared/src/db";
import {
LLMApiKeySchema,
+ createLLMOutput,
+ createLLMToolSet,
+ generateLLMText,
+ isLLMCompletionError,
logger,
- fetchLLMCompletion,
contextWithLangfuseProps,
+ mapLegacyLLMCompletionParams,
+ streamLLMText,
} from "@langfuse/shared/src/server";
import * as opentelemetry from "@opentelemetry/api";
@@ -66,88 +70,96 @@ export default async function chatCompletionHandler(req: NextRequest) {
);
}
- const fetchLLMCompletionParams = {
- llmConnection: parsedKey.data,
- messages,
+ // If messages contain tool results, we include tools in the request
+ const hasToolResults = messages.some((msg) => msg.type === "tool-result");
+ // Fix empty tool_call_id values by mapping to langgraph IDs
+ const fixedMessages =
+ (tools && tools.length > 0) || hasToolResults
+ ? messages.map((msg) => {
+ if (
+ msg.type === "tool-result" &&
+ (!msg.toolCallId || msg.toolCallId === "")
+ ) {
+ const assistantMessages = messages
+ .filter(
+ (m) => m.type === "assistant-tool-call" && m.toolCalls,
+ )
+ .reverse();
+
+ // Find the first matching tool call by name
+ // Note: using 'as any' because we filtered for assistant-tool-call messages above
+ for (const prevMsg of assistantMessages) {
+ const matchingToolCall = (prevMsg as any).toolCalls.find(
+ (tc: any) => tc.name === (msg as any)._originalRole,
+ );
+ if (matchingToolCall && matchingToolCall.id) {
+ return {
+ ...msg,
+ toolCallId: matchingToolCall.id,
+ };
+ }
+ }
+ }
+
+ return msg;
+ })
+ : messages;
+
+ const completionParams = mapLegacyLLMCompletionParams({
+ connection: parsedKey.data,
+ messages: fixedMessages,
modelParams,
- structuredOutputSchema,
- callbacks: [new PosthogCallbackHandler("playground", body, userId)],
- };
+ });
if (structuredOutputSchema) {
- const result = await fetchLLMCompletion({
- ...fetchLLMCompletionParams,
- streaming: false,
- structuredOutputSchema,
+ const result = await generateLLMText({
+ ...completionParams,
+ output: createLLMOutput(structuredOutputSchema),
});
- return NextResponse.json(result);
+ return NextResponse.json(result.output);
}
- // If messages contain tool results, we include tools in the request
- const hasToolResults = messages.some((msg) => msg.type === "tool-result");
-
if ((tools && tools.length > 0) || hasToolResults) {
- // Fix empty tool_call_id values by mapping to langgraph IDs
- const fixedMessages = messages.map((msg) => {
- if (
- msg.type === "tool-result" &&
- (!msg.toolCallId || msg.toolCallId === "")
- ) {
- const assistantMessages = messages
- .filter((m) => m.type === "assistant-tool-call" && m.toolCalls)
- .reverse();
-
- // Find the first matching tool call by name
- // Note: using 'as any' because we filtered for assistant-tool-call messages above
- for (const prevMsg of assistantMessages) {
- const matchingToolCall = (prevMsg as any).toolCalls.find(
- (tc: any) => tc.name === (msg as any)._originalRole,
- );
- if (matchingToolCall && matchingToolCall.id) {
- return {
- ...msg,
- toolCallId: matchingToolCall.id,
- };
- }
- }
- }
-
- return msg;
+ const result = await generateLLMText({
+ ...completionParams,
+ tools: createLLMToolSet(tools ?? []),
});
-
- const result = await (fetchLLMCompletion as any)({
- ...fetchLLMCompletionParams,
- messages: fixedMessages,
- streaming: false,
- tools: tools ?? [],
+ return NextResponse.json({
+ content: result.text,
+ tool_calls: result.toolCalls.map((toolCall) => ({
+ name: toolCall.toolName,
+ id: toolCall.toolCallId,
+ args:
+ typeof toolCall.input === "object" &&
+ toolCall.input !== null &&
+ !Array.isArray(toolCall.input)
+ ? toolCall.input
+ : {},
+ })),
+ ...(result.finalStep.reasoningText
+ ? { reasoning: result.finalStep.reasoningText }
+ : {}),
});
- return NextResponse.json(result);
}
if (streaming) {
- const completion = await fetchLLMCompletion({
- ...fetchLLMCompletionParams,
- streaming,
- });
-
- return new Response(completion, {
- status: 200,
- headers: {
- "Content-Type": "text/plain; charset=utf-8",
+ const completion = await streamLLMText(completionParams);
+ return new Response(
+ completion.textStream.pipeThrough(new TextEncoderStream()),
+ {
+ status: 200,
+ headers: {
+ "Content-Type": "text/plain; charset=utf-8",
+ },
},
- });
- }
- const completion = await fetchLLMCompletion({
- ...fetchLLMCompletionParams,
- streaming,
- });
-
- if (typeof completion === "string") {
- return NextResponse.json({ content: completion });
+ );
}
+ const completion = await generateLLMText(completionParams);
return NextResponse.json({
content: completion.text,
- reasoning: completion.reasoning,
+ ...(completion.finalStep.reasoningText
+ ? { reasoning: completion.finalStep.reasoningText }
+ : {}),
});
});
} catch (err) {
@@ -165,7 +177,10 @@ export default async function chatCompletionHandler(req: NextRequest) {
if (err instanceof Error) {
const statusCode =
- (err as any)?.response?.status ?? (err as any)?.status ?? 500;
+ (isLLMCompletionError(err) ? err.responseStatusCode : undefined) ??
+ (err as any)?.response?.status ??
+ (err as any)?.status ??
+ 500;
const errorMessage = err.message || "An unknown error occurred";
return NextResponse.json(
diff --git a/web/src/features/search-bar/AI_FILTER_PLAN.md b/web/src/features/search-bar/AI_FILTER_PLAN.md
index 5c01fdc437..34a4bd59ba 100644
--- a/web/src/features/search-bar/AI_FILTER_PLAN.md
+++ b/web/src/features/search-bar/AI_FILTER_PLAN.md
@@ -150,7 +150,7 @@ engineering loop and authentic dogfooding.
AI-features Langfuse project via `traceSinkParams` (env
`langfuse-natural-language-filter`, traceName `search-bar-filter`,
`targetProjectId = LANGFUSE_AI_FEATURES_PROJECT_ID`), gated on org
- `aiTelemetryEnabled`. `fetchLLMCompletion` records the system+user messages and
+ `aiTelemetryEnabled`. `generateLLMText` records the system+user messages and
the raw completion.
- ❌ **Prompt is in-code** (`buildFilterPrompt.ts`, registry-derived) → no
versions, no deploy-free iteration, no prompt↔trace linkage, nothing to eval.
diff --git a/web/src/features/search-bar/server/router.ts b/web/src/features/search-bar/server/router.ts
index 0a236000e7..e87f18bf2d 100644
--- a/web/src/features/search-bar/server/router.ts
+++ b/web/src/features/search-bar/server/router.ts
@@ -30,7 +30,7 @@ import {
import { buildFilterSystemPrompt } from "./buildFilterPrompt";
import { parseGeneratedFilters } from "./parseFilterCompletion";
import {
- fetchLangfuseAICompletion,
+ generateLangfuseAIText,
getLangfuseAITraceSinkParams,
isLangfuseAITracingConfigured,
} from "@/src/features/ai-features/server/bedrockCompletion";
@@ -135,7 +135,7 @@ export const searchBarRouter = createTRPCRouter({
});
}
- const llmCompletion = await fetchLangfuseAICompletion({
+ const llmCompletion = await generateLangfuseAIText({
messages: [
{
role: ChatMessageRole.System,
@@ -180,10 +180,6 @@ export const searchBarRouter = createTRPCRouter({
: undefined,
});
- if (typeof llmCompletion !== "string") {
- throw new Error("Expected LLM completion to be a string");
- }
-
// Parse the model output and keep only the filters that round-trip to
// bar grammar — a hallucinated/non-v4 column is dropped, never applied.
// Score names are validated against the observed sets (exact keeps, a
diff --git a/worker/src/__tests__/evalService.test.ts b/worker/src/__tests__/evalService.test.ts
index 4dceeec39b..3adcbc9c10 100644
--- a/worker/src/__tests__/evalService.test.ts
+++ b/worker/src/__tests__/evalService.test.ts
@@ -34,19 +34,17 @@ import {
} from "../features/evaluation/evalService";
import { requiresDatabaseLookup } from "../features/evaluation/traceFilterUtils";
-// Mock fetchLLMCompletion module with default passthrough behavior
+// Mock the shared LLM runtime with default passthrough behavior.
vi.mock("@langfuse/shared/src/server", async () => {
const actual = await vi.importActual("@langfuse/shared/src/server");
return {
...actual,
- fetchLLMCompletion: vi
- .fn()
- .mockImplementation(actual.fetchLLMCompletion as any),
+ generateLLMText: vi.fn().mockImplementation(actual.generateLLMText as any),
};
});
// Import the mocked function
-import { fetchLLMCompletion } from "@langfuse/shared/src/server";
+import { generateLLMText } from "@langfuse/shared/src/server";
import { UnrecoverableError } from "../errors/UnrecoverableError";
let OPENAI_API_KEY = process.env.OPENAI_API_KEY;
@@ -1954,15 +1952,11 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
delay: 1000,
};
- await expect(evaluate({ event: payload })).rejects.toThrowError(
- new LLMCompletionError({
- message:
- "401 status code (no body)\n" +
- "\n" +
- "Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/MODEL_AUTHENTICATION/\n",
- responseStatusCode: 401,
- }),
- );
+ await expect(evaluate({ event: payload })).rejects.toMatchObject({
+ name: "LLMCompletionError",
+ responseStatusCode: 401,
+ isRetryable: false,
+ });
const jobs = await prisma.jobExecution.findMany({
where: { projectId },
@@ -2139,8 +2133,8 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
test("handles LLM timeout gracefully", async () => {
const { projectId } = await createOrgProjectAndApiKey();
// Set up the mock to simulate timeout for this test only
- const mockFetchLLMCompletion = vi.mocked(fetchLLMCompletion);
- mockFetchLLMCompletion.mockRejectedValueOnce(
+ const mockGenerateLLMText = vi.mocked(generateLLMText);
+ mockGenerateLLMText.mockRejectedValueOnce(
new ApiError("Request timeout after 120000ms", 500),
);
@@ -2244,7 +2238,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
expect(jobs[0].status.toString()).toBe("PENDING");
// Clean up the mock after this test
- mockFetchLLMCompletion.mockReset();
+ mockGenerateLLMText.mockReset();
}, 15_000);
});
@@ -3043,15 +3037,15 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
},
});
- // Mock fetchLLMCompletion to capture the traceSinkParams
+ // Mock the LLM runtime to capture the trace parameters.
let capturedTraceSinkParams: any = null;
- vi.mocked(fetchLLMCompletion).mockImplementationOnce(
- async (params: any) => {
- capturedTraceSinkParams = params.traceSinkParams;
- return { score: 0.8, reasoning: "Good response" };
- },
- );
+ vi.mocked(generateLLMText).mockImplementationOnce((async (
+ params: any,
+ ) => {
+ capturedTraceSinkParams = params.trace;
+ return { output: { score: 0.8, reasoning: "Good response" } };
+ }) as any);
await evaluate({
event: {
@@ -3060,7 +3054,7 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
},
});
- // Verify traceSinkParams were passed to fetchLLMCompletion
+ // Verify trace parameters were passed to the shared LLM runtime.
expect(capturedTraceSinkParams).toBeDefined();
expect(capturedTraceSinkParams.targetProjectId).toBe(projectId);
expect(capturedTraceSinkParams.traceId).toMatch(/^[a-f0-9]{32}$/);
@@ -3085,10 +3079,12 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;
const jobExecutionId = randomUUID();
const templateId = randomUUID();
- vi.mocked(fetchLLMCompletion).mockResolvedValueOnce({
- score: 0,
- reasoning: "The response is safe and not toxic.",
- });
+ vi.mocked(generateLLMText).mockResolvedValueOnce({
+ output: {
+ score: 0,
+ reasoning: "The response is safe and not toxic.",
+ },
+ } as any);
await upsertTrace({
id: traceId,
diff --git a/worker/src/__tests__/experimentsService.test.ts b/worker/src/__tests__/experimentsService.test.ts
index b3a7ef64a5..24f48d432f 100644
--- a/worker/src/__tests__/experimentsService.test.ts
+++ b/worker/src/__tests__/experimentsService.test.ts
@@ -15,7 +15,7 @@ vi.mock("@langfuse/shared/src/server", async () => {
const actual = await vi.importActual("@langfuse/shared/src/server");
return {
...actual,
- fetchLLMCompletion: vi.fn().mockResolvedValue({ id: "test-id" }),
+ generateLLMText: vi.fn().mockResolvedValue({ text: "test output" }),
logger: {
info: vi.fn(),
error: vi.fn(),
diff --git a/worker/src/__tests__/fetchLLMCompletion-bedrock-auth.test.ts b/worker/src/__tests__/fetchLLMCompletion-bedrock-auth.test.ts
deleted file mode 100644
index 893732e376..0000000000
--- a/worker/src/__tests__/fetchLLMCompletion-bedrock-auth.test.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { BEDROCK_USE_DEFAULT_CREDENTIALS } from "@langfuse/shared";
-import { resolveBedrockAuth } from "@langfuse/shared/src/server";
-
-describe("resolveBedrockAuth", () => {
- it("uses bearer token auth when Bedrock secret contains a Bedrock API key", () => {
- expect(
- resolveBedrockAuth({
- secretKey: JSON.stringify({
- apiKey: "bedrock-api-key-1234",
- }),
- allowDefaultCredentials: true,
- }),
- ).toEqual({
- clientOptions: {
- token: { token: "bedrock-api-key-1234" },
- authSchemePreference: ["httpBearerAuth"],
- },
- });
- });
-
- it("keeps SigV4 auth when Bedrock secret contains AWS access keys", () => {
- expect(
- resolveBedrockAuth({
- secretKey: JSON.stringify({
- accessKeyId: "AKIAIOSFODNN7EXAMPLE",
- secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
- }),
- allowDefaultCredentials: true,
- }),
- ).toEqual({
- credentials: {
- accessKeyId: "AKIAIOSFODNN7EXAMPLE",
- secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
- },
- });
- });
-
- it("preserves the default credential provider chain sentinel behavior", () => {
- expect(
- resolveBedrockAuth({
- secretKey: BEDROCK_USE_DEFAULT_CREDENTIALS,
- allowDefaultCredentials: true,
- }),
- ).toEqual({});
- });
-
- it("throws when sentinel is used but default credentials are not allowed", () => {
- expect(() =>
- resolveBedrockAuth({
- secretKey: BEDROCK_USE_DEFAULT_CREDENTIALS,
- allowDefaultCredentials: false,
- }),
- ).toThrow("Invalid Bedrock credentials");
- });
-
- it("throws on invalid JSON secret key", () => {
- expect(() =>
- resolveBedrockAuth({
- secretKey: "not-valid-json",
- allowDefaultCredentials: false,
- }),
- ).toThrow("Invalid Bedrock credentials");
- });
-
- it("throws on JSON that does not match any credential schema", () => {
- expect(() =>
- resolveBedrockAuth({
- secretKey: JSON.stringify({ unknownField: "value" }),
- allowDefaultCredentials: false,
- }),
- ).toThrow("Invalid Bedrock credentials");
- });
-});
diff --git a/worker/src/__tests__/fetchLLMCompletionErrors.test.ts b/worker/src/__tests__/fetchLLMCompletionErrors.test.ts
deleted file mode 100644
index a253b31979..0000000000
--- a/worker/src/__tests__/fetchLLMCompletionErrors.test.ts
+++ /dev/null
@@ -1,508 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const anthropicInvokeMock = vi.fn();
-const chatAnthropicConstructorMock = vi.fn().mockImplementation(function () {
- return {
- invoke: anthropicInvokeMock,
- pipe: vi.fn().mockReturnValue({
- invoke: anthropicInvokeMock,
- }),
- withStructuredOutput: vi.fn().mockReturnValue({
- invoke: anthropicInvokeMock,
- }),
- };
-});
-
-const mockGcpServiceAccountKey = {
- type: "service_account",
- project_id: "test-project",
- private_key_id: "test-key-id",
- private_key: "-----BEGIN PRIVATE KEY-----\ntest\n-----END PRIVATE KEY-----\n",
- client_email: "[email protected]",
- client_id: "1234567890",
- auth_uri: "https://accounts.google.com/o/oauth2/auth",
- token_uri: "https://oauth2.googleapis.com/token",
- auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs",
- client_x509_cert_url:
- "https://www.googleapis.com/robot/v1/metadata/x509/test%40test-project.iam.gserviceaccount.com",
-} as const;
-
-process.env.CLICKHOUSE_URL ??= "http://localhost:8123";
-process.env.CLICKHOUSE_USER ??= "default";
-process.env.CLICKHOUSE_PASSWORD ??= "password";
-process.env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET ??= "test-bucket";
-process.env.ENCRYPTION_KEY ??=
- "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
-
-class MockLLMCompletionError extends Error {
- responseStatusCode: number;
- isRetryable: boolean;
- blockReason: null;
-
- constructor(params: {
- message: string;
- responseStatusCode?: number;
- isRetryable?: boolean;
- cause?: unknown;
- }) {
- super(params.message, { cause: params.cause });
- this.name = "LLMCompletionError";
- this.responseStatusCode = params.responseStatusCode ?? 500;
- this.isRetryable = params.isRetryable ?? false;
- this.blockReason = null;
- }
-
- shouldBlockConfig() {
- return false;
- }
-
- getEvaluatorBlockReason() {
- return null;
- }
-}
-
-describe("fetchLLMCompletion provider error classification", () => {
- let encrypt: typeof import("../../../packages/shared/src/encryption").encrypt;
- let fetchLLMCompletion: typeof import("../../../packages/shared/src/server/llm/fetchLLMCompletion").fetchLLMCompletion;
-
- beforeEach(async () => {
- anthropicInvokeMock.mockReset();
- chatAnthropicConstructorMock.mockClear();
- vi.resetModules();
-
- vi.doMock(
- "../../../packages/shared/node_modules/@langchain/anthropic",
- () => ({
- ChatAnthropic: chatAnthropicConstructorMock,
- }),
- );
- vi.doMock("../../../packages/shared/src/server/llm/errors", () => ({
- LLMCompletionError: MockLLMCompletionError,
- }));
-
- ({ encrypt } = await import("../../../packages/shared/src/encryption"));
- ({ fetchLLMCompletion } =
- await import("../../../packages/shared/src/server/llm/fetchLLMCompletion"));
- });
-
- it("treats wrapped Anthropic context overflow errors as non-retryable", async () => {
- const { ContextOverflowError } =
- await import("../../../packages/shared/node_modules/@langchain/core/errors");
- const cause = new Error(
- '400 {"type":"error","error":{"type":"invalid_request_error","message":"prompt is too long: 202089 tokens > 200000 maximum"},"request_id":"req_123"}',
- );
- (cause as Error & { status: number }).status = 400;
-
- const contextOverflowError = ContextOverflowError.fromError(cause);
-
- anthropicInvokeMock.mockRejectedValue(contextOverflowError);
-
- await expect(
- fetchLLMCompletion({
- streaming: false,
- messages: [
- {
- role: "user",
- content: "Score this observation.",
- type: "public-api-created",
- },
- ],
- modelParams: {
- provider: "anthropic",
- adapter: "anthropic",
- model: "claude-haiku-4-5-20251001",
- temperature: 0,
- max_tokens: 10,
- },
- llmConnection: {
- secretKey: encrypt("anthropic-api-key"),
- },
- }),
- ).rejects.toMatchObject({
- name: "LLMCompletionError",
- responseStatusCode: 400,
- isRetryable: false,
- });
- });
-
- it("preserves provider status codes from wrapped error causes", async () => {
- const cause = new Error("Provider authentication failed");
- (cause as Error & { status: number }).status = 401;
- const wrappedError = new Error("Connection error.", { cause });
-
- anthropicInvokeMock.mockRejectedValue(wrappedError);
-
- try {
- await fetchLLMCompletion({
- streaming: false,
- messages: [
- {
- role: "user",
- content: "Score this observation.",
- type: "public-api-created",
- },
- ],
- modelParams: {
- provider: "anthropic",
- adapter: "anthropic",
- model: "claude-haiku-4-5-20251001",
- temperature: 0,
- max_tokens: 10,
- },
- llmConnection: {
- secretKey: encrypt("anthropic-api-key"),
- },
- });
- expect.fail("Expected fetchLLMCompletion to throw");
- } catch (e) {
- expect(e).toMatchObject({
- name: "LLMCompletionError",
- responseStatusCode: 401,
- isRetryable: false,
- });
- expect((e as Error).cause).toBe(wrappedError);
- }
- });
-
- it("forwards Anthropic options and normalizes sampling params for Claude on Vertex", async () => {
- const modelInstance = {
- topP: -1,
- temperature: 0,
- invoke: anthropicInvokeMock,
- pipe: vi.fn().mockReturnValue({
- invoke: anthropicInvokeMock,
- }),
- withStructuredOutput: vi.fn().mockReturnValue({
- invoke: anthropicInvokeMock,
- }),
- };
-
- chatAnthropicConstructorMock.mockImplementationOnce(function () {
- return modelInstance;
- });
- anthropicInvokeMock.mockResolvedValue({ content: "ok" });
-
- await expect(
- fetchLLMCompletion({
- streaming: false,
- messages: [
- {
- role: "user",
- content: "Score this observation.",
- type: "public-api-created",
- },
- ],
- modelParams: {
- provider: "vertexai",
- adapter: "google-vertex-ai",
- model: "claude-sonnet-4-6",
- temperature: 0,
- max_tokens: 10,
- providerOptions: {
- thinking: {
- type: "enabled",
- budget_tokens: 16000,
- },
- },
- },
- llmConnection: {
- secretKey: encrypt(JSON.stringify(mockGcpServiceAccountKey)),
- config: {
- location: "us-east5",
- },
- },
- }),
- ).resolves.toEqual({ text: "ok" });
-
- expect(chatAnthropicConstructorMock).toHaveBeenCalledWith(
- expect.objectContaining({
- model: "claude-sonnet-4-6",
- temperature: 0,
- topP: undefined,
- invocationKwargs: {
- thinking: {
- type: "enabled",
- budget_tokens: 16000,
- },
- },
- }),
- );
- expect(modelInstance.topP).toBeUndefined();
- expect(modelInstance.temperature).toBe(0);
- });
-
- it("applies the adaptive thinking structured output workaround for Claude on Vertex", async () => {
- const thinkingDuringStructuredOutput: unknown[] = [];
- const modelInstance = {
- thinking: { type: "disabled" },
- invoke: anthropicInvokeMock,
- pipe: vi.fn().mockReturnValue({
- invoke: anthropicInvokeMock,
- }),
- withStructuredOutput: vi.fn().mockImplementation(function () {
- thinkingDuringStructuredOutput.push(modelInstance.thinking);
- return {
- invoke: anthropicInvokeMock,
- };
- }),
- };
-
- chatAnthropicConstructorMock.mockImplementationOnce(function () {
- return modelInstance;
- });
- anthropicInvokeMock.mockResolvedValue({ result: "ok" });
-
- await expect(
- fetchLLMCompletion({
- streaming: false,
- messages: [
- {
- role: "user",
- content: "Return structured output.",
- type: "public-api-created",
- },
- ],
- modelParams: {
- provider: "vertexai",
- adapter: "google-vertex-ai",
- model: "claude-fable-5",
- temperature: 0,
- max_tokens: 10,
- },
- llmConnection: {
- secretKey: encrypt(JSON.stringify(mockGcpServiceAccountKey)),
- config: {
- location: "us-east5",
- },
- },
- structuredOutputSchema: {
- type: "object",
- properties: {
- result: { type: "string" },
- },
- required: ["result"],
- additionalProperties: false,
- },
- }),
- ).resolves.toEqual({ result: "ok" });
-
- expect(thinkingDuringStructuredOutput).toEqual([{ type: "adaptive" }]);
- expect(modelInstance.thinking).toEqual({ type: "disabled" });
- });
-
- it("rejects Claude on Vertex model names that are not single path segments", async () => {
- await expect(
- fetchLLMCompletion({
- streaming: false,
- messages: [
- {
- role: "user",
- content: "Score this observation.",
- type: "public-api-created",
- },
- ],
- modelParams: {
- provider: "vertexai",
- adapter: "google-vertex-ai",
- model:
- "../../../../../../../projects/victim/locations/us-east5/publishers/anthropic/models/claude-3-5-sonnet",
- temperature: 0,
- max_tokens: 10,
- },
- llmConnection: {
- secretKey: encrypt(JSON.stringify(mockGcpServiceAccountKey)),
- config: {
- location: "us-east5",
- },
- },
- }),
- ).rejects.toThrow(
- "Invalid Anthropic Vertex AI model name. Model names must be a single Vertex model ID segment.",
- );
-
- expect(chatAnthropicConstructorMock).not.toHaveBeenCalled();
- });
-
- it("rejects Claude on Vertex locations that could reshape the Vertex host", async () => {
- await expect(
- fetchLLMCompletion({
- streaming: false,
- messages: [
- {
- role: "user",
- content: "Score this observation.",
- type: "public-api-created",
- },
- ],
- modelParams: {
- provider: "vertexai",
- adapter: "google-vertex-ai",
- model: "claude-sonnet-4-6",
- temperature: 0,
- max_tokens: 10,
- },
- llmConnection: {
- secretKey: encrypt(JSON.stringify(mockGcpServiceAccountKey)),
- config: {
- location: "attacker.example/",
- },
- },
- }),
- ).rejects.toThrow(
- "Invalid Vertex AI location. Locations must be a single Vertex region identifier.",
- );
-
- expect(chatAnthropicConstructorMock).not.toHaveBeenCalled();
- });
-
- it("rejects an empty Claude on Vertex location with the clean error", async () => {
- await expect(
- fetchLLMCompletion({
- streaming: false,
- messages: [
- {
- role: "user",
- content: "Score this observation.",
- type: "public-api-created",
- },
- ],
- modelParams: {
- provider: "vertexai",
- adapter: "google-vertex-ai",
- model: "claude-sonnet-4-6",
- temperature: 0,
- max_tokens: 10,
- },
- llmConnection: {
- secretKey: encrypt(JSON.stringify(mockGcpServiceAccountKey)),
- config: {
- location: "",
- },
- },
- }),
- ).rejects.toThrow(
- "Invalid Vertex AI location. Locations must be a single Vertex region identifier.",
- );
-
- expect(chatAnthropicConstructorMock).not.toHaveBeenCalled();
- });
-
- it("does not forward Anthropic env credentials to the Vertex client", async () => {
- let capturedCreateClient:
- | ((options: { apiKey?: string | null }) => {
- apiKey: string | null;
- authToken: string | null;
- })
- | undefined;
-
- chatAnthropicConstructorMock.mockImplementationOnce(function (args: {
- createClient: (options: { apiKey?: string | null }) => {
- apiKey: string | null;
- authToken: string | null;
- };
- }) {
- capturedCreateClient = args.createClient;
- return {
- invoke: anthropicInvokeMock,
- pipe: vi.fn().mockReturnValue({
- invoke: anthropicInvokeMock,
- }),
- withStructuredOutput: vi.fn().mockReturnValue({
- invoke: anthropicInvokeMock,
- }),
- };
- });
- anthropicInvokeMock.mockResolvedValue({ content: "ok" });
-
- await expect(
- fetchLLMCompletion({
- streaming: false,
- messages: [
- {
- role: "user",
- content: "Score this observation.",
- type: "public-api-created",
- },
- ],
- modelParams: {
- provider: "vertexai",
- adapter: "google-vertex-ai",
- model: "claude-sonnet-4-6",
- temperature: 0,
- max_tokens: 10,
- },
- llmConnection: {
- secretKey: encrypt(JSON.stringify(mockGcpServiceAccountKey)),
- config: {
- location: "us-east5",
- },
- },
- }),
- ).resolves.toEqual({ text: "ok" });
-
- expect(capturedCreateClient).toBeDefined();
- // ChatAnthropic forwards process.env.ANTHROPIC_API_KEY here, and the base
- // SDK also defaults apiKey/authToken from env. The Vertex client must force
- // both null so neither ships as a header to Google.
- const client = capturedCreateClient!({
- apiKey: "sk-should-not-leak",
- });
- expect(client.apiKey).toBeNull();
- expect(client.authToken).toBeNull();
- });
-
- it("drops a providerOptions.model override for Claude on Vertex", async () => {
- chatAnthropicConstructorMock.mockImplementationOnce(function () {
- return {
- invoke: anthropicInvokeMock,
- pipe: vi.fn().mockReturnValue({
- invoke: anthropicInvokeMock,
- }),
- withStructuredOutput: vi.fn().mockReturnValue({
- invoke: anthropicInvokeMock,
- }),
- };
- });
- anthropicInvokeMock.mockResolvedValue({ content: "ok" });
-
- await expect(
- fetchLLMCompletion({
- streaming: false,
- messages: [
- {
- role: "user",
- content: "Score this observation.",
- type: "public-api-created",
- },
- ],
- modelParams: {
- provider: "vertexai",
- adapter: "google-vertex-ai",
- model: "claude-sonnet-4-6",
- temperature: 0,
- max_tokens: 10,
- providerOptions: {
- model:
- "../../../../../../../projects/victim/locations/us-east5/publishers/anthropic/models/claude-3-5-sonnet",
- },
- },
- llmConnection: {
- secretKey: encrypt(JSON.stringify(mockGcpServiceAccountKey)),
- config: {
- location: "us-east5",
- },
- },
- }),
- ).resolves.toEqual({ text: "ok" });
-
- expect(chatAnthropicConstructorMock).toHaveBeenCalledWith(
- expect.objectContaining({
- model: "claude-sonnet-4-6",
- invocationKwargs: {},
- }),
- );
- // The validated `model` field must win; the injected override is stripped.
- const { invocationKwargs } = chatAnthropicConstructorMock.mock.calls[0][0];
- expect(invocationKwargs).not.toHaveProperty("model");
- });
-});
diff --git a/worker/src/__tests__/fetchLLMCompletionReasoning.test.ts b/worker/src/__tests__/fetchLLMCompletionReasoning.test.ts
deleted file mode 100644
index fc1406d594..0000000000
--- a/worker/src/__tests__/fetchLLMCompletionReasoning.test.ts
+++ /dev/null
@@ -1,310 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import {
- AIMessage,
- AIMessageChunk,
-} from "../../../packages/shared/node_modules/@langchain/core/messages";
-
-// Real AIMessage(Chunk) instances are required because the production code
-// reads `message.contentBlocks`, which is a class getter that dispatches to
-// `@langchain/core`'s registered translator based on `response_metadata.model_provider`.
-// Plain object mocks bypass the translator and would leave raw
-// `reasoning_content` blocks unstripped.
-function bedrockAIMessage(params: {
- content: AIMessage["content"];
- tool_calls?: AIMessage["tool_calls"];
-}): AIMessage {
- return new AIMessage({
- content: params.content,
- tool_calls: params.tool_calls,
- response_metadata: { model_provider: "bedrock-converse" },
- });
-}
-
-function bedrockAIMessageChunk(params: {
- content: AIMessage["content"];
-}): AIMessageChunk {
- return new AIMessageChunk({
- content: params.content,
- response_metadata: { model_provider: "bedrock-converse" },
- });
-}
-
-const invokeMock = vi.fn();
-const streamMock = vi.fn();
-const pipeMock = vi.fn().mockImplementation((parser) => ({
- invoke: invokeMock,
- stream: (...args: any[]) => parser.transform(streamMock(...args), {}),
-}));
-const bindToolsInvokeMock = vi.fn();
-const bindToolsMock = vi.fn().mockReturnValue({
- invoke: bindToolsInvokeMock,
-});
-const chatBedrockConverseConstructorMock = vi
- .fn()
- .mockImplementation(function () {
- return {
- invoke: invokeMock,
- bindTools: bindToolsMock,
- pipe: pipeMock,
- };
- });
-
-class MockLLMCompletionError extends Error {
- responseStatusCode: number;
- isRetryable: boolean;
- blockReason: null;
-
- constructor(params: {
- message: string;
- responseStatusCode?: number;
- isRetryable?: boolean;
- }) {
- super(params.message);
- this.name = "LLMCompletionError";
- this.responseStatusCode = params.responseStatusCode ?? 500;
- this.isRetryable = params.isRetryable ?? false;
- this.blockReason = null;
- }
-
- shouldBlockConfig() {
- return false;
- }
-
- getEvaluatorBlockReason() {
- return null;
- }
-}
-
-process.env.CLICKHOUSE_URL ??= "http://localhost:8123";
-process.env.CLICKHOUSE_USER ??= "default";
-process.env.CLICKHOUSE_PASSWORD ??= "password";
-process.env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET ??= "test-bucket";
-process.env.ENCRYPTION_KEY ??=
- "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
-
-describe("fetchLLMCompletion Bedrock reasoning blocks", () => {
- let originalCloudRegion: string | undefined;
- let encrypt: typeof import("../../../packages/shared/src/encryption").encrypt;
- let fetchLLMCompletion: typeof import("../../../packages/shared/src/server/llm/fetchLLMCompletion").fetchLLMCompletion;
-
- beforeEach(async () => {
- invokeMock.mockReset();
- streamMock.mockReset();
- pipeMock.mockClear();
- bindToolsInvokeMock.mockReset();
- bindToolsMock.mockClear();
- chatBedrockConverseConstructorMock.mockClear();
- vi.resetModules();
- originalCloudRegion = process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
- delete process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
- vi.doMock("../../../packages/shared/node_modules/@langchain/aws", () => ({
- ChatBedrockConverse: chatBedrockConverseConstructorMock,
- }));
- vi.doMock("../../../packages/shared/src/server/llm/errors", () => ({
- LLMCompletionError: MockLLMCompletionError,
- }));
-
- ({ encrypt } = await import("../../../packages/shared/src/encryption"));
- ({ fetchLLMCompletion } =
- await import("../../../packages/shared/src/server/llm/fetchLLMCompletion"));
- });
-
- afterEach(() => {
- if (originalCloudRegion === undefined) {
- delete process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
- } else {
- process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;
- }
- });
-
- it("preserves plain string completions when Bedrock returns no reasoning", async () => {
- invokeMock.mockResolvedValue(bedrockAIMessage({ content: "4" }));
-
- const completion = await fetchLLMCompletion({
- streaming: false,
- messages: [
- {
- role: "user",
- content: "What is 2+2? Answer only with the number.",
- type: "public-api-created",
- },
- ],
- modelParams: {
- provider: "bedrock",
- adapter: "bedrock",
- model: "openai.gpt-oss-120b-1:0",
- temperature: 0,
- max_tokens: 10,
- },
- llmConnection: {
- secretKey: encrypt(JSON.stringify({ apiKey: "test-api-key" })),
- config: {
- region: "us-east-1",
- },
- },
- });
-
- expect(completion).toBe("4");
- });
-
- it("returns Bedrock GPT OSS reasoning separately from text", async () => {
- invokeMock.mockResolvedValue(
- bedrockAIMessage({
- content: [
- {
- type: "reasoning_content",
- reasoningText: "Compute the arithmetic.",
- },
- { type: "text", text: "4" },
- ],
- }),
- );
-
- const completion = await fetchLLMCompletion({
- streaming: false,
- messages: [
- {
- role: "user",
- content: "What is 2+2? Answer only with the number.",
- type: "public-api-created",
- },
- ],
- modelParams: {
- provider: "bedrock",
- adapter: "bedrock",
- model: "openai.gpt-oss-120b-1:0",
- temperature: 0,
- max_tokens: 10,
- },
- llmConnection: {
- secretKey: encrypt(JSON.stringify({ apiKey: "test-api-key" })),
- config: {
- region: "us-east-1",
- },
- },
- });
-
- expect(completion).toEqual({
- text: "4",
- reasoning: "Compute the arithmetic.",
- });
- });
-
- it("strips Bedrock reasoning blocks before parsing tool calls", async () => {
- bindToolsInvokeMock.mockResolvedValue(
- bedrockAIMessage({
- content: [
- {
- type: "reasoning_content",
- reasoningText: "Need the weather tool.",
- },
- { type: "text", text: "" },
- ],
- tool_calls: [
- {
- id: "tool-use-1",
- name: "get_weather",
- args: { location: "Paris" },
- },
- ],
- }),
- );
-
- const completion = await fetchLLMCompletion({
- streaming: false,
- messages: [
- {
- role: "user",
- content: "What's the weather like in Paris?",
- type: "public-api-created",
- },
- ],
- modelParams: {
- provider: "bedrock",
- adapter: "bedrock",
- model: "openai.gpt-oss-120b-1:0",
- temperature: 0,
- max_tokens: 100,
- },
- tools: [
- {
- name: "get_weather",
- description: "Get the current weather for a location",
- parameters: {
- type: "object",
- properties: {
- location: { type: "string" },
- },
- required: ["location"],
- },
- },
- ],
- llmConnection: {
- secretKey: encrypt(JSON.stringify({ apiKey: "test-api-key" })),
- config: {
- region: "us-east-1",
- },
- },
- });
-
- expect(completion).toEqual({
- content: [{ type: "text", text: "" }],
- tool_calls: [
- {
- id: "tool-use-1",
- name: "get_weather",
- args: { location: "Paris" },
- },
- ],
- reasoning: "Need the weather tool.",
- });
- });
-
- it("filters Bedrock reasoning blocks out of streaming output", async () => {
- streamMock.mockImplementation(async function* () {
- yield bedrockAIMessageChunk({
- content: [
- {
- type: "reasoning_content",
- reasoningText: "Do not show this in the playground.",
- },
- ],
- });
- yield bedrockAIMessageChunk({
- content: [{ type: "text", text: "Hello!" }],
- });
- } as any);
-
- const stream = await fetchLLMCompletion({
- streaming: true,
- messages: [
- {
- role: "user",
- content: "hi",
- type: "public-api-created",
- },
- ],
- modelParams: {
- provider: "bedrock",
- adapter: "bedrock",
- model: "openai.gpt-oss-120b-1:0",
- temperature: 0,
- max_tokens: 100,
- },
- llmConnection: {
- secretKey: encrypt(JSON.stringify({ apiKey: "test-api-key" })),
- config: {
- region: "us-east-1",
- },
- },
- });
-
- const decoder = new TextDecoder();
- let text = "";
- for await (const chunk of stream) {
- text += decoder.decode(chunk);
- }
-
- expect(text).toBe("Hello!");
- });
-});
diff --git a/worker/src/__tests__/fetchLLMCompletionTimeout.test.ts b/worker/src/__tests__/fetchLLMCompletionTimeout.test.ts
deleted file mode 100644
index af2fd145ce..0000000000
--- a/worker/src/__tests__/fetchLLMCompletionTimeout.test.ts
+++ /dev/null
@@ -1,312 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { AIMessage } from "../../../packages/shared/node_modules/@langchain/core/messages";
-
-const invokeMock = vi.fn();
-const streamMock = vi.fn();
-const bedrockInvokeMock = vi.fn();
-const chatGoogleConstructorMock = vi.fn().mockImplementation(function () {
- return {
- invoke: invokeMock,
- pipe: vi.fn().mockReturnValue({
- stream: streamMock,
- }),
- };
-});
-const chatBedrockConverseConstructorMock = vi
- .fn()
- .mockImplementation(function () {
- return {
- invoke: bedrockInvokeMock,
- pipe: vi.fn().mockReturnValue({
- invoke: bedrockInvokeMock,
- stream: streamMock,
- }),
- };
- });
-const VERTEXAI_USE_DEFAULT_CREDENTIALS = "__VERTEXAI_DEFAULT_CREDENTIALS__";
-
-process.env.CLICKHOUSE_URL ??= "http://localhost:8123";
-process.env.CLICKHOUSE_USER ??= "default";
-process.env.CLICKHOUSE_PASSWORD ??= "password";
-process.env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET ??= "test-bucket";
-process.env.ENCRYPTION_KEY ??=
- "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
-
-class MockLLMCompletionError extends Error {
- responseStatusCode: number;
- isRetryable: boolean;
- blockReason: null;
-
- constructor(params: {
- message: string;
- responseStatusCode?: number;
- isRetryable?: boolean;
- }) {
- super(params.message);
- this.name = "LLMCompletionError";
- this.responseStatusCode = params.responseStatusCode ?? 500;
- this.isRetryable = params.isRetryable ?? false;
- this.blockReason = null;
- }
-
- shouldBlockConfig() {
- return false;
- }
-
- getEvaluatorBlockReason() {
- return null;
- }
-}
-
-describe("fetchLLMCompletion runtime timeouts", () => {
- let originalTimeout: number;
- let originalCloudRegion: string | undefined;
- let env: typeof import("../../../packages/shared/src/env").env;
- let encrypt: typeof import("../../../packages/shared/src/encryption").encrypt;
- let fetchLLMCompletion: typeof import("../../../packages/shared/src/server/llm/fetchLLMCompletion").fetchLLMCompletion;
-
- beforeEach(async () => {
- vi.useFakeTimers();
- invokeMock.mockReset();
- streamMock.mockReset();
- chatGoogleConstructorMock.mockClear();
- vi.resetModules();
- originalCloudRegion = process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
- delete process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
- vi.doMock(
- "../../../packages/shared/node_modules/@langchain/google",
- () => ({
- ChatGoogle: chatGoogleConstructorMock,
- }),
- );
- vi.doMock("../../../packages/shared/src/server/llm/errors", () => ({
- LLMCompletionError: MockLLMCompletionError,
- }));
-
- ({ env } = await import("../../../packages/shared/src/env"));
- ({ encrypt } = await import("../../../packages/shared/src/encryption"));
- ({ fetchLLMCompletion } =
- await import("../../../packages/shared/src/server/llm/fetchLLMCompletion"));
-
- originalTimeout = env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS;
- });
-
- afterEach(() => {
- env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS = originalTimeout;
- if (originalCloudRegion === undefined) {
- delete process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
- } else {
- process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;
- }
- vi.useRealTimers();
- });
-
- it("wraps non-streaming VertexAI timeouts as non-retryable LLMCompletionError", async () => {
- env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS = 25;
-
- invokeMock.mockImplementation(() => new Promise(() => {}));
-
- const completionPromise = fetchLLMCompletion({
- streaming: false,
- messages: [
- {
- role: "user",
- content: "What is 2+2? Answer only with the number.",
- type: "public-api-created",
- },
- ],
- modelParams: {
- provider: "google-vertex-ai",
- adapter: "google-vertex-ai",
- model: "gemini-2.0-flash",
- temperature: 0,
- max_tokens: 10,
- },
- llmConnection: {
- secretKey: encrypt(VERTEXAI_USE_DEFAULT_CREDENTIALS),
- config: null,
- },
- });
-
- const completionRejection = expect(completionPromise).rejects.toMatchObject(
- {
- name: "LLMCompletionError",
- message: "Request timed out after 25ms",
- isRetryable: false,
- },
- );
-
- await vi.runOnlyPendingTimersAsync();
- await completionRejection;
- });
-
- it("wraps streaming VertexAI timeouts as non-retryable LLMCompletionError", async () => {
- env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS = 25;
-
- streamMock.mockImplementation(() => new Promise(() => {}));
-
- const completionPromise = fetchLLMCompletion({
- streaming: true,
- messages: [
- {
- role: "user",
- content: "Stream the answer.",
- type: "public-api-created",
- },
- ],
- modelParams: {
- provider: "google-vertex-ai",
- adapter: "google-vertex-ai",
- model: "gemini-2.0-flash",
- temperature: 0,
- max_tokens: 10,
- },
- llmConnection: {
- secretKey: encrypt(VERTEXAI_USE_DEFAULT_CREDENTIALS),
- config: null,
- },
- });
-
- const completionRejection = expect(completionPromise).rejects.toMatchObject(
- {
- name: "LLMCompletionError",
- message: "Request timed out after 25ms",
- isRetryable: false,
- },
- );
-
- await vi.runOnlyPendingTimersAsync();
- await completionRejection;
- });
-
- it("passes Google AI Studio thinking provider options as ChatGoogle top-level fields", async () => {
- invokeMock.mockResolvedValue(new AIMessage("4"));
-
- await fetchLLMCompletion({
- streaming: false,
- messages: [
- {
- role: "user",
- content: "What is 2+2? Answer only with the number.",
- type: "public-api-created",
- },
- ],
- modelParams: {
- provider: "google-ai-studio",
- adapter: "google-ai-studio",
- model: "gemini-2.5-flash",
- temperature: 0,
- max_tokens: 10,
- providerOptions: {
- thinkingBudget: 1024,
- thinkingLevel: "high",
- },
- },
- llmConnection: {
- secretKey: encrypt("google-api-key"),
- },
- });
-
- expect(chatGoogleConstructorMock).toHaveBeenCalledWith(
- expect.objectContaining({
- thinkingBudget: 1024,
- thinkingLevel: "high",
- }),
- );
- expect(chatGoogleConstructorMock).not.toHaveBeenCalledWith(
- expect.objectContaining({
- thinkingConfig: expect.anything(),
- }),
- );
- });
-});
-
-describe("fetchLLMCompletion end of model lifetime", () => {
- let originalCloudRegion: string | undefined;
- let encrypt: typeof import("../../../packages/shared/src/encryption").encrypt;
- let fetchLLMCompletion: typeof import("../../../packages/shared/src/server/llm/fetchLLMCompletion").fetchLLMCompletion;
- let ResourceNotFoundException: any;
-
- beforeEach(async () => {
- invokeMock.mockReset();
- streamMock.mockReset();
- bedrockInvokeMock.mockReset();
- chatBedrockConverseConstructorMock.mockClear();
- vi.resetModules();
- originalCloudRegion = process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
- delete process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
- // @langchain/aws is a dependency of @langfuse/shared, not worker — a bare
- // specifier can't resolve from this test file under pnpm strict isolation.
- vi.doMock("../../../packages/shared/node_modules/@langchain/aws", () => ({
- ChatBedrockConverse: chatBedrockConverseConstructorMock,
- }));
- vi.doMock("../../../packages/shared/src/server/llm/errors", () => ({
- LLMCompletionError: MockLLMCompletionError,
- }));
-
- ({ encrypt } = await import("../../../packages/shared/src/encryption"));
- ({ fetchLLMCompletion } =
- await import("../../../packages/shared/src/server/llm/fetchLLMCompletion"));
-
- // Resolve the real AWS SDK exception via @langchain/aws's dependency tree.
- const awsModulePath = require.resolve("@langchain/aws", {
- paths: [require("path").resolve(__dirname, "../../../packages/shared")],
- });
- ({ ResourceNotFoundException } = await import(
- require.resolve("@aws-sdk/client-bedrock-runtime", {
- paths: [require("path").dirname(awsModulePath)],
- })
- ));
- });
-
- afterEach(() => {
- if (originalCloudRegion === undefined) {
- delete process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
- } else {
- process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;
- }
- });
-
- it("treats end-of-life model errors as non-retryable", async () => {
- const endOfLifeError = new ResourceNotFoundException({
- message:
- "This model version has reached the end of its life. Please refer to the AWS documentation for more details.",
- $metadata: { httpStatusCode: 404 },
- });
- bedrockInvokeMock.mockRejectedValue(endOfLifeError);
-
- const completionPromise = fetchLLMCompletion({
- streaming: false,
- messages: [
- {
- role: "user",
- content: "What is 2+2? Answer only with the number.",
- type: "public-api-created",
- },
- ],
- modelParams: {
- provider: "bedrock",
- adapter: "bedrock",
- model: "anthropic.claude-3-5-sonnet-20240620-v1:0",
- temperature: 0,
- max_tokens: 10,
- },
- llmConnection: {
- secretKey: encrypt(JSON.stringify({ apiKey: "test-api-key" })),
- config: {
- region: "us-east-1",
- },
- },
- });
-
- expect(chatBedrockConverseConstructorMock).toHaveBeenCalled();
-
- await expect(completionPromise).rejects.toMatchObject({
- name: "LLMCompletionError",
- message:
- "This model version has reached the end of its life. Please refer to the AWS documentation for more details.",
- responseStatusCode: 404,
- isRetryable: false,
- });
- });
-});
diff --git a/worker/src/__tests__/googleSecureApiClient.test.ts b/worker/src/__tests__/googleSecureApiClient.test.ts
deleted file mode 100644
index cccfbfceec..0000000000
--- a/worker/src/__tests__/googleSecureApiClient.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { describe, expect, test } from "vitest";
-import { rewriteGoogleAIStudioUrl } from "../../../packages/shared/src/server/llm/googleSecureApiClient";
-
-// Real Google Vertex AI and AI Studio request paths are exercised end-to-end
-// in llmConnections.test.ts against live APIs. This file keeps the pure
-// URL-rewrite unit cases that the live tests can't easily express.
-
-describe("rewriteGoogleAIStudioUrl", () => {
- test.each([
- {
- name: "custom base URL",
- requestUrl:
- "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent",
- baseURL: "https://example.com/google",
- expectedUrl:
- "https://example.com/google/v1beta/models/gemini-2.5-flash:generateContent",
- },
- {
- name: "opaque custom base URL prefix",
- requestUrl:
- "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
- baseURL:
- "https://86c599932057.ngrok.app?url=https://generativelanguage.googleapis.com",
- expectedUrl:
- "https://86c599932057.ngrok.app?url=https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
- },
- {
- name: "non-Google URL",
- requestUrl: "https://other.example.com/v1beta/models/model:generate",
- baseURL: "https://example.com/google",
- expectedUrl: "https://other.example.com/v1beta/models/model:generate",
- },
- {
- name: "unset base URL",
- requestUrl:
- "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent",
- baseURL: undefined,
- expectedUrl:
- "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent",
- },
- ])("rewrites $name", ({ requestUrl, baseURL, expectedUrl }) => {
- expect(rewriteGoogleAIStudioUrl(requestUrl, baseURL)).toBe(expectedUrl);
- });
-});
diff --git a/worker/src/__tests__/llmConnections.test.ts b/worker/src/__tests__/llmConnections.test.ts
index 542435eedc..4eaa4c6a14 100644
--- a/worker/src/__tests__/llmConnections.test.ts
+++ b/worker/src/__tests__/llmConnections.test.ts
@@ -1,8 +1,11 @@
import { describe, test, expect } from "vitest";
import {
- fetchLLMCompletion,
+ createLLMOutput,
+ createLLMToolSet,
+ generateLLMText,
isLLMCompletionError,
- type CompletionWithReasoning,
+ mapLegacyLLMCompletionParams,
+ streamLLMText,
} from "@langfuse/shared/src/server";
import { encrypt } from "@langfuse/shared/encryption";
import {
@@ -41,13 +44,46 @@ import { z } from "zod";
* - LANGFUSE_LLM_CONNECTION_GOOGLEAISTUDIO_KEY
*/
-type TestLLMConnection = {
- secretKey: string;
- extraHeaders?: string | null;
- baseURL?: string | null;
- config?: Record<string, string> | null;
+type TestLLMConnection = Parameters<
+ typeof mapLegacyLLMCompletionParams
+>[0]["connection"];
+
+type TestCompletionParams = {
+ messages: Parameters<typeof mapLegacyLLMCompletionParams>[0]["messages"];
+ modelParams: ModelParams;
+ llmConnection: TestLLMConnection;
+ structuredOutputSchema?: z.ZodType;
+ tools?: Parameters<typeof createLLMToolSet>[0];
};
+function generateWithStoredConnection(params: TestCompletionParams) {
+ const { structuredOutputSchema, tools, ...legacyParams } = params;
+
+ return generateLLMText({
+ ...mapLegacyLLMCompletionParams({
+ messages: legacyParams.messages,
+ modelParams: legacyParams.modelParams,
+ connection: legacyParams.llmConnection,
+ }),
+ ...(structuredOutputSchema
+ ? { output: createLLMOutput(structuredOutputSchema) }
+ : {}),
+ ...(tools?.length ? { tools: createLLMToolSet(tools) } : {}),
+ });
+}
+
+function streamWithStoredConnection(
+ params: Omit<TestCompletionParams, "structuredOutputSchema" | "tools">,
+) {
+ return streamLLMText(
+ mapLegacyLLMCompletionParams({
+ messages: params.messages,
+ modelParams: params.modelParams,
+ connection: params.llmConnection,
+ }),
+ );
+}
+
const googleAIStudioFallbackModels = [
"gemini-3.1-flash-lite",
"gemini-2.5-flash",
@@ -116,7 +152,7 @@ type EvalStructuredOutputTestCase = {
name: string;
prompt: string;
outputDefinition: PersistedEvalOutputDefinition;
- responseSchema: z.ZodTypeAny;
+ responseSchema: z.ZodType;
assertParsed?: (data: {
score: number | boolean | string;
reasoning: string;
@@ -193,8 +229,7 @@ function registerEvalStructuredOutputTests(params: {
const completion = await (
params.runWithModel ?? ((operation) => operation())
)((model) =>
- fetchLLMCompletion({
- streaming: false,
+ generateWithStoredConnection({
messages: [
{
role: "user",
@@ -210,7 +245,7 @@ function registerEvalStructuredOutputTests(params: {
}),
);
- const parsed = testCase.responseSchema.safeParse(completion);
+ const parsed = testCase.responseSchema.safeParse(completion.output);
expect(parsed.success).toBe(true);
if (parsed.success) {
expect(parsed.data.reasoning.trim().length).toBeGreaterThan(0);
@@ -255,8 +290,7 @@ describe("LLM Connection Tests", () => {
test("simple completion", async () => {
checkEnvVar();
- const completion = await fetchLLMCompletion({
- streaming: false,
+ const completion = await generateWithStoredConnection({
messages: [
{
role: "user",
@@ -276,15 +310,13 @@ describe("LLM Connection Tests", () => {
},
});
- expect(typeof completion).toBe("string");
- expect(completion).toContain("4");
+ expect(completion.text).toContain("4");
}, 30_000);
test("streaming completion", async () => {
checkEnvVar();
- const stream = await fetchLLMCompletion({
- streaming: true,
+ const stream = await streamWithStoredConnection({
messages: [
{
role: "user",
@@ -304,12 +336,11 @@ describe("LLM Connection Tests", () => {
},
});
- const decoder = new TextDecoder();
let fullResponse = "";
let chunkCount = 0;
- for await (const chunk of stream) {
- fullResponse += decoder.decode(chunk);
+ for await (const chunk of stream.textStream) {
+ fullResponse += chunk;
chunkCount++;
}
@@ -335,8 +366,7 @@ describe("LLM Connection Tests", () => {
test("tool calling", async () => {
checkEnvVar();
- const completion = await fetchLLMCompletion({
- streaming: false,
+ const completion = await generateWithStoredConnection({
messages: [
{
role: "user",
@@ -357,11 +387,9 @@ describe("LLM Connection Tests", () => {
},
});
- expect(completion).toHaveProperty("tool_calls");
- expect(Array.isArray(completion.tool_calls)).toBe(true);
- expect(completion.tool_calls.length).toBeGreaterThan(0);
- expect(completion.tool_calls[0].name).toBe("get_weather");
- expect(completion.tool_calls[0].args).toHaveProperty("location");
+ expect(completion.toolCalls.length).toBeGreaterThan(0);
+ expect(completion.toolCalls[0].toolName).toBe("get_weather");
+ expect(completion.toolCalls[0].input).toHaveProperty("location");
}, 30_000);
});
@@ -381,8 +409,7 @@ describe("LLM Connection Tests", () => {
test("simple completion", async () => {
checkEnvVar();
- const completion = await fetchLLMCompletion({
- streaming: false,
+ const completion = await generateWithStoredConnection({
messages: [
{
role: "user",
@@ -404,15 +431,13 @@ describe("LLM Connection Tests", () => {
},
});
- expect(typeof completion).toBe("string");
- expect(completion).toContain("4");
+ expect(completion.text).toContain("4");
}, 30_000);
test("streaming completion", async () => {
checkEnvVar();
- const stream = await fetchLLMCompletion({
- streaming: true,
+ const stream = await streamWithStoredConnection({
messages: [
{
role: "user",
@@ -434,12 +459,11 @@ describe("LLM Connection Tests", () => {
},
});
- const decoder = new TextDecoder();
let fullResponse = "";
let chunkCount = 0;
- for await (const chunk of stream) {
- fullResponse += decoder.decode(chunk);
+ for await (const chunk of stream.textStream) {
+ fullResponse += chunk;
chunkCount++;
}
@@ -465,8 +489,7 @@ describe("LLM Connection Tests", () => {
test("tool calling", async () => {
checkEnvVar();
- const completion = await fetchLLMCompletion({
- streaming: false,
+ const completion = await generateWithStoredConnection({
messages: [
{
role: "user",
@@ -489,11 +512,9 @@ describe("LLM Connection Tests", () => {
},
});
- expect(completion).toHaveProperty("tool_calls");
- expect(Array.isArray(completion.tool_calls)).toBe(true);
- expect(completion.tool_calls.length).toBeGreaterThan(0);
- expect(completion.tool_calls[0].name).toBe("get_weather");
- expect(completion.tool_calls[0].args).toHaveProperty("location");
+ expect(completion.toolCalls.length).toBeGreaterThan(0);
+ expect(completion.toolCalls[0].toolName).toBe("get_weather");
+ expect(completion.toolCalls[0].input).toHaveProperty("location");
}, 30_000);
});
@@ -525,8 +546,7 @@ describe("LLM Connection Tests", () => {
test("simple completion", async () => {
checkEnvVars();
- const completion = await fetchLLMCompletion({
- streaming: false,
+ const completion = await generateWithStoredConnection({
messages: [
{
role: "user",
@@ -547,15 +567,13 @@ describe("LLM Connection Tests", () => {
},
});
- expect(typeof completion).toBe("string");
- expect(completion).toContain("4");
+ expect(completion.text).toContain("4");
}, 30_000);
test("streaming completion", async () => {
checkEnvVars();
- const stream = await fetchLLMCompletion({
- streaming: true,
+ const stream = await streamWithStoredConnection({
messages: [
{
role: "user",
@@ -576,12 +594,11 @@ describe("LLM Connection Tests", () => {
},
});
- const decoder = new TextDecoder();
let fullResponse = "";
let chunkCount = 0;
- for await (const chunk of stream) {
- fullResponse += decoder.decode(chunk);
+ for await (const chunk of stream.textStream) {
+ fullResponse += chunk;
chunkCount++;
}
@@ -608,8 +625,7 @@ describe("LLM Connection Tests", () => {
test("tool calling", async () => {
checkEnvVars();
- const completion = await fetchLLMCompletion({
- streaming: false,
+ const completion = await generateWithStoredConnection({
messages: [
{
role: "user",
@@ -631,11 +647,9 @@ describe("LLM Connection Tests", () => {
},
});
- expect(completion).toHaveProperty("tool_calls");
- expect(Array.isArray(completion.tool_calls)).toBe(true);
- expect(completion.tool_calls.length).toBeGreaterThan(0);
- expect(completion.tool_calls[0].name).toBe("get_weather");
- expect(completion.tool_calls[0].args).toHaveProperty("location");
+ expect(completion.toolCalls.length).toBeGreaterThan(0);
+ expect(completion.toolCalls[0].toolName).toBe("get_weather");
+ expect(completion.toolCalls[0].input).toHaveProperty("location");
}, 60_000);
});
@@ -684,8 +698,7 @@ describe("LLM Connection Tests", () => {
test("simple completion", async () => {
checkEnvVars();
- const completion = await fetchLLMCompletion({
- streaming: false,
+ const completion = await generateWithStoredConnection({
messages: [
{
role: "user",
@@ -706,15 +719,13 @@ describe("LLM Connection Tests", () => {
},
});
- expect(typeof completion).toBe("string");
- expect(completion).toContain("4");
+ expect(completion.text).toContain("4");
}, 30_000);
test("streaming completion", async () => {
checkEnvVars();
- const stream = await fetchLLMCompletion({
- streaming: true,
+ const stream = await streamWithStoredConnection({
messages: [
{
role: "user",
@@ -735,12 +746,11 @@ describe("LLM Connection Tests", () => {
},
});
- const decoder = new TextDecoder();
let fullResponse = "";
let chunkCount = 0;
- for await (const chunk of stream) {
- fullResponse += decoder.decode(chunk);
+ for await (const chunk of stream.textStream) {
+ fullResponse += chunk;
chunkCount++;
}
@@ -768,8 +778,7 @@ describe("LLM Connection Tests", () => {
test("tool calling", async () => {
checkEnvVars();
- const completion = await fetchLLMCompletion({
- streaming: false,
+ const completion = await generateWithStoredConnection({
messages: [
{
role: "user",
@@ -791,11 +800,9 @@ describe("LLM Connection Tests", () => {
},
});
- expect(completion).toHaveProperty("tool_calls");
- expect(Array.isArray(completion.tool_calls)).toBe(true);
- expect(completion.tool_calls.length).toBeGreaterThan(0);
- expect(completion.tool_calls[0].name).toBe("get_weather");
- expect(completion.tool_calls[0].args).toHaveProperty("location");
+ expect(completion.toolCalls.length).toBeGreaterThan(0);
+ expect(completion.toolCalls[0].toolName).toBe("get_weather");
+ expect(completion.toolCalls[0].input).toHaveProperty("location");
}, 30_000);
});
@@ -833,8 +840,7 @@ describe("LLM Connection Tests", () => {
test("simple completion", async () => {
checkEnvVars();
- const completion = await fetchLLMCompletion({
- streaming: false,
+ const completion = await generateWithStoredConnection({
messages: [
{
role: "user",
@@ -855,15 +861,13 @@ describe("LLM Connection Tests", () => {
},
});
- expect(typeof completion).toBe("string");
- expect(completion).toContain("4");
+ expect(completion.text).toContain("4");
}, 30_000);
test("streaming completion", async () => {
checkEnvVars();
- const stream = await fetchLLMCompletion({
- streaming: true,
+ const stream = await streamWithStoredConnection({
messages: [
{
role: "user",
@@ -884,12 +888,11 @@ describe("LLM Connection Tests", () => {
},
});
- const decoder = new TextDecoder();
let fullResponse = "";
let chunkCount = 0;
- for await (const chunk of stream) {
- fullResponse += decoder.decode(chunk);
+ for await (const chunk of stream.textStream) {
+ fullResponse += chunk;
chunkCount++;
}
@@ -914,8 +917,7 @@ describe("LLM Connection Tests", () => {
test("simple completion", async () => {
checkEnvVar();
- const completion = await fetchLLMCompletion({
- streaming: false,
+ const completion = await generateWithStoredConnection({
messages: [
{
role: "user",
@@ -936,9 +938,7 @@ describe("LLM Connection Tests", () => {
},
});
- // VertexAI always returns CompletionWithReasoning (text + optional reasoning)
- expect(typeof completion).toBe("object");
- expect((completion as CompletionWithReasoning).text).toContain("4");
+ expect(completion.text).toContain("4");
}, 30_000);
test("Claude model routes through Anthropic publisher endpoint", async () => {
@@ -947,8 +947,7 @@ describe("LLM Connection Tests", () => {
const claudeVertexModel = "claude-3-haiku@20240307";
try {
- const completion = await fetchLLMCompletion({
- streaming: false,
+ const completion = await generateWithStoredConnection({
messages: [
{
role: "user",
@@ -971,28 +970,31 @@ describe("LLM Connection Tests", () => {
},
});
- expect(typeof completion).toBe("object");
- expect((completion as CompletionWithReasoning).text).toContain("4");
+ expect(completion.text).toContain("4");
} catch (error) {
const message = String(error);
// The CI project currently does not have access to Anthropic publisher
// models. The regression signal is that Claude-on-Vertex reaches the
// Anthropic publisher endpoint instead of /v1/v1/messages or Google's
- // Gemini/Gemma publisher path.
- expect(message).toContain(
- `/publishers/anthropic/models/${claudeVertexModel}`,
- );
- expect(message).not.toContain("/v1/v1/messages");
- expect(message).not.toContain("/publishers/google/");
+ // Gemini/Gemma publisher path. Some provider errors only include the
+ // normalized Vertex 404 without echoing the request URL.
+ if (message.includes("/publishers/")) {
+ expect(message).toContain(
+ `/publishers/anthropic/models/${claudeVertexModel}`,
+ );
+ expect(message).not.toContain("/v1/v1/messages");
+ expect(message).not.toContain("/publishers/google/");
+ } else {
+ expect(message).toContain("Not Found");
+ }
}
}, 30_000);
test("streaming completion", async () => {
checkEnvVar();
- const stream = await fetchLLMCompletion({
- streaming: true,
+ const stream = await streamWithStoredConnection({
messages: [
{
role: "user",
@@ -1013,12 +1015,11 @@ describe("LLM Connection Tests", () => {
},
});
- const decoder = new TextDecoder();
let fullResponse = "";
let chunkCount = 0;
- for await (const chunk of stream) {
- fullResponse += decoder.decode(chunk);
+ for await (const chunk of stream.textStream) {
+ fullResponse += chunk;
chunkCount++;
}
@@ -1045,8 +1046,7 @@ describe("LLM Connection Tests", () => {
test("tool calling", async () => {
checkEnvVar();
- const completion = await fetchLLMCompletion({
- streaming: false,
+ const completion = await generateWithStoredConnection({
messages: [
{
role: "user",
@@ -1068,18 +1068,15 @@ describe("LLM Connection Tests", () => {
},
});
- expect(completion).toHaveProperty("tool_calls");
- expect(Array.isArray(completion.tool_calls)).toBe(true);
- expect(completion.tool_calls.length).toBeGreaterThan(0);
- expect(completion.tool_calls[0].name).toBe("get_weather");
- expect(completion.tool_calls[0].args).toHaveProperty("location");
+ expect(completion.toolCalls.length).toBeGreaterThan(0);
+ expect(completion.toolCalls[0].toolName).toBe("get_weather");
+ expect(completion.toolCalls[0].input).toHaveProperty("location");
}, 30_000);
test("thinking model with tool calling strips reasoning from content and parses tool calls", async () => {
checkEnvVar();
- const completion = await fetchLLMCompletion({
- streaming: false,
+ const completion = await generateWithStoredConnection({
messages: [
{
role: "user",
@@ -1103,21 +1100,18 @@ describe("LLM Connection Tests", () => {
});
// Should parse tool calls successfully despite reasoning blocks in content
- expect(completion).toHaveProperty("tool_calls");
- expect(Array.isArray(completion.tool_calls)).toBe(true);
- expect(completion.tool_calls.length).toBeGreaterThan(0);
- expect(completion.tool_calls[0].name).toBe("get_weather");
+ expect(completion.toolCalls.length).toBeGreaterThan(0);
+ expect(completion.toolCalls[0].toolName).toBe("get_weather");
// Reasoning should be extracted separately
- if ((completion as any).reasoning) {
- expect(typeof (completion as any).reasoning).toBe("string");
+ if (completion.reasoningText) {
+ expect(typeof completion.reasoningText).toBe("string");
}
}, 60_000);
- test("thinking model returns CompletionWithReasoning with separate text and reasoning", async () => {
+ test("thinking model exposes text and reasoning separately", async () => {
checkEnvVar();
- const completion = await fetchLLMCompletion({
- streaming: false,
+ const completion = await generateWithStoredConnection({
messages: [
{
role: "user",
@@ -1139,10 +1133,7 @@ describe("LLM Connection Tests", () => {
},
});
- // Always returns CompletionWithReasoning for VertexAI
- expect(typeof completion).toBe("object");
- const result = completion as CompletionWithReasoning;
- expect(result.text).toContain("4");
+ expect(completion.text).toContain("4");
// With maxReasoningTokens > 0, reasoning should be present
// Note: this depends on the model actually producing reasoning output
}, 60_000);
@@ -1163,8 +1154,7 @@ describe("LLM Connection Tests", () => {
checkEnvVar();
const completion = await runWithGoogleAIStudioModelFallback((model) =>
- fetchLLMCompletion({
- streaming: false,
+ generateWithStoredConnection({
messages: [
{
role: "user",
@@ -1187,17 +1177,14 @@ describe("LLM Connection Tests", () => {
}),
);
- // GoogleAIStudio always returns CompletionWithReasoning (text + optional reasoning)
- expect(typeof completion).toBe("object");
- expect((completion as CompletionWithReasoning).text).toContain("4");
+ expect(completion.text).toContain("4");
}, 30_000);
test("streaming completion", async () => {
checkEnvVar();
await runWithGoogleAIStudioModelFallback(async (model) => {
- const stream = await fetchLLMCompletion({
- streaming: true,
+ const stream = await streamWithStoredConnection({
messages: [
{
role: "user",
@@ -1219,12 +1206,11 @@ describe("LLM Connection Tests", () => {
},
});
- const decoder = new TextDecoder();
let fullResponse = "";
let chunkCount = 0;
- for await (const chunk of stream) {
- fullResponse += decoder.decode(chunk);
+ for await (const chunk of stream.textStream) {
+ fullResponse += chunk;
chunkCount++;
}
@@ -1255,8 +1241,7 @@ describe("LLM Connection Tests", () => {
checkEnvVar();
const completion = await runWithGoogleAIStudioModelFallback((model) =>
- fetchLLMCompletion({
- streaming: false,
+ generateWithStoredConnection({
messages: [
{
role: "user",
@@ -1280,11 +1265,9 @@ describe("LLM Connection Tests", () => {
}),
);
- expect(completion).toHaveProperty("tool_calls");
- expect(Array.isArray(completion.tool_calls)).toBe(true);
- expect(completion.tool_calls.length).toBeGreaterThan(0);
- expect(completion.tool_calls[0].name).toBe("get_weather");
- expect(completion.tool_calls[0].args).toHaveProperty("location");
+ expect(completion.toolCalls.length).toBeGreaterThan(0);
+ expect(completion.toolCalls[0].toolName).toBe("get_weather");
+ expect(completion.toolCalls[0].input).toHaveProperty("location");
}, 30_000);
test("single system message is converted to user message", async () => {
@@ -1294,8 +1277,7 @@ describe("LLM Connection Tests", () => {
// GoogleAIStudio must convert it to a user message to prevent:
// "GenerateContentRequest.contents is not specified" error
const completion = await runWithGoogleAIStudioModelFallback((model) =>
- fetchLLMCompletion({
- streaming: false,
+ generateWithStoredConnection({
messages: [
{
role: "system",
@@ -1318,9 +1300,7 @@ describe("LLM Connection Tests", () => {
}),
);
- // GoogleAIStudio always returns CompletionWithReasoning
- expect(typeof completion).toBe("object");
- expect((completion as CompletionWithReasoning).text).toContain("4");
+ expect(completion.text).toContain("4");
}, 30_000);
});
});
diff --git a/worker/src/__tests__/network.ts b/worker/src/__tests__/network.ts
index 5bda2da5e1..27a330a04e 100644
--- a/worker/src/__tests__/network.ts
+++ b/worker/src/__tests__/network.ts
@@ -12,21 +12,14 @@ const DEFAULT_RESPONSE = {
index: 0,
message: {
role: "assistant",
- content: null,
- tool_calls: [
- {
- function: {
- name: "extract",
- arguments: JSON.stringify({
- score: 0,
- reasoning:
- "The provided text is a harmless play on words that poses no risk of harm or offense. It is a lighthearted joke that uses wordplay to create humor without targeting or derogating any group of people.",
- }),
- type: "tool_call",
- id: "call_cJ6HLI1gZSIRJVOrFsChO1SI",
- },
- },
- ],
+ // AI SDK structured outputs use OpenAI response_format and return the
+ // validated object as JSON text, rather than the legacy LangChain
+ // extraction tool-call shape.
+ content: JSON.stringify({
+ score: 0,
+ reasoning:
+ "The provided text is a harmless play on words that poses no risk of harm or offense. It is a lighthearted joke that uses wordplay to create humor without targeting or derogating any group of people.",
+ }),
},
logprobs: null,
finish_reason: "stop",
diff --git a/worker/src/__tests__/secureLlmFetch.test.ts b/worker/src/__tests__/secureLlmFetch.test.ts
index d14edb4a7e..e40ae97a82 100644
--- a/worker/src/__tests__/secureLlmFetch.test.ts
+++ b/worker/src/__tests__/secureLlmFetch.test.ts
@@ -1,11 +1,11 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { encrypt } from "../../../packages/shared/src/encryption";
import { env } from "../../../packages/shared/src/env";
+import { LLMAdapter } from "../../../packages/shared/src/server/llm/types";
import {
- ChatMessageType,
- LLMAdapter,
-} from "../../../packages/shared/src/server/llm/types";
-import { fetchLLMCompletion } from "../../../packages/shared/src/server/llm/fetchLLMCompletion";
+ generateLLMText,
+ streamLLMText,
+} from "../../../packages/shared/src/server/llm/llmText";
import {
createSecureLlmFetch,
fetchSecureLlmUrl,
@@ -84,6 +84,7 @@ const OPENAI_RESPONSES_RESPONSE = JSON.parse(OPENAI_RESPONSES_BODY);
describe("secure LLM fetch", () => {
const originalWhitelistedHosts = env.LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST;
+ const originalWhitelistedIps = env.LANGFUSE_LLM_CONNECTION_WHITELISTED_IPS;
// env is the zod-validated object: read from process.env at module load and
// not refreshed afterward. Mutating process.env later is a no-op for the
// code under test, so we mutate `env.*` directly and restore in afterEach.
@@ -93,12 +94,14 @@ describe("secure LLM fetch", () => {
beforeEach(() => {
env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;
env.LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST = ["127.0.0.1"];
+ env.LANGFUSE_LLM_CONNECTION_WHITELISTED_IPS = ["127.0.0.1"];
});
afterEach(async () => {
vi.restoreAllMocks();
await Promise.all(servers.splice(0).map((s) => s.close()));
env.LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST = originalWhitelistedHosts;
+ env.LANGFUSE_LLM_CONNECTION_WHITELISTED_IPS = originalWhitelistedIps;
env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;
});
@@ -120,29 +123,26 @@ describe("secure LLM fetch", () => {
res.end(OPENAI_RESPONSE_BODY);
});
- const completion = await fetchLLMCompletion({
- streaming: false,
+ const completion = await generateLLMText({
messages: [
{
role: "user",
content: "What is 2+2? Answer only with the number.",
- type: ChatMessageType.PublicAPICreated,
},
],
- modelParams: {
- provider: "openai",
+ model: {
adapter: LLMAdapter.OpenAI,
- model: "gpt-4o-mini",
- temperature: 0,
- max_tokens: 10,
+ id: "gpt-4o-mini",
},
- llmConnection: {
+ temperature: 0,
+ maxOutputTokens: 10,
+ connection: {
secretKey: encrypt("openai-api-key"),
baseURL: `${server.url}/v1`,
},
});
- expect(completion).toBe("4");
+ expect(completion.text).toBe("4");
expect(server.requests).toHaveLength(1);
const [request] = server.requests;
expect(request.method).toBe("POST");
@@ -164,23 +164,20 @@ describe("secure LLM fetch", () => {
res.end(OPENAI_RESPONSES_BODY);
});
- const completion = await fetchLLMCompletion({
- streaming: false,
+ const completion = await generateLLMText({
messages: [
{
role: "user",
content: "What is 2+2? Answer only with the number.",
- type: ChatMessageType.PublicAPICreated,
},
],
- modelParams: {
- provider: "openai",
+ model: {
adapter: LLMAdapter.OpenAI,
- model: "gpt-4o-mini",
- temperature: 0,
- max_tokens: 10,
+ id: "gpt-4o-mini",
},
- llmConnection: {
+ temperature: 0,
+ maxOutputTokens: 10,
+ connection: {
secretKey: encrypt("openai-api-key"),
baseURL: `${server.url}/v1`,
config: {
@@ -189,7 +186,7 @@ describe("secure LLM fetch", () => {
},
});
- expect(completion).toBe("4");
+ expect(completion.text).toBe("4");
expect(server.requests).toHaveLength(1);
const [request] = server.requests;
expect(request.method).toBe("POST");
@@ -250,23 +247,20 @@ describe("secure LLM fetch", () => {
res.end();
});
- const stream = await fetchLLMCompletion({
- streaming: true,
+ const stream = await streamLLMText({
messages: [
{
role: "user",
content: "What is 2+2? Answer only with the number.",
- type: ChatMessageType.PublicAPICreated,
},
],
- modelParams: {
- provider: "openai",
+ model: {
adapter: LLMAdapter.OpenAI,
- model: "gpt-4o-mini",
- temperature: 0,
- max_tokens: 10,
+ id: "gpt-4o-mini",
},
- llmConnection: {
+ temperature: 0,
+ maxOutputTokens: 10,
+ connection: {
secretKey: encrypt("openai-api-key"),
baseURL: `${server.url}/v1`,
config: {
@@ -275,10 +269,9 @@ describe("secure LLM fetch", () => {
},
});
- const decoder = new TextDecoder();
let text = "";
- for await (const chunk of stream) {
- text += decoder.decode(chunk);
+ for await (const chunk of stream.textStream) {
+ text += chunk;
}
expect(text).toBe("pong");
@@ -286,6 +279,45 @@ describe("secure LLM fetch", () => {
expect(server.requests[0].url).toBe("/v1/responses");
},
);
+
+ test(
+ "strips encrypted connection headers from cross-origin redirects",
+ { timeout: 30_000 },
+ async () => {
+ const target = await spinUp((_req, _body, res) => {
+ res.setHeader("content-type", "application/json");
+ res.end(OPENAI_RESPONSE_BODY);
+ });
+ const redirector = await spinUp((_req, _body, res) => {
+ res.statusCode = 307;
+ res.setHeader("location", `${target.url}/v1/chat/completions`);
+ res.end();
+ });
+
+ const completion = await generateLLMText({
+ messages: [{ role: "user", content: "Say 4" }],
+ model: {
+ adapter: LLMAdapter.OpenAI,
+ id: "gpt-4o-mini",
+ },
+ connection: {
+ secretKey: encrypt("openai-api-key"),
+ baseURL: `${redirector.url}/v1`,
+ extraHeaders: encrypt(
+ JSON.stringify({ "x-gateway-token": "gateway-secret" }),
+ ),
+ },
+ });
+
+ expect(completion.text).toBe("4");
+ expect(redirector.requests).toHaveLength(1);
+ expect(redirector.requests[0].headers["x-gateway-token"]).toBe(
+ "gateway-secret",
+ );
+ expect(target.requests).toHaveLength(1);
+ expect(target.requests[0].headers["x-gateway-token"]).toBeUndefined();
+ },
+ );
});
describe("SSRF protection", () => {
diff --git a/worker/src/features/evaluation/__tests__/evalExecutionDeps.test.ts b/worker/src/features/evaluation/__tests__/evalExecutionDeps.test.ts
index 9c78b53392..21042a59d8 100644
--- a/worker/src/features/evaluation/__tests__/evalExecutionDeps.test.ts
+++ b/worker/src/features/evaluation/__tests__/evalExecutionDeps.test.ts
@@ -3,8 +3,8 @@ import { z } from "zod";
import { createProductionEvalExecutionDeps } from "../evalExecutionDeps";
import { EXPORT_VOLUME_METRIC } from "../../../services/exportVolumeMetric";
-const { mockFetchLLMCompletion, mockRecordIncrement } = vi.hoisted(() => ({
- mockFetchLLMCompletion: vi.fn(),
+const { mockGenerateLLMText, mockRecordIncrement } = vi.hoisted(() => ({
+ mockGenerateLLMText: vi.fn(),
mockRecordIncrement: vi.fn(),
}));
@@ -13,7 +13,7 @@ vi.mock("@langfuse/shared/src/server", async (importOriginal) => {
await importOriginal<typeof import("@langfuse/shared/src/server")>();
return {
...original,
- fetchLLMCompletion: mockFetchLLMCompletion,
+ generateLLMText: mockGenerateLLMText,
recordIncrement: mockRecordIncrement,
};
});
@@ -32,7 +32,7 @@ vi.mock("../../../env", async (importOriginal) => {
describe("createProductionEvalExecutionDeps", () => {
beforeEach(() => {
vi.clearAllMocks();
- mockFetchLLMCompletion.mockResolvedValue({ completion: "ok" });
+ mockGenerateLLMText.mockResolvedValue({ output: { completion: "ok" } });
});
it("enables internal direct event write for llm-as-a-judge traces", async () => {
@@ -68,9 +68,9 @@ describe("createProductionEvalExecutionDeps", () => {
},
});
- expect(mockFetchLLMCompletion).toHaveBeenCalledWith(
+ expect(mockGenerateLLMText).toHaveBeenCalledWith(
expect.objectContaining({
- traceSinkParams: expect.objectContaining({
+ trace: expect.objectContaining({
traceId: "trace-123",
environment: "langfuse-llm-as-a-judge",
eventsWriter: expect.objectContaining({
diff --git a/worker/src/features/evaluation/evalExecutionDeps.ts b/worker/src/features/evaluation/evalExecutionDeps.ts
index d3a9d8b7b4..7a23a2e661 100644
--- a/worker/src/features/evaluation/evalExecutionDeps.ts
+++ b/worker/src/features/evaluation/evalExecutionDeps.ts
@@ -4,10 +4,12 @@ import { JobExecutionStatus } from "@prisma/client";
import { prisma } from "@langfuse/shared/src/db";
import {
buildEventBucketPrefix,
+ createLLMOutput,
DefaultEvalModelService,
- fetchLLMCompletion,
+ generateLLMText,
IngestionQueue,
LLMAdapter,
+ mapLegacyLLMCompletionParams,
QueueJobs,
ScoreEventType,
UNKNOWN_INGESTION_SDK_VALUE,
@@ -17,9 +19,7 @@ import { getEvalS3StorageClient } from "./s3StorageClient";
import { createInternalEventsWriter } from "../internal-tracing/createInternalEventsWriter";
import { recordExportVolume } from "../../services/exportVolumeMetric";
-type StructuredOutputSchema = NonNullable<
- Parameters<typeof fetchLLMCompletion>[0]["structuredOutputSchema"]
->;
+type StructuredOutputSchema = z.ZodType;
/**
* Result of fetching model configuration.
@@ -206,15 +206,16 @@ export function createProductionEvalExecutionDeps(): EvalExecutionDeps {
},
callLLM: async (params) => {
- // Type assertion needed because the deps interface uses a simplified apiKey type for testability
- // while the actual fetchLLMCompletion requires a full LlmApiKey type
- const llmConnection = params.modelConfig.apiKey as unknown as Parameters<
- typeof fetchLLMCompletion
- >[0]["llmConnection"];
+ // The dependency interface deliberately keeps the stored connection
+ // shape small for testability. The boundary mapper owns conversion from
+ // persisted Langfuse settings into the native AI SDK call contract.
+ const connection = params.modelConfig.apiKey as unknown as Parameters<
+ typeof mapLegacyLLMCompletionParams
+ >[0]["connection"];
const adapter = params.modelConfig.apiKey
.adapter as unknown as Parameters<
- typeof fetchLLMCompletion
+ typeof mapLegacyLLMCompletionParams
>[0]["modelParams"]["adapter"];
// llmaj egress: serialized request body (messages + schema), uncompressed.
@@ -227,9 +228,8 @@ export function createProductionEvalExecutionDeps(): EvalExecutionDeps {
)
: 0);
- const result = await fetchLLMCompletion({
- streaming: false,
- llmConnection,
+ const llmParams = mapLegacyLLMCompletionParams({
+ connection,
messages: params.messages,
modelParams: {
provider: params.modelConfig.provider,
@@ -237,9 +237,12 @@ export function createProductionEvalExecutionDeps(): EvalExecutionDeps {
adapter,
...params.modelConfig.modelParams,
},
- structuredOutputSchema: params.structuredOutputSchema,
+ });
+ const result = await generateLLMText({
+ ...llmParams,
+ output: createLLMOutput(params.structuredOutputSchema),
maxRetries: 1,
- traceSinkParams: {
+ trace: {
targetProjectId: params.traceSinkParams.targetProjectId,
traceId: params.traceSinkParams.traceId,
traceName: params.traceSinkParams.traceName,
@@ -256,7 +259,7 @@ export function createProductionEvalExecutionDeps(): EvalExecutionDeps {
projectId: params.traceSinkParams.targetProjectId,
});
- return result;
+ return result.output;
},
fetchModelConfig: async ({ projectId, provider, model, modelParams }) => {
diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.ts
index 7e1b5607d9..ea20b3cd7f 100644
--- a/worker/src/features/evaluation/evalService.ts
+++ b/worker/src/features/evaluation/evalService.ts
@@ -238,9 +238,10 @@ export const createEvalJobs = async ({
//
// DUAL SAFEGUARD:
// - This check prevents eval job CREATION for internal traces
- // - fetchLLMCompletion.ts enforces that internal traces MUST use "langfuse-" prefix
+ // - The shared LLM runtime enforces that internal traces MUST use the
+ // "langfuse-" prefix
//
- // See: packages/shared/src/server/llm/fetchLLMCompletion.ts (enforcement)
+ // See: packages/shared/src/server/llm (enforcement)
// See: packages/shared/src/server/llm/types.ts (LangfuseInternalTraceEnvironment enum)
if (
sourceEventType === "trace-upsert" &&
diff --git a/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts b/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts
index fbed795a5e..e41067a1ea 100644
--- a/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts
+++ b/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts
@@ -32,15 +32,15 @@ interface ScheduleObservationEvalsParams {
*
* 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
+ * (shared AI SDK LLM runtime), 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
+ * equivalent of internal tracing's synchronous onRootEventRecordReady
+ * scheduling, which only ever offers 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.
diff --git a/worker/src/features/experiments/experimentServiceClickhouse.ts b/worker/src/features/experiments/experimentServiceClickhouse.ts
index dc692dc34e..84488d536f 100644
--- a/worker/src/features/experiments/experimentServiceClickhouse.ts
+++ b/worker/src/features/experiments/experimentServiceClickhouse.ts
@@ -7,16 +7,18 @@ import {
import {
ChatMessage,
convertDateToClickhouseDateTime,
+ createLLMOutput,
createUnknownSdkIngestionAttribution,
createDatasetItemFilterState,
DatasetRunItemUpsertQueue,
eventTypes,
ExperimentCreateEventSchema,
- fetchLLMCompletion,
+ generateLLMText,
getDatasetItems,
IngestionEventType,
LangfuseInternalTraceEnvironment,
logger,
+ mapLegacyLLMCompletionParams,
processEventBatch,
queryClickhouse,
QueueJobs,
@@ -206,10 +208,8 @@ async function processLLMCall(
}),
};
- await fetchLLMCompletion({
- streaming: false,
- llmConnection: config.validatedApiKey,
- maxRetries: 1,
+ const llmParams = mapLegacyLLMCompletionParams({
+ connection: config.validatedApiKey,
messages,
modelParams: {
provider: config.provider,
@@ -217,9 +217,16 @@ async function processLLMCall(
adapter: config.validatedApiKey.adapter,
...config.model_params,
},
- structuredOutputSchema: config.structuredOutputSchema,
- traceSinkParams,
- }).catch(); // catch errors and do not retry
+ });
+
+ await generateLLMText({
+ ...llmParams,
+ maxRetries: 1,
+ ...(config.structuredOutputSchema
+ ? { output: createLLMOutput(config.structuredOutputSchema) }
+ : {}),
+ trace: traceSinkParams,
+ }).catch(() => undefined); // catch errors and do not retry
return { success: true };
}