🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore(fetch-llm-completion): add remaining AI SDK adapters (#14854)
Hassieb Pakzad2c7f86d4e058
diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 83a2f6d2ec..27a4ae4e8d 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -94,6 +94,11 @@"seed": "ts-node -r dotenv/config --compiler-options {\"module\":\"CommonJS\"} scripts/seeder/seed-postgres.ts"},"dependencies": {+ "@ai-sdk/amazon-bedrock": "^5.0.8",+ "@ai-sdk/anthropic": "^4.0.5",+ "@ai-sdk/azure": "^4.0.5",+ "@ai-sdk/google": "^4.0.6",+ "@ai-sdk/google-vertex": "^5.0.8","@ai-sdk/openai": "^4.0.0","@anthropic-ai/tokenizer": "^0.0.4","@anthropic-ai/vertex-sdk": "^0.17.1",@@ -101,6 +106,7 @@"@aws-sdk/client-lambda": "^3.1046.0","@aws-sdk/client-s3": "^3.1013.0","@aws-sdk/client-sesv2": "^3.1013.0",+ "@aws-sdk/credential-providers": "^3.1056.0","@aws-sdk/lib-storage": "^3.1013.0","@aws-sdk/s3-request-presigner": "^3.1013.0","@azure/storage-blob": "^12.26.0",diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex cfa170c913..0e306e0572 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -450,8 +450,9 @@ const EnvSchema = z.object({.positive().default(120_000), // 2 minutes- // Comma-separated list of LLM adapters (e.g. "openai") whose completions run- // on the AI SDK execution engine instead of LangChain+ // 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 LangChainLANGFUSE_LLM_COMPLETION_AI_SDK_ADAPTERS: z.string().optional()diff --git a/packages/shared/src/server/llm/ai-sdk/executeAiSdkCompletion.ts b/packages/shared/src/server/llm/ai-sdk/executeAiSdkCompletion.tsindex e1340d91ff..30ee42d5f2 100644--- a/packages/shared/src/server/llm/ai-sdk/executeAiSdkCompletion.ts+++ b/packages/shared/src/server/llm/ai-sdk/executeAiSdkCompletion.ts@@ -19,6 +19,7 @@ import {mapToLLMCompletionError,} from "../completionErrorMapping";import { LLMCompletionError } from "../errors";+import type { LLMConnectionConfig } from "../../../interfaces/customLLMProviderConfigSchemas";import {ChatMessage,LLMJSONSchema,@@ -29,7 +30,8 @@ import {TraceSinkParams,} from "../types";import { mapChatMessagesToModelMessages } from "./messages";-import { buildOpenAIModel, type OpenAIApiMode } from "./providers/openai";+import { buildAiSdkModel, type CreateSecureFetch } from "./providers";+import type { AiSdkEngineDecision } from "./resolveLlmExecutionDecision";import {createAiSdkTelemetryCapture,type AiSdkTelemetryCapture,@@ -59,11 +61,12 @@ export type AiSdkCompletionParams = {apiKey: string;baseURL?: string | null;extraHeaders?: Record<string, string>;+ llmConnectionConfig?: LLMConnectionConfig | null;+ shouldUseLangfuseAPIKey?: boolean;maxRetries?: number;timeoutMs: number;- fetch: typeof fetch;- apiMode: OpenAIApiMode;- translatedProviderOptions?: Record<string, unknown>;+ createFetch: CreateSecureFetch;+ decision: AiSdkEngineDecision;traceSinkParams?: TraceSinkParams;};@@ -90,7 +93,7 @@ export async function executeAiSdkCompletion(structuredOutputSchema,maxRetries,timeoutMs,- translatedProviderOptions,+ decision,traceSinkParams,} = params;@@ -101,8 +104,19 @@ export async function executeAiSdkCompletion(let modelMessages: ModelMessage[];let capture: AiSdkTelemetryCapture | undefined;try {- model = buildOpenAIModel(params);- modelMessages = mapChatMessagesToModelMessages(messages);+ 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,@@ -129,10 +143,11 @@ export async function executeAiSdkCompletion(topP: modelParams.top_p,maxRetries,timeout: timeoutMs,- ...(translatedProviderOptions+ ...(decision.translatedProviderOptions? {providerOptions: {- openai: translatedProviderOptions as Record<string, JSONValue>,+ [decision.providerOptionsName]:+ decision.translatedProviderOptions as Record<string, JSONValue>,},}: {}),diff --git a/packages/shared/src/server/llm/ai-sdk/messages.test.ts b/packages/shared/src/server/llm/ai-sdk/messages.test.tsnew file mode 100644index 0000000000..93543daa6c--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/messages.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from "vitest";++import {+ type ChatMessage,+ ChatMessageRole,+ ChatMessageType,+ LLMAdapter,+} from "../types";+import { mapChatMessagesToModelMessages } from "./messages";++const systemMessage: ChatMessage = {+ type: ChatMessageType.System,+ role: ChatMessageRole.System,+ content: "You are terse.",+};++const userMessage: ChatMessage = {+ type: ChatMessageType.User,+ role: ChatMessageRole.User,+ content: "Hi",+};++describe("mapChatMessagesToModelMessages", () => {+ it("keeps the first system message as system", () => {+ expect(+ mapChatMessagesToModelMessages([systemMessage, userMessage], {+ adapter: LLMAdapter.Anthropic,+ }),+ ).toEqual([+ { role: "system", content: "You are terse." },+ { role: "user", content: "Hi" },+ ]);+ });++ it("converts a lone message to a user message for providers requiring one", () => {+ for (const adapter of [+ LLMAdapter.Anthropic,+ LLMAdapter.Bedrock,+ LLMAdapter.VertexAI,+ LLMAdapter.GoogleAIStudio,+ ]) {+ expect(+ mapChatMessagesToModelMessages([systemMessage], { adapter }),+ ).toEqual([{ role: "user", content: "You are terse." }]);+ }+ });++ it("keeps a lone system message as system for OpenAI-style providers", () => {+ for (const adapter of [LLMAdapter.OpenAI, LLMAdapter.Azure]) {+ expect(+ mapChatMessagesToModelMessages([systemMessage], { adapter }),+ ).toEqual([{ role: "system", content: "You are terse." }]);+ }+ });++ it("drops a lone empty message like the LangChain filter", () => {+ expect(+ mapChatMessagesToModelMessages([{ ...systemMessage, content: "" }], {+ adapter: LLMAdapter.Anthropic,+ }),+ ).toEqual([]);+ });+});diff --git a/packages/shared/src/server/llm/ai-sdk/messages.ts b/packages/shared/src/server/llm/ai-sdk/messages.tsindex 87e430e940..fc9fa181bb 100644--- a/packages/shared/src/server/llm/ai-sdk/messages.ts+++ b/packages/shared/src/server/llm/ai-sdk/messages.ts@@ -5,7 +5,9 @@ import {ChatMessage,ChatMessageRole,ChatMessageType,+ LLMAdapter,LLMToolCall,+ PROVIDERS_WITH_REQUIRED_USER_MESSAGE,} from "../types";// Helper function to safely stringify content@@ -29,10 +31,25 @@ const toSafeContent = (content: unknown): string =>* - tool results resolve their `toolName` from the preceding assistant* tool-call messages; orphan tool results fail fast as a non-retryable* error instead of a provider-side 400+ * - for providers that require at least one user message, a lone message+ * becomes a user message regardless of its role (LangChain-parity:+ * `transformSystemMessageToUserMessage`)*/export function mapChatMessagesToModelMessages(messages: ChatMessage[],+ options?: { adapter?: LLMAdapter },): ModelMessage[] {+ if (+ messages.length === 1 &&+ options?.adapter !== undefined &&+ PROVIDERS_WITH_REQUIRED_USER_MESSAGE.includes(options.adapter)+ ) {+ const safeContent = toSafeContent(messages[0].content);+ return safeContent.length > 0+ ? [{ role: "user", content: safeContent }]+ : [];+ }+const toolCallIdToName = new Map<string, string>();for (const message of messages) {if (message.type === ChatMessageType.AssistantToolCall) {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.tsnew file mode 100644index 0000000000..ace166360b--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/providers/anthropic.test.ts@@ -0,0 +1,149 @@+import { describe, expect, it } from "vitest";++import {+ toAnthropicBaseURL,+ translateAnthropicProviderOptions,+} from "./anthropic";++describe("toAnthropicBaseURL", () => {+ it("returns undefined for missing baseURL", () => {+ expect(toAnthropicBaseURL(undefined)).toBeUndefined();+ expect(toAnthropicBaseURL(null)).toBeUndefined();+ expect(toAnthropicBaseURL("")).toBeUndefined();+ });++ it("appends /v1 to the origin-style URL LangChain expects", () => {+ expect(toAnthropicBaseURL("https://api.anthropic.com")).toBe(+ "https://api.anthropic.com/v1",+ );+ expect(toAnthropicBaseURL("https://proxy.example.com/anthropic/")).toBe(+ "https://proxy.example.com/anthropic/v1",+ );+ });++ it("keeps an existing /v1 suffix", () => {+ expect(toAnthropicBaseURL("https://api.anthropic.com/v1")).toBe(+ "https://api.anthropic.com/v1",+ );+ expect(toAnthropicBaseURL("https://api.anthropic.com/v1/")).toBe(+ "https://api.anthropic.com/v1",+ );+ });+});++describe("translateAnthropicProviderOptions", () => {+ it("returns undefined for empty input", () => {+ expect(translateAnthropicProviderOptions(undefined)).toEqual({+ ok: true,+ value: undefined,+ });+ expect(translateAnthropicProviderOptions({})).toEqual({+ ok: true,+ value: undefined,+ });+ });++ it("translates snake_case thinking config to AI SDK camelCase", () => {+ expect(+ translateAnthropicProviderOptions({+ thinking: { type: "enabled", budget_tokens: 2048 },+ }),+ ).toEqual({+ ok: true,+ value: { thinking: { type: "enabled", budgetTokens: 2048 } },+ });+ });++ it("passes through camelCase thinking and adaptive display", () => {+ expect(+ translateAnthropicProviderOptions({+ thinking: { type: "adaptive", display: "summarized" },+ }),+ ).toEqual({+ ok: true,+ value: { thinking: { type: "adaptive", display: "summarized" } },+ });+ expect(+ translateAnthropicProviderOptions({+ thinking: { type: "enabled", budgetTokens: 1024 },+ }),+ ).toEqual({+ ok: true,+ value: { thinking: { type: "enabled", budgetTokens: 1024 } },+ });+ });++ it("rejects thinking configs with unknown shape", () => {+ expect(+ translateAnthropicProviderOptions({+ thinking: { type: "enabled", budget_tokens: 1024, custom: true },+ }),+ ).toEqual({ ok: false, unknownKeys: ["thinking"] });+ expect(translateAnthropicProviderOptions({ thinking: "enabled" })).toEqual({+ ok: false,+ unknownKeys: ["thinking"],+ });+ });++ it("translates metadata.user_id", () => {+ expect(+ translateAnthropicProviderOptions({ metadata: { user_id: "user-1" } }),+ ).toEqual({ ok: true, value: { metadata: { userId: "user-1" } } });+ });++ it("rejects metadata with unknown fields", () => {+ expect(+ translateAnthropicProviderOptions({ metadata: { foo: "bar" } }),+ ).toEqual({ ok: false, unknownKeys: ["metadata"] });+ });++ it("passes through AI SDK-shaped keys", () => {+ expect(+ translateAnthropicProviderOptions({+ sendReasoning: true,+ disableParallelToolUse: true,+ structuredOutputMode: "jsonTool",+ }),+ ).toEqual({+ ok: true,+ value: {+ sendReasoning: true,+ disableParallelToolUse: true,+ structuredOutputMode: "jsonTool",+ },+ });+ });++ it("merges a nested anthropic object verbatim", () => {+ expect(+ translateAnthropicProviderOptions({+ anthropic: { thinking: { type: "enabled", budgetTokens: 512 } },+ }),+ ).toEqual({+ ok: true,+ value: { thinking: { type: "enabled", budgetTokens: 512 } },+ });+ });++ it("rejects unknown keys instead of silently dropping them", () => {+ expect(+ translateAnthropicProviderOptions({+ thinking: { type: "enabled" },+ top_k: 5,+ output_config: { effort: "high" },+ }),+ ).toEqual({ ok: false, unknownKeys: ["top_k", "output_config"] });+ });++ it("drops a model override only for the Vertex-Claude path", () => {+ expect(+ translateAnthropicProviderOptions(+ { model: "claude-override" },+ { dropModelOverride: true },+ ),+ ).toEqual({ ok: true, value: undefined });+ expect(+ translateAnthropicProviderOptions({ model: "claude-override" }),+ ).toEqual({ ok: false, unknownKeys: ["model"] });+ });+});diff --git a/packages/shared/src/server/llm/ai-sdk/providers/anthropic.ts b/packages/shared/src/server/llm/ai-sdk/providers/anthropic.tsnew file mode 100644index 0000000000..779e3a7e4d--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/providers/anthropic.ts@@ -0,0 +1,186 @@+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+ * `https://api.anthropic.com/v1`) and appends only `/messages`.+ */+export function toAnthropicBaseURL(+ baseURL: string | null | undefined,+): string | undefined {+ return ensureBaseURLSuffix(baseURL, "/v1");+}++export function buildAnthropicModel(params: {+ modelParams: ModelParams;+ apiKey: string;+ baseURL?: string | null;+ extraHeaders?: Record<string, string>;+ fetch: typeof fetch;+}): LanguageModel {+ const provider = createAnthropic({+ apiKey: params.apiKey,+ baseURL: toAnthropicBaseURL(params.baseURL),+ headers: params.extraHeaders,+ fetch: params.fetch,+ });++ return provider(params.modelParams.model);+}++// Keys the AI SDK Anthropic provider accepts verbatim (camelCase, already+// AI SDK-shaped). `thinking` and `metadata` are handled separately because+// their nested fields need snake_case translation.+const ANTHROPIC_PASSTHROUGH_KEYS = new Set([+ "sendReasoning",+ "disableParallelToolUse",+ "structuredOutputMode",+ "effort",+ "speed",+]);++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+ * 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.+ *+ * 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" }`.+ *+ * 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.+ */+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.+ */+ dropModelOverride?: boolean;+ },+): TranslatedProviderOptions {+ if (!providerOptions || Object.keys(providerOptions).length === 0) {+ return { ok: true, value: undefined };+ }++ const translated: Record<string, unknown> = {};+ const unknownKeys: string[] = [];++ for (const [key, value] of Object.entries(providerOptions)) {+ if (key === "anthropic" && isPlainObject(value)) {+ // Nested `anthropic` object is treated as already AI SDK-shaped.+ Object.assign(translated, value);+ continue;+ }++ if (key === "model" && options?.dropModelOverride) {+ continue;+ }++ if (key === "thinking") {+ const thinking = translateAnthropicThinking(value);+ if (!thinking.ok) {+ unknownKeys.push(key);+ continue;+ }+ translated.thinking = thinking.value;+ continue;+ }++ if (key === "metadata") {+ const metadata = translateAnthropicMetadata(value);+ if (!metadata.ok) {+ unknownKeys.push(key);+ continue;+ }+ translated.metadata = metadata.value;+ continue;+ }++ if (ANTHROPIC_PASSTHROUGH_KEYS.has(key)) {+ translated[key] = value;+ continue;+ }++ unknownKeys.push(key);+ }++ if (unknownKeys.length > 0) {+ return { ok: false, unknownKeys };+ }++ return {+ ok: true,+ value: Object.keys(translated).length > 0 ? translated : undefined,+ };+}++function translateAnthropicThinking(+ value: unknown,+): { ok: true; value: Record<string, unknown> } | { ok: false } {+ if (typeof value !== "object" || value === null) return { ok: false };++ const {+ type,+ budget_tokens: budgetTokensSnake,+ budgetTokens: budgetTokensCamel,+ display,+ ...rest+ } = value as Record<string, unknown>;++ if (Object.keys(rest).length > 0) return { ok: false };+ if (typeof type !== "string" || !ANTHROPIC_THINKING_TYPES.has(type)) {+ return { ok: false };+ }++ const budgetTokens = budgetTokensCamel ?? budgetTokensSnake;++ return {+ ok: true,+ value: {+ type,+ ...(budgetTokens !== undefined ? { budgetTokens } : {}),+ ...(display !== undefined ? { display } : {}),+ },+ };+}++function translateAnthropicMetadata(+ value: unknown,+): { ok: true; value: Record<string, unknown> } | { ok: false } {+ if (typeof value !== "object" || value === null) return { ok: false };++ const {+ user_id: userIdSnake,+ userId: userIdCamel,+ ...rest+ } = value as Record<string, unknown>;++ if (Object.keys(rest).length > 0) return { ok: false };++ const userId = userIdCamel ?? userIdSnake;++ return {+ ok: true,+ value: userId !== undefined ? { userId } : {},+ };+}diff --git a/packages/shared/src/server/llm/ai-sdk/providers/azure.test.ts b/packages/shared/src/server/llm/ai-sdk/providers/azure.test.tsnew file mode 100644index 0000000000..6501fd96ae--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/providers/azure.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from "vitest";++import { translateAzureBaseURL } from "./azure";++describe("translateAzureBaseURL", () => {+ it("strips the trailing /deployments segment", () => {+ expect(+ translateAzureBaseURL(+ "https://my-instance.openai.azure.com/openai/deployments",+ ),+ ).toEqual({+ ok: true,+ value: "https://my-instance.openai.azure.com/openai",+ });+ });++ it("tolerates trailing slashes", () => {+ expect(+ translateAzureBaseURL(+ "https://my-instance.openai.azure.com/openai/deployments/",+ ),+ ).toEqual({+ ok: true,+ value: "https://my-instance.openai.azure.com/openai",+ });+ });++ it("declines a missing base URL", () => {+ expect(translateAzureBaseURL(undefined).ok).toBe(false);+ expect(translateAzureBaseURL(null).ok).toBe(false);+ expect(translateAzureBaseURL("").ok).toBe(false);+ });++ it("declines base URLs without the /deployments suffix", () => {+ expect(+ translateAzureBaseURL("https://my-proxy.example.com/openai").ok,+ ).toBe(false);+ });+});diff --git a/packages/shared/src/server/llm/ai-sdk/providers/azure.ts b/packages/shared/src/server/llm/ai-sdk/providers/azure.tsnew file mode 100644index 0000000000..5f2a2dc66a--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/providers/azure.ts@@ -0,0 +1,69 @@+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.+const AZURE_OPENAI_API_VERSION = "2025-02-01-preview";++export type AzureBaseURLTranslation =+ | { ok: true; value: string }+ | { 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+ * `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.+ */+export function translateAzureBaseURL(+ baseURL: string | null | undefined,+): AzureBaseURLTranslation {+ if (!baseURL) {+ return { ok: false, reason: "Azure connections require a base URL" };+ }++ const trimmed = trimTrailingSlashes(baseURL);+ if (!trimmed.endsWith("/deployments")) {+ return {+ ok: false,+ reason: "Azure base URL does not end with /deployments",+ };+ }++ return { ok: true, value: trimmed.slice(0, -"/deployments".length) };+}++export function buildAzureModel(params: {+ modelParams: ModelParams;+ apiKey: string;+ baseURL?: string | null;+ extraHeaders?: Record<string, string>;+ fetch: typeof fetch;+}): 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.+ throw new Error(baseUrlTranslation.reason);+ }++ const provider = createAzure({+ apiKey: params.apiKey,+ baseURL: baseUrlTranslation.value,+ apiVersion: AZURE_OPENAI_API_VERSION,+ useDeploymentBasedUrls: true,+ headers: params.extraHeaders,+ fetch: params.fetch,+ });++ // Chat Completions to match `AzureChatOpenAI`; the model name is the Azure+ // deployment name.+ return provider.chat(params.modelParams.model);+}diff --git a/packages/shared/src/server/llm/ai-sdk/providers/bedrock.test.ts b/packages/shared/src/server/llm/ai-sdk/providers/bedrock.test.tsnew file mode 100644index 0000000000..c62915acd6--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/providers/bedrock.test.ts@@ -0,0 +1,142 @@+import { describe, expect, it } from "vitest";++import { BEDROCK_USE_DEFAULT_CREDENTIALS } from "../../../../interfaces/customLLMProviderConfigSchemas";+import {+ assertValidBedrockRegion,+ resolveBedrockProviderAuth,+ translateBedrockProviderOptions,+} from "./bedrock";++describe("translateBedrockProviderOptions", () => {+ it("returns undefined for empty input", () => {+ expect(translateBedrockProviderOptions(undefined)).toEqual({+ ok: true,+ value: undefined,+ });+ expect(translateBedrockProviderOptions({})).toEqual({+ ok: true,+ value: undefined,+ });+ });++ it("wraps options verbatim as additionalModelRequestFields", () => {+ expect(+ translateBedrockProviderOptions({+ thinking: { type: "enabled", budget_tokens: 1024 },+ top_k: 10,+ }),+ ).toEqual({+ ok: true,+ value: {+ additionalModelRequestFields: {+ thinking: { type: "enabled", budget_tokens: 1024 },+ top_k: 10,+ },+ },+ });+ });++ it("keeps a non-object bedrock key in the verbatim passthrough", () => {+ expect(+ translateBedrockProviderOptions({ bedrock: ["us-east-1"], top_k: 10 }),+ ).toEqual({+ ok: true,+ value: {+ additionalModelRequestFields: { bedrock: ["us-east-1"], top_k: 10 },+ },+ });+ });++ it("merges a nested bedrock object as AI SDK-shaped options", () => {+ expect(+ translateBedrockProviderOptions({+ bedrock: {+ reasoningConfig: { type: "enabled", budgetTokens: 1024 },+ },+ anthropic_beta: ["computer-use-2024-10-22"],+ }),+ ).toEqual({+ ok: true,+ value: {+ additionalModelRequestFields: {+ anthropic_beta: ["computer-use-2024-10-22"],+ },+ reasoningConfig: { type: "enabled", budgetTokens: 1024 },+ },+ });+ });+});++describe("assertValidBedrockRegion", () => {+ it("accepts AWS region identifiers and undefined", () => {+ expect(() => assertValidBedrockRegion("us-east-1")).not.toThrow();+ expect(() => assertValidBedrockRegion("eu-central-1")).not.toThrow();+ expect(() => assertValidBedrockRegion(undefined)).not.toThrow();+ });++ it("rejects host-reshaping regions", () => {+ expect(() =>+ assertValidBedrockRegion("[email protected]/"),+ ).toThrow("Invalid Bedrock region");+ expect(() => assertValidBedrockRegion("us-east-1.attacker.test")).toThrow(+ "Invalid Bedrock region",+ );+ });+});++describe("resolveBedrockProviderAuth", () => {+ it("uses the default credential chain for the sentinel when allowed", () => {+ const auth = resolveBedrockProviderAuth({+ secretKey: BEDROCK_USE_DEFAULT_CREDENTIALS,+ allowDefaultCredentials: true,+ });+ expect(auth.credentialProvider).toBeTypeOf("function");+ expect(auth.accessKeyId).toBeUndefined();+ // Empty string (not undefined) so the provider never falls back to the+ // server's AWS_BEARER_TOKEN_BEDROCK env var.+ expect(auth.apiKey).toBe("");+ });++ it("rejects the sentinel when default credentials are not allowed", () => {+ expect(() =>+ resolveBedrockProviderAuth({+ secretKey: BEDROCK_USE_DEFAULT_CREDENTIALS,+ allowDefaultCredentials: false,+ }),+ ).toThrow("Invalid Bedrock credentials");+ });++ it("maps access key JSON to explicit credentials, suppressing the bearer env fallback", () => {+ expect(+ resolveBedrockProviderAuth({+ secretKey: JSON.stringify({+ accessKeyId: "AKIA123",+ secretAccessKey: "secret",+ }),+ allowDefaultCredentials: false,+ }),+ ).toEqual({+ accessKeyId: "AKIA123",+ secretAccessKey: "secret",+ apiKey: "",+ });+ });++ it("maps a Bedrock API key to bearer auth", () => {+ expect(+ resolveBedrockProviderAuth({+ secretKey: JSON.stringify({ apiKey: "bedrock-key" }),+ allowDefaultCredentials: false,+ }),+ ).toEqual({ apiKey: "bedrock-key" });+ });++ it("rejects malformed credentials", () => {+ expect(() =>+ resolveBedrockProviderAuth({+ secretKey: "not-json",+ allowDefaultCredentials: false,+ }),+ ).toThrow("Invalid Bedrock credentials");+ });+});diff --git a/packages/shared/src/server/llm/ai-sdk/providers/bedrock.ts b/packages/shared/src/server/llm/ai-sdk/providers/bedrock.tsnew file mode 100644index 0000000000..dd8281d414--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/providers/bedrock.ts@@ -0,0 +1,169 @@+import { createAmazonBedrock } from "@ai-sdk/amazon-bedrock";+import { fromNodeProviderChain } from "@aws-sdk/credential-providers";+import type { LanguageModel } from "ai";++import { env } from "../../../../env";+import {+ BEDROCK_USE_DEFAULT_CREDENTIALS,+ BedrockConfigSchema,+ BedrockCredentialSchema,+ type LLMConnectionConfig,+} from "../../../../interfaces/customLLMProviderConfigSchemas";+import type { ModelParams } from "../../types";+import type { 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.+const AWS_REGION_PATTERN = /^[a-z0-9-]+$/;++export function assertValidBedrockRegion(region: string | undefined): void {+ if (region !== undefined && !AWS_REGION_PATTERN.test(region)) {+ throw new Error(+ "Invalid Bedrock region. Regions must be a single AWS region identifier.",+ );+ }+}++/**+ * 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+ * 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+ * top level instead.+ */+export function translateBedrockProviderOptions(+ providerOptions: Record<string, unknown> | undefined,+): TranslatedProviderOptions {+ if (!providerOptions || Object.keys(providerOptions).length === 0) {+ return { ok: true, value: undefined };+ }++ const { bedrock: nested, ...rest } = providerOptions;++ // A non-object `bedrock` key is not an escape hatch — keep it in the+ // verbatim passthrough like LangChain would.+ const passthrough = isPlainObject(nested)+ ? rest+ : { ...rest, ...(nested !== undefined ? { bedrock: nested } : {}) };++ const translated: Record<string, unknown> = {+ ...(Object.keys(passthrough).length > 0+ ? { additionalModelRequestFields: passthrough }+ : {}),+ };++ if (isPlainObject(nested)) {+ Object.assign(translated, nested);+ }++ return {+ ok: true,+ value: Object.keys(translated).length > 0 ? translated : undefined,+ };+}++// `createAmazonBedrock` defaults an unset `apiKey` from the server's+// AWS_BEARER_TOKEN_BEDROCK env var, and a resolved bearer token wins over+// every other credential form — a tenant's access keys would silently+// 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.+const SUPPRESS_BEARER_TOKEN_ENV_FALLBACK = { apiKey: "" };++/**+ * Mirrors `resolveBedrockAuth` on the LangChain path: 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.+ */+export function resolveBedrockProviderAuth(params: {+ secretKey: string;+ allowDefaultCredentials: boolean;+}): Pick<+ Parameters<typeof createAmazonBedrock>[0] & object,+ "accessKeyId" | "secretAccessKey" | "apiKey" | "credentialProvider"+> {+ const { secretKey, allowDefaultCredentials } = params;++ if (+ secretKey === BEDROCK_USE_DEFAULT_CREDENTIALS &&+ 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, ...).+ return {+ credentialProvider: fromNodeProviderChain(),+ ...SUPPRESS_BEARER_TOKEN_ENV_FALLBACK,+ };+ }++ try {+ const parsedCredential = BedrockCredentialSchema.parse(+ JSON.parse(secretKey),+ );++ if ("apiKey" in parsedCredential) {+ return { apiKey: parsedCredential.apiKey };+ }++ // Note: the provider only reads AWS_SESSION_TOKEN when the access keys+ // come from the environment; with both keys passed explicitly it uses the+ // (unset) option value, so no server session token can leak in here.+ return {+ accessKeyId: parsedCredential.accessKeyId,+ secretAccessKey: parsedCredential.secretAccessKey,+ ...SUPPRESS_BEARER_TOKEN_ENV_FALLBACK,+ };+ } catch {+ throw new Error(+ "Invalid Bedrock credentials. Expected AWS access key JSON or a Bedrock API key.",+ );+ }+}++/**+ * 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.+ */+export function buildBedrockModel(params: {+ modelParams: ModelParams;+ apiKey: string;+ config?: LLMConnectionConfig | null;+ shouldUseLangfuseAPIKey: boolean;+}): LanguageModel {+ const { modelParams, apiKey, config, shouldUseLangfuseAPIKey } = params;++ const { region } = shouldUseLangfuseAPIKey+ ? { region: env.LANGFUSE_AWS_BEDROCK_REGION }+ : BedrockConfigSchema.parse(config);+ assertValidBedrockRegion(region);++ const isSelfHosted = !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ const auth = resolveBedrockProviderAuth({+ secretKey: apiKey,+ allowDefaultCredentials: isSelfHosted || shouldUseLangfuseAPIKey,+ });++ const provider = createAmazonBedrock({+ region,+ ...auth,+ });++ return provider(modelParams.model);+}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.tsnew file mode 100644index 0000000000..d8afdde9ff--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/providers/google.test.ts@@ -0,0 +1,199 @@+import { describe, expect, it } from "vitest";++import {+ toGoogleAIStudioBaseURL,+ translateGoogleProviderOptions,+} from "./google";++describe("toGoogleAIStudioBaseURL", () => {+ it("returns undefined for missing baseURL", () => {+ expect(toGoogleAIStudioBaseURL(undefined)).toBeUndefined();+ expect(toGoogleAIStudioBaseURL(null)).toBeUndefined();+ });++ it("appends /v1beta to the origin-style URL LangChain expects", () => {+ expect(toGoogleAIStudioBaseURL("https://proxy.example.com/google")).toBe(+ "https://proxy.example.com/google/v1beta",+ );+ expect(toGoogleAIStudioBaseURL("https://proxy.example.com/google/")).toBe(+ "https://proxy.example.com/google/v1beta",+ );+ });++ it("keeps an existing /v1beta suffix", () => {+ expect(+ toGoogleAIStudioBaseURL(+ "https://generativelanguage.googleapis.com/v1beta",+ ),+ ).toBe("https://generativelanguage.googleapis.com/v1beta");+ });+});++describe("translateGoogleProviderOptions", () => {+ it("returns undefined without thinking options", () => {+ expect(+ translateGoogleProviderOptions({+ providerOptions: undefined,+ model: "gemini-2.5-flash",+ }),+ ).toEqual({ ok: true, value: undefined });+ });++ it("silently strips unknown keys like LangChain's non-strict schema", () => {+ expect(+ translateGoogleProviderOptions({+ providerOptions: { customField: 1, thinkingBudget: 1024 },+ model: "gemini-2.5-flash",+ }),+ ).toEqual({+ ok: true,+ value: {+ thinkingConfig: { thinkingBudget: 1024, includeThoughts: true },+ },+ });+ });++ it("maps thinkingBudget for the gemini-2.5 budget family", () => {+ expect(+ translateGoogleProviderOptions({+ providerOptions: { thinkingBudget: 0 },+ model: "gemini-2.5-flash",+ }),+ ).toEqual({+ ok: true,+ value: { thinkingConfig: { thinkingBudget: 0, includeThoughts: false } },+ });+ });++ it("clamps gemini-2.5-pro budgets below the 128 minimum", () => {+ expect(+ translateGoogleProviderOptions({+ providerOptions: { thinkingBudget: 0 },+ model: "gemini-2.5-pro",+ }),+ ).toEqual({+ ok: true,+ value: {+ thinkingConfig: { thinkingBudget: 128, includeThoughts: false },+ },+ });+ expect(+ translateGoogleProviderOptions({+ providerOptions: { thinkingBudget: 100 },+ model: "gemini-2.5-pro",+ }),+ ).toEqual({+ ok: true,+ value: { thinkingConfig: { thinkingBudget: 128, includeThoughts: true } },+ });+ });++ it("prefers maxReasoningTokens over thinkingBudget like LangChain", () => {+ expect(+ translateGoogleProviderOptions({+ providerOptions: { thinkingBudget: 1024 },+ model: "gemini-2.5-flash",+ maxReasoningTokens: 2048,+ }),+ ).toEqual({+ ok: true,+ value: {+ thinkingConfig: { thinkingBudget: 2048, includeThoughts: true },+ },+ });+ });++ it("maps thinkingLevel for level-family models", () => {+ expect(+ translateGoogleProviderOptions({+ providerOptions: { thinkingLevel: "HIGH" },+ model: "gemini-3-flash",+ }),+ ).toEqual({+ ok: true,+ value: {+ thinkingConfig: { thinkingLevel: "high", includeThoughts: true },+ },+ });+ expect(+ translateGoogleProviderOptions({+ providerOptions: { thinkingLevel: "minimal" },+ model: "gemini-3-flash",+ }),+ ).toEqual({+ ok: true,+ value: {+ thinkingConfig: { thinkingLevel: "minimal", includeThoughts: false },+ },+ });+ });++ it("remaps unsupported levels for gemini-3 pro families", () => {+ expect(+ translateGoogleProviderOptions({+ providerOptions: { thinkingLevel: "medium" },+ model: "gemini-3-pro",+ }),+ ).toEqual({+ ok: true,+ value: {+ thinkingConfig: { thinkingLevel: "high", includeThoughts: true },+ },+ });+ expect(+ translateGoogleProviderOptions({+ providerOptions: { thinkingLevel: "minimal" },+ model: "gemini-3.1-pro",+ }),+ ).toEqual({+ ok: true,+ value: {+ thinkingConfig: { thinkingLevel: "low", includeThoughts: false },+ },+ });+ });++ it("declines representation conversions LangChain does via model tables", () => {+ // level-only on a budget-family model+ expect(+ translateGoogleProviderOptions({+ providerOptions: { thinkingLevel: "high" },+ model: "gemini-2.5-flash",+ }).ok,+ ).toBe(false);+ // budget-only on a level-family model+ expect(+ translateGoogleProviderOptions({+ providerOptions: { thinkingBudget: 1024 },+ model: "gemini-3-flash",+ }).ok,+ ).toBe(false);+ });++ it("declines wrong types so LangChain surfaces the parse error", () => {+ expect(+ translateGoogleProviderOptions({+ providerOptions: { thinkingBudget: "lots" },+ model: "gemini-2.5-flash",+ }).ok,+ ).toBe(false);+ });++ it("merges a nested google object verbatim", () => {+ expect(+ translateGoogleProviderOptions({+ providerOptions: {+ google: { safetySettings: [] },+ thinkingBudget: 512,+ },+ model: "gemini-2.5-flash",+ }),+ ).toEqual({+ ok: true,+ value: {+ safetySettings: [],+ thinkingConfig: { thinkingBudget: 512, includeThoughts: true },+ },+ });+ });+});diff --git a/packages/shared/src/server/llm/ai-sdk/providers/google.ts b/packages/shared/src/server/llm/ai-sdk/providers/google.tsnew file mode 100644index 0000000000..b507d7d1e1--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/providers/google.ts@@ -0,0 +1,173 @@+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`).+ */+export function toGoogleAIStudioBaseURL(+ baseURL: string | null | undefined,+): string | undefined {+ return ensureBaseURLSuffix(baseURL, "/v1beta");+}++export function buildGoogleAIStudioModel(params: {+ modelParams: ModelParams;+ apiKey: string;+ baseURL?: string | null;+ fetch: typeof fetch;+}): LanguageModel {+ const provider = createGoogleGenerativeAI({+ apiKey: params.apiKey,+ baseURL: toGoogleAIStudioBaseURL(params.baseURL),+ 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);+}++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.+ *+ * LangChain then derives a 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.+ */+export function translateGoogleProviderOptions(params: {+ providerOptions: Record<string, unknown> | undefined;+ model: string;+ maxReasoningTokens?: number;+}): TranslatedProviderOptions {+ const { providerOptions, model, maxReasoningTokens } = params;++ const translated: Record<string, unknown> = {};++ const nested = providerOptions?.google;+ if (isPlainObject(nested)) {+ // Nested `google` object is treated as already AI SDK-shaped.+ Object.assign(translated, nested);+ }++ const rawThinkingBudget = providerOptions?.thinkingBudget;+ const rawThinkingLevel = providerOptions?.thinkingLevel;++ if (+ rawThinkingBudget !== undefined &&+ typeof rawThinkingBudget !== "number"+ ) {+ // LangChain's schema parse would throw; decline so it does.+ return { ok: false, unknownKeys: ["thinkingBudget"] };+ }+ if (rawThinkingLevel !== undefined && typeof rawThinkingLevel !== "string") {+ return { ok: false, unknownKeys: ["thinkingLevel"] };+ }++ // LangChain precedence: maxReasoningTokens ?? thinkingBudget.+ const thinkingBudget = maxReasoningTokens ?? rawThinkingBudget;+ const thinkingLevel = rawThinkingLevel?.toLowerCase();++ if (thinkingBudget !== undefined || thinkingLevel !== undefined) {+ const thinkingConfig = buildThinkingConfig({+ model,+ thinkingBudget,+ thinkingLevel,+ });+ if (!thinkingConfig.ok) return thinkingConfig;++ translated.thinkingConfig = {+ ...(typeof translated.thinkingConfig === "object"+ ? translated.thinkingConfig+ : {}),+ ...thinkingConfig.value,+ };+ }++ return {+ ok: true,+ value: Object.keys(translated).length > 0 ? translated : undefined,+ };+}++function buildThinkingConfig(params: {+ model: string;+ thinkingBudget?: number;+ thinkingLevel?: string;+}):+ | { ok: true; value: Record<string, unknown> }+ | { ok: false; unknownKeys: string[] } {+ const { model } = 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.+ 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+ // 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+ // negative budgets pass through to surface the same provider error.+ const includeThoughts = !(+ thinkingBudget === 0 ||+ (model.includes("pro") && thinkingBudget === 128)+ );+ if (+ model.startsWith("gemini-2.5-pro") &&+ thinkingBudget >= 0 &&+ thinkingBudget < 128+ ) {+ thinkingBudget = 128;+ }++ return {+ ok: true,+ value: { thinkingBudget, includeThoughts },+ };+ }++ // Level-family model (gemini-3 and newer).+ if (thinkingLevel === undefined) {+ return { ok: false, unknownKeys: ["thinkingBudget"] };+ }+ if (!GOOGLE_THINKING_LEVELS.has(thinkingLevel)) {+ return { ok: false, unknownKeys: ["thinkingLevel"] };+ }++ const includeThoughts = thinkingLevel !== "minimal";++ // LangChain remaps unsupported levels for the pro families.+ if (model.startsWith("gemini-3-pro")) {+ if (thinkingLevel === "minimal") thinkingLevel = "low";+ else if (thinkingLevel === "medium") thinkingLevel = "high";+ } else if (model.startsWith("gemini-3.1-pro")) {+ if (thinkingLevel === "minimal") thinkingLevel = "low";+ }++ return {+ ok: true,+ value: { thinkingLevel, includeThoughts },+ };+}diff --git a/packages/shared/src/server/llm/ai-sdk/providers/index.ts b/packages/shared/src/server/llm/ai-sdk/providers/index.tsnew file mode 100644index 0000000000..9a7e219dce--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/providers/index.ts@@ -0,0 +1,124 @@+import type { LanguageModel } from "ai";++import type { LLMConnectionConfig } from "../../../../interfaces/customLLMProviderConfigSchemas";+import { LLMAdapter, type ModelParams } from "../../types";+import type { AiSdkEngineDecision } from "../resolveLlmExecutionDecision";+import { buildAnthropicModel } from "./anthropic";+import { buildAzureModel } from "./azure";+import { buildBedrockModel } from "./bedrock";+import { buildGoogleAIStudioModel } from "./google";+import { buildOpenAIModel } from "./openai";+import { buildVertexModel, isClaudeModel } from "./vertex";++const AZURE_OPENAI_API_KEY_HEADER = "api-key";+const ANTHROPIC_API_KEY_HEADER = "x-api-key";+const GOOGLE_API_KEY_HEADER = "X-Goog-Api-Key";+const VERTEX_AI_AUTH_HEADER = "authorization";++/**+ * Factory for the secure LLM fetch (outbound URL validation, redirect+ * handling, proxy support) with a per-adapter log context and the adapter's+ * API-key header registered as sensitive.+ */+export type CreateSecureFetch = (+ logContext: string,+ additionalSensitiveHeaders?: string[],+) => 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.+ */+export async function buildAiSdkModel(params: {+ decision: AiSdkEngineDecision;+ modelParams: ModelParams;+ apiKey: string;+ baseURL?: string | null;+ extraHeaders?: Record<string, string>;+ config?: LLMConnectionConfig | null;+ shouldUseLangfuseAPIKey: boolean;+ createFetch: CreateSecureFetch;+}): Promise<LanguageModel> {+ const {+ decision,+ modelParams,+ apiKey,+ baseURL,+ extraHeaders,+ config,+ shouldUseLangfuseAPIKey,+ createFetch,+ } = params;++ switch (decision.adapter) {+ case LLMAdapter.OpenAI:+ return buildOpenAIModel({+ modelParams,+ apiKey,+ baseURL,+ extraHeaders,+ apiMode: decision.openAIApiMode ?? "chat-completions",+ fetch: createFetch("OpenAI LLM base URL"),+ });++ case LLMAdapter.Azure:+ return buildAzureModel({+ modelParams,+ apiKey,+ baseURL,+ extraHeaders,+ fetch: createFetch("Azure OpenAI LLM base URL", [+ AZURE_OPENAI_API_KEY_HEADER,+ ]),+ });++ case LLMAdapter.Anthropic:+ return buildAnthropicModel({+ modelParams,+ apiKey,+ baseURL,+ extraHeaders,+ fetch: createFetch("Anthropic LLM base URL", [+ ANTHROPIC_API_KEY_HEADER,+ ]),+ });++ case LLMAdapter.Bedrock:+ return buildBedrockModel({+ modelParams,+ apiKey,+ config,+ shouldUseLangfuseAPIKey,+ });++ case LLMAdapter.GoogleAIStudio:+ return buildGoogleAIStudioModel({+ modelParams,+ apiKey,+ baseURL,+ fetch: createFetch("Google AI Studio LLM base URL", [+ GOOGLE_API_KEY_HEADER,+ ]),+ });++ case LLMAdapter.VertexAI:+ return buildVertexModel({+ modelParams,+ apiKey,+ config,+ extraHeaders,+ fetch: createFetch(+ isClaudeModel(modelParams.model)+ ? "Anthropic Vertex AI endpoint"+ : "Vertex AI LLM endpoint",+ [VERTEX_AI_AUTH_HEADER],+ ),+ });++ default: {+ const _exhaustiveCheck: never = decision.adapter;+ throw new Error(`AI SDK adapter is not supported: ${_exhaustiveCheck}`);+ }+ }+}diff --git a/packages/shared/src/server/llm/ai-sdk/providers/openai.test.ts b/packages/shared/src/server/llm/ai-sdk/providers/openai.test.tsindex e668057853..c62ef4ccf1 100644--- a/packages/shared/src/server/llm/ai-sdk/providers/openai.test.ts+++ b/packages/shared/src/server/llm/ai-sdk/providers/openai.test.ts@@ -19,6 +19,7 @@ describe("translateOpenAIProviderOptions", () => {reasoning_effort: "high",service_tier: "flex",parallel_tool_calls: false,+ prompt_cache_key: "eval-project-1",store: true,});@@ -28,6 +29,7 @@ describe("translateOpenAIProviderOptions", () => {reasoningEffort: "high",serviceTier: "flex",parallelToolCalls: false,+ promptCacheKey: "eval-project-1",store: true,},});diff --git a/packages/shared/src/server/llm/ai-sdk/providers/openai.ts b/packages/shared/src/server/llm/ai-sdk/providers/openai.tsindex 284b28e46d..b43386a328 100644--- a/packages/shared/src/server/llm/ai-sdk/providers/openai.ts+++ b/packages/shared/src/server/llm/ai-sdk/providers/openai.ts@@ -3,6 +3,8 @@ import type { LanguageModel } from "ai";import type { ModelParams } from "../../types";import { processOpenAIBaseURL } from "../../utils";+import type { TranslatedProviderOptions } from "./types";+import { isPlainObject } from "./utils";export type OpenAIApiMode = "responses" | "chat-completions";@@ -56,6 +58,7 @@ const OPENAI_PROVIDER_OPTION_KEY_MAP: Record<string, string> = {max_completion_tokens: "maxCompletionTokens",text_verbosity: "textVerbosity",verbosity: "textVerbosity",+ prompt_cache_key: "promptCacheKey",store: "store",user: "user",// camelCase (already AI SDK-shaped)@@ -65,12 +68,9 @@ const OPENAI_PROVIDER_OPTION_KEY_MAP: Record<string, string> = {logitBias: "logitBias",maxCompletionTokens: "maxCompletionTokens",textVerbosity: "textVerbosity",+ promptCacheKey: "promptCacheKey",};-export type TranslatedProviderOptions =- | { ok: true; value: Record<string, unknown> | undefined }- | { ok: false; unknownKeys: string[] };-export function translateOpenAIProviderOptions(providerOptions: Record<string, unknown> | undefined,): TranslatedProviderOptions {@@ -82,7 +82,7 @@ export function translateOpenAIProviderOptions(const unknownKeys: string[] = [];for (const [key, value] of Object.entries(providerOptions)) {- if (key === "openai" && typeof value === "object" && value !== null) {+ if (key === "openai" && isPlainObject(value)) {// Nested `openai` object is treated as already AI SDK-shaped.Object.assign(translated, value);continue;diff --git a/packages/shared/src/server/llm/ai-sdk/providers/types.ts b/packages/shared/src/server/llm/ai-sdk/providers/types.tsnew file mode 100644index 0000000000..12353501c4--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/providers/types.ts@@ -0,0 +1,10 @@+/**+ * 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.+ */+export type TranslatedProviderOptions =+ | { ok: true; value: Record<string, unknown> | undefined }+ | { ok: false; unknownKeys: string[] };diff --git a/packages/shared/src/server/llm/ai-sdk/providers/utils.ts b/packages/shared/src/server/llm/ai-sdk/providers/utils.tsnew file mode 100644index 0000000000..df44a41345--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/providers/utils.ts@@ -0,0 +1,37 @@+/**+ * Trims trailing slashes without regex — connection base URLs are user+ * input, and `/\/+$/`-style patterns are flagged as polynomially+ * backtracking on adversarial strings (CodeQL js/polynomial-redos).+ */+export function trimTrailingSlashes(url: string): string {+ let end = url.length;+ while (end > 0 && url[end - 1] === "/") end--;+ return url.slice(0, end);+}++/**+ * 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+ * the version segment is part of `baseURL`. Keeps an already-suffixed URL+ * unchanged.+ */+export function ensureBaseURLSuffix(+ baseURL: string | null | undefined,+ suffix: string,+): string | undefined {+ if (!baseURL) return undefined;++ const trimmed = trimTrailingSlashes(baseURL);+ return trimmed.endsWith(suffix) ? trimmed : `${trimmed}${suffix}`;+}++/**+ * Guard for the nested per-provider escape-hatch objects (`{ openai: {...} }`+ * etc.): only plain objects are treated as AI SDK-shaped options; arrays and+ * other values fall through to the adapter's regular key handling.+ */+export function isPlainObject(+ value: unknown,+): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/packages/shared/src/server/llm/ai-sdk/providers/vertex.test.ts b/packages/shared/src/server/llm/ai-sdk/providers/vertex.test.tsnew file mode 100644index 0000000000..c4cfefc05d--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/providers/vertex.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from "vitest";++import {+ assertValidAnthropicVertexModelName,+ assertValidVertexLocation,+ isClaudeModel,+} from "./vertex";++describe("isClaudeModel", () => {+ it("detects Claude models case-insensitively", () => {+ expect(isClaudeModel("claude-sonnet-4-5@20250929")).toBe(true);+ expect(isClaudeModel("Claude-Opus-4-1")).toBe(true);+ expect(isClaudeModel("gemini-2.5-flash")).toBe(false);+ });+});++describe("assertValidAnthropicVertexModelName", () => {+ it("accepts single Vertex model ID segments", () => {+ expect(() =>+ assertValidAnthropicVertexModelName("claude-sonnet-4-5@20250929"),+ ).not.toThrow();+ });++ it("rejects names with URL delimiters or traversal", () => {+ expect(() =>+ assertValidAnthropicVertexModelName("claude/../../other"),+ ).toThrow("Invalid Anthropic Vertex AI model name");+ expect(() => assertValidAnthropicVertexModelName("claude..x")).toThrow(+ "Invalid Anthropic Vertex AI model name",+ );+ });+});++describe("assertValidVertexLocation", () => {+ it("accepts region identifiers and undefined", () => {+ expect(() => assertValidVertexLocation("us-east5")).not.toThrow();+ expect(() => assertValidVertexLocation("global")).not.toThrow();+ expect(() => assertValidVertexLocation(undefined)).not.toThrow();+ });++ it("rejects URL-reshaping locations", () => {+ expect(() => assertValidVertexLocation("evil.example.com/")).toThrow(+ "Invalid Vertex AI location",+ );+ expect(() => assertValidVertexLocation("us-east5.attacker")).toThrow(+ "Invalid Vertex AI location",+ );+ });+});diff --git a/packages/shared/src/server/llm/ai-sdk/providers/vertex.ts b/packages/shared/src/server/llm/ai-sdk/providers/vertex.tsnew file mode 100644index 0000000000..ce479ccc37--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/providers/vertex.ts@@ -0,0 +1,127 @@+import { createVertex } from "@ai-sdk/google-vertex";+import { createVertexAnthropic } from "@ai-sdk/google-vertex/anthropic";+import type { LanguageModel } from "ai";+import { GoogleAuth, type GoogleAuthOptions } from "google-auth-library";++import { env } from "../../../../env";+import GCPServiceAccountKeySchema, {+ type LLMConnectionConfig,+ 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",+];++const ANTHROPIC_VERTEX_MODEL_NAME_PATTERN = /^[A-Za-z0-9_.@-]+$/;++// Vertex region identifiers are lowercase alphanumerics plus hyphens+// (e.g. "us-east5", "europe-west1") with the special "global"/"us"/"eu"+// endpoints. Disallowing every URL delimiter keeps an attacker-controlled+// location from reshaping the Vertex host the SDKs build from it.+const VERTEX_LOCATION_PATTERN = /^[a-z0-9-]+$/;++export function isClaudeModel(modelName: string): boolean {+ return modelName.toLowerCase().includes("claude");+}++export function assertValidAnthropicVertexModelName(modelName: string): void {+ if (+ !ANTHROPIC_VERTEX_MODEL_NAME_PATTERN.test(modelName) ||+ modelName.includes("..")+ ) {+ throw new Error(+ "Invalid Anthropic Vertex AI model name. Model names must be a single Vertex model ID segment.",+ );+ }+}++// location flows into the Vertex host the SDKs build from it+// (https://${location}-aiplatform.googleapis.com), so reject anything that+// could reshape that host and exfiltrate the Google OAuth bearer token.+export function assertValidVertexLocation(location: string | undefined): void {+ if (location !== undefined && !VERTEX_LOCATION_PATTERN.test(location)) {+ throw new Error(+ "Invalid Vertex AI location. Locations must be a single Vertex region identifier.",+ );+ }+}++/**+ * 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`.+ *+ * 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.+ */+export async function buildVertexModel(params: {+ modelParams: ModelParams;+ apiKey: string;+ config?: LLMConnectionConfig | null;+ extraHeaders?: Record<string, string>;+ fetch: typeof fetch;+}): Promise<LanguageModel> {+ const { modelParams, apiKey, config, extraHeaders } = params;++ const { location } = config+ ? VertexAIConfigSchema.parse(config)+ : { location: undefined };+ assertValidVertexLocation(location);++ const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);+ const shouldUseDefaultCredentials =+ apiKey === VERTEXAI_USE_DEFAULT_CREDENTIALS && !isLangfuseCloud;++ // Security: with ADC we intentionally ignore user-provided project IDs to+ // prevent privilege escalation via the server's credentials.+ const serviceAccountKey = shouldUseDefaultCredentials+ ? undefined+ : GCPServiceAccountKeySchema.parse(JSON.parse(apiKey));+ const googleAuthOptions: GoogleAuthOptions | undefined = serviceAccountKey+ ? {+ credentials: serviceAccountKey,+ projectId: serviceAccountKey.project_id,+ }+ : undefined;++ // The AI SDK requires an explicit project for URL construction (it does not+ // ask the auth library); resolve it from ADC when no key is configured.+ const project =+ serviceAccountKey?.project_id ??+ (await new GoogleAuth({ scopes: VERTEX_AI_AUTH_SCOPES }).getProjectId());++ // LangChain defaults the location to "global" for both model families.+ const resolvedLocation = location ?? "global";++ if (isClaudeModel(modelParams.model)) {+ assertValidAnthropicVertexModelName(modelParams.model);++ const provider = createVertexAnthropic({+ project,+ location: resolvedLocation,+ googleAuthOptions,+ headers: extraHeaders,+ fetch: params.fetch,+ });++ return provider(modelParams.model);+ }++ // Note: extra headers are intentionally not sent for Gemini — the LangChain+ // engine's Vertex client only injects the OAuth headers.+ const provider = createVertex({+ project,+ location: resolvedLocation,+ googleAuthOptions,+ fetch: params.fetch,+ });++ return provider(modelParams.model);+}diff --git a/packages/shared/src/server/llm/ai-sdk/requestShape.test.ts b/packages/shared/src/server/llm/ai-sdk/requestShape.test.tsnew file mode 100644index 0000000000..1fc0533a21--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/requestShape.test.ts@@ -0,0 +1,445 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import {+ type ChatMessage,+ ChatMessageRole,+ ChatMessageType,+ LLMAdapter,+ type ModelParams,+} from "../types";+import { executeAiSdkCompletion } from "./executeAiSdkCompletion";+import { resolveLlmExecutionDecision } from "./resolveLlmExecutionDecision";++// The Vertex provider exchanges service-account credentials for an OAuth+// token via google-auth-library before issuing the model request; both the+// provider and our vertex builder resolve to the same library copy, so this+// mock covers token generation and the ADC project lookup.+vi.mock("google-auth-library", () => ({+ GoogleAuth: class {+ getClient = async () => ({+ getAccessToken: async () => ({ token: "fake-gcp-token" }),+ });+ getProjectId = async () => "adc-project";+ },+}));++const ALL_ADAPTERS = Object.values(LLMAdapter);++const messages: ChatMessage[] = [+ {+ type: ChatMessageType.System,+ role: ChatMessageRole.System,+ content: "You are terse.",+ },+ { type: ChatMessageType.User, role: ChatMessageRole.User, content: "Hi" },+];++type CapturedRequest = {+ url: string;+ method: string;+ headers: Headers;+ body: Record<string, unknown>;+};++/**+ * Fetch stub that records every outgoing request and answers with a canned+ * provider response, so the assertion target is the exact wire format the AI+ * SDK provider constructs (URL, auth header, JSON body).+ */+function createCaptureFetch(response: unknown) {+ const calls: CapturedRequest[] = [];+ const fetchImpl: typeof fetch = async (input, init) => {+ const request = new Request(input, init);+ calls.push({+ url: request.url,+ method: request.method,+ headers: request.headers,+ body: JSON.parse(await request.text()) as Record<string, unknown>,+ });+ return new Response(JSON.stringify(response), {+ status: 200,+ headers: { "content-type": "application/json" },+ });+ };+ return { calls, fetch: fetchImpl };+}++const OPENAI_CHAT_RESPONSE = {+ id: "chatcmpl-1",+ object: "chat.completion",+ created: 1,+ model: "gpt-4o",+ choices: [+ {+ index: 0,+ message: { role: "assistant", content: "ok" },+ finish_reason: "stop",+ },+ ],+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },+};++const OPENAI_RESPONSES_RESPONSE = {+ id: "resp_1",+ object: "response",+ created_at: 1,+ status: "completed",+ error: null,+ incomplete_details: null,+ model: "gpt-4o",+ output: [+ {+ type: "message",+ id: "msg_1",+ status: "completed",+ role: "assistant",+ content: [{ type: "output_text", text: "ok", annotations: [] }],+ },+ ],+ usage: {+ input_tokens: 1,+ input_tokens_details: { cached_tokens: 0 },+ output_tokens: 1,+ output_tokens_details: { reasoning_tokens: 0 },+ total_tokens: 2,+ },+};++const ANTHROPIC_RESPONSE = {+ id: "msg_1",+ type: "message",+ role: "assistant",+ model: "claude-sonnet-5",+ content: [{ type: "text", text: "ok" }],+ stop_reason: "end_turn",+ stop_sequence: null,+ usage: { input_tokens: 1, output_tokens: 1 },+};++const GOOGLE_RESPONSE = {+ candidates: [+ {+ content: { role: "model", parts: [{ text: "ok" }] },+ finishReason: "STOP",+ },+ ],+ usageMetadata: {+ promptTokenCount: 1,+ candidatesTokenCount: 1,+ totalTokenCount: 2,+ },+};++const BEDROCK_RESPONSE = {+ output: { message: { role: "assistant", content: [{ text: "ok" }] } },+ stopReason: "end_turn",+ usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },+ metrics: { latencyMs: 1 },+};++const FAKE_GCP_SERVICE_ACCOUNT_KEY = JSON.stringify({+ type: "service_account",+ project_id: "sa-project-123",+ private_key_id: "key-id",+ private_key: "-----BEGIN PRIVATE KEY-----\nfake\n-----END PRIVATE KEY-----\n",+ client_email: "[email protected]",+ client_id: "123",+ 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://example.com/cert",+});++async function runCompletion(params: {+ modelParams: ModelParams;+ apiKey: string;+ baseURL?: string | null;+ extraHeaders?: Record<string, string>;+ 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,+ });++ expect(calls).toHaveLength(1);+ return { result, request: calls[0] };+}++afterEach(() => {+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();+});++describe("AI SDK request shapes", () => {+ it("OpenAI chat completions: default URL, bearer auth, translated body params", async () => {+ const { result, request } = await runCompletion({+ modelParams: {+ provider: "openai",+ adapter: LLMAdapter.OpenAI,+ model: "gpt-4o",+ max_tokens: 128,+ temperature: 0.2,+ providerOptions: {+ reasoning_effort: "high",+ prompt_cache_key: "eval-project-1",+ },+ },+ apiKey: "sk-test",+ response: OPENAI_CHAT_RESPONSE,+ });++ expect(result).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");+ expect(request.body.reasoning_effort).toBe("high");+ expect(request.body.prompt_cache_key).toBe("eval-project-1");+ expect(request.body.temperature).toBe(0.2);+ expect(request.body.max_tokens).toBe(128);+ expect(request.body.messages).toEqual([+ { role: "system", content: "You are terse." },+ { role: "user", content: "Hi" },+ ]);+ });++ it("OpenAI responses mode: /v1/responses when useResponsesApi is set", async () => {+ const { request } = await runCompletion({+ modelParams: {+ provider: "openai",+ adapter: LLMAdapter.OpenAI,+ model: "gpt-4o",+ },+ apiKey: "sk-test",+ llmConnectionConfig: { useResponsesApi: true },+ response: OPENAI_RESPONSES_RESPONSE,+ });++ expect(request.url).toBe("https://api.openai.com/v1/responses");+ expect(request.headers.get("authorization")).toBe("Bearer sk-test");+ expect(request.body.model).toBe("gpt-4o");+ });++ it("Azure: LangChain 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,+ },+ apiKey: "azure-key",+ baseURL: "https://my-instance.openai.azure.com/openai/deployments",+ extraHeaders: { "x-custom": "1" },+ response: OPENAI_CHAT_RESPONSE,+ });++ expect(request.url).toBe(+ "https://my-instance.openai.azure.com/openai/deployments/gpt4o-deployment/chat/completions?api-version=2025-02-01-preview",+ );+ expect(request.headers.get("api-key")).toBe("azure-key");+ expect(request.headers.get("x-custom")).toBe("1");+ });++ it("Anthropic: /v1/messages on a custom origin with snake_case thinking body", async () => {+ const { request } = await runCompletion({+ modelParams: {+ provider: "anthropic",+ adapter: LLMAdapter.Anthropic,+ model: "claude-sonnet-5",+ max_tokens: 256,+ providerOptions: { thinking: { type: "enabled", budget_tokens: 1024 } },+ },+ apiKey: "anthropic-key",+ baseURL: "https://anthropic-proxy.example.com",+ response: ANTHROPIC_RESPONSE,+ });++ expect(request.url).toBe("https://anthropic-proxy.example.com/v1/messages");+ 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.+ expect(request.body.max_tokens).toBe(256 + 1024);+ expect(request.body.thinking).toEqual({+ type: "enabled",+ budget_tokens: 1024,+ });+ // The leading system message becomes the top-level system param.+ expect(JSON.stringify(request.body.system)).toContain("You are terse.");+ expect(request.body.messages).toHaveLength(1);+ });++ it("Google AI Studio: /v1beta path on a custom origin with thinkingConfig", async () => {+ const { request } = await runCompletion({+ modelParams: {+ provider: "google-ai-studio",+ adapter: LLMAdapter.GoogleAIStudio,+ model: "gemini-2.5-flash",+ providerOptions: { thinkingBudget: 512 },+ },+ apiKey: "google-key",+ baseURL: "https://google-proxy.example.com",+ response: GOOGLE_RESPONSE,+ });++ expect(request.url).toBe(+ "https://google-proxy.example.com/v1beta/models/gemini-2.5-flash:generateContent",+ );+ expect(request.headers.get("x-goog-api-key")).toBe("google-key");+ const generationConfig = request.body.generationConfig as Record<+ string,+ unknown+ >;+ expect(generationConfig.thinkingConfig).toEqual({+ thinkingBudget: 512,+ includeThoughts: true,+ });+ });++ it("Vertex Gemini: regional host, SA-key project, OAuth bearer, maxReasoningTokens", async () => {+ const { request } = await runCompletion({+ modelParams: {+ provider: "vertex",+ adapter: LLMAdapter.VertexAI,+ model: "gemini-2.5-flash",+ maxReasoningTokens: 2048,+ },+ apiKey: FAKE_GCP_SERVICE_ACCOUNT_KEY,+ llmConnectionConfig: { location: "us-east5" },+ response: GOOGLE_RESPONSE,+ });++ // Known engine difference: the AI SDK targets the v1beta1 Vertex API+ // (LangChain used v1); both serve generateContent with the same contract.+ 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",+ );+ expect(request.headers.get("authorization")).toBe("Bearer fake-gcp-token");+ const generationConfig = request.body.generationConfig as Record<+ string,+ unknown+ >;+ expect(generationConfig.thinkingConfig).toEqual({+ thinkingBudget: 2048,+ includeThoughts: true,+ });+ });++ it("Vertex Claude: anthropic publisher rawPredict URL with vertex anthropic_version", async () => {+ const { request } = await runCompletion({+ modelParams: {+ provider: "vertex",+ adapter: LLMAdapter.VertexAI,+ model: "claude-sonnet-4-5@20250929",+ max_tokens: 128,+ },+ apiKey: FAKE_GCP_SERVICE_ACCOUNT_KEY,+ llmConnectionConfig: { location: "us-east5" },+ response: ANTHROPIC_RESPONSE,+ });++ expect(decodeURIComponent(request.url)).toBe(+ "https://us-east5-aiplatform.googleapis.com/v1/projects/sa-project-123/locations/us-east5/publishers/anthropic/models/claude-sonnet-4-5@20250929:rawPredict",+ );+ expect(request.headers.get("authorization")).toBe("Bearer fake-gcp-token");+ // Vertex mode: the version moves into the body and the model into the URL.+ expect(request.body.anthropic_version).toBeTruthy();+ expect(request.body.model).toBeUndefined();+ expect(request.body.max_tokens).toBe(128);+ });++ // The Bedrock builder deliberately uses no custom fetch (VPC endpoints),+ // so capture at the global fetch the AI SDK falls back to.+ async function runBedrockCompletion() {+ const modelParams: ModelParams = {+ provider: "bedrock",+ adapter: LLMAdapter.Bedrock,+ model: "anthropic.claude-3-5-sonnet-20241022-v2:0",+ max_tokens: 64,+ providerOptions: { top_k: 10 },+ };+ 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",+ }),+ llmConnectionConfig,+ timeoutMs: 10_000,+ createFetch: () => fetch,+ decision,+ });++ expect(result).toBe("ok");+ expect(calls).toHaveLength(1);+ return calls[0];+ }++ it("Bedrock: converse URL from validated region, SigV4 auth, verbatim additional fields", async () => {+ const request = await runBedrockCompletion();++ expect(decodeURIComponent(request.url)).toBe(+ "https://bedrock-runtime.us-east-1.amazonaws.com/model/anthropic.claude-3-5-sonnet-20241022-v2:0/converse",+ );+ expect(request.headers.get("authorization")).toMatch(/^AWS4-HMAC-SHA256/);+ expect(request.body.additionalModelRequestFields).toEqual({ top_k: 10 });+ expect(request.body.inferenceConfig).toMatchObject({ maxTokens: 64 });+ });++ it("Bedrock: tenant credentials suppress server-level env auth fallbacks", async () => {+ // A self-hosted operator may set these for their own purposes; tenant+ // connections must never authenticate with them. Unsuppressed, the+ // provider's AWS_BEARER_TOKEN_BEDROCK fallback wins over the tenant's+ // access keys entirely (requests would run under the SERVER identity).+ vi.stubEnv("AWS_BEARER_TOKEN_BEDROCK", "server-bearer-token");+ vi.stubEnv("AWS_SESSION_TOKEN", "server-session-token");++ const request = await runBedrockCompletion();++ // SigV4 with the tenant keys — not `Bearer server-bearer-token`.+ expect(request.headers.get("authorization")).toMatch(/^AWS4-HMAC-SHA256/);+ expect(request.headers.get("authorization")).toContain("AKIA123");+ // No merged server session token (would surface as this SigV4 header).+ expect(request.headers.get("x-amz-security-token")).toBeNull();+ });+});diff --git a/packages/shared/src/server/llm/ai-sdk/resolveLlmExecutionDecision.test.ts b/packages/shared/src/server/llm/ai-sdk/resolveLlmExecutionDecision.test.tsnew file mode 100644index 0000000000..ae19c13e88--- /dev/null+++ b/packages/shared/src/server/llm/ai-sdk/resolveLlmExecutionDecision.test.ts@@ -0,0 +1,219 @@+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.tsindex c4d6046484..2cf0e965b6 100644--- a/packages/shared/src/server/llm/ai-sdk/resolveLlmExecutionDecision.ts+++ b/packages/shared/src/server/llm/ai-sdk/resolveLlmExecutionDecision.ts@@ -1,65 +1,211 @@import { getCurrentSpan } from "../../instrumentation";-import { OpenAIConfigSchema } from "../../../interfaces/customLLMProviderConfigSchemas";+import {+ BedrockConfigSchema,+ OpenAIConfigSchema,+ VertexAIConfigSchema,+} from "../../../interfaces/customLLMProviderConfigSchemas";import type { LLMConnectionConfig } from "../../../interfaces/customLLMProviderConfigSchemas";-import { LLMAdapter } from "../types";+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 { logger } from "../../logger";+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 =- | {- engine: "ai-sdk";- aiSdkAdapter: "openai";- openAIApiMode: OpenAIApiMode;- translatedProviderOptions?: Record<string, unknown>;- }+ | 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` 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.+ * `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: {- adapter: LLMAdapter;- providerOptions?: Record<string, unknown>;+ modelParams: ModelParams;llmConnectionConfig?: LLMConnectionConfig | null;+ baseURL?: string | null;+ shouldUseLangfuseAPIKey?: boolean;enabledAdapters: readonly string[];}): LlmExecutionDecision {- const { adapter, providerOptions, llmConnectionConfig, enabledAdapters } =- params;+ const {+ modelParams,+ llmConnectionConfig,+ baseURL,+ shouldUseLangfuseAPIKey,+ enabledAdapters,+ } = params;+ const { adapter, model, providerOptions } = modelParams;- if (adapter !== LLMAdapter.OpenAI || !enabledAdapters.includes("openai")) {- return { engine: "langchain-js" };+ if (!enabledAdapters.includes(adapter)) {+ return LANGCHAIN_DECISION;}- const translated = translateOpenAIProviderOptions(providerOptions);- if (!translated.ok) {- logger.warn(- `Cannot translate provider options: ${translated.unknownKeys.join(",")}`,+ 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(",")}`,);- return { engine: "langchain-js" };- }+ switch (adapter) {+ case LLMAdapter.OpenAI: {+ const translated = translateOpenAIProviderOptions(providerOptions);+ if (!translated.ok) return declineForOptions(translated);- const openAIConfig = OpenAIConfigSchema.parse(llmConnectionConfig ?? {});-- return {- engine: "ai-sdk",- aiSdkAdapter: "openai",- // Chat Completions stays the default: flipping to the Responses API would- // break OpenAI-compatible proxies configured via custom baseURL.- openAIApiMode: openAIConfig.useResponsesApi- ? "responses"- : "chat-completions",- translatedProviderOptions: translated.value,- };+ 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;+ }+ }}/**@@ -76,7 +222,9 @@ export function recordLlmExecutionDecision(span.setAttribute("langfuse.llm.execution_engine", decision.engine);if (decision.engine === "ai-sdk") {- span.setAttribute("langfuse.llm.ai_sdk.adapter", decision.aiSdkAdapter);- span.setAttribute("langfuse.llm.openai.api_mode", decision.openAIApiMode);+ 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/telemetryIntegration.test.ts b/packages/shared/src/server/llm/ai-sdk/telemetryIntegration.test.tsindex 39444b32ea..0fd316a76b 100644--- a/packages/shared/src/server/llm/ai-sdk/telemetryIntegration.test.ts+++ b/packages/shared/src/server/llm/ai-sdk/telemetryIntegration.test.ts@@ -22,6 +22,7 @@ import {type TraceSinkParams,} from "../types";import { executeAiSdkCompletion } from "./executeAiSdkCompletion";+import type { AiSdkEngineDecision } from "./resolveLlmExecutionDecision";const publishToOtelIngestionQueue = vi.fn().mockResolvedValue(undefined);@@ -56,6 +57,13 @@ 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@@ -116,8 +124,8 @@ describe("AI SDK telemetry integration", () => {streaming: false,apiKey: "sk-test",timeoutMs: 10_000,- fetch: globalThis.fetch,- apiMode: "chat-completions",+ createFetch: () => globalThis.fetch,+ decision,traceSinkParams,});@@ -216,8 +224,8 @@ describe("AI SDK telemetry integration", () => {streaming: false,apiKey: "sk-test",timeoutMs: 10_000,- fetch: globalThis.fetch,- apiMode: "chat-completions",+ createFetch: () => globalThis.fetch,+ decision,traceSinkParams: {targetProjectId: "project-1",traceId: experimentTraceId,diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.tsindex a55f4955b3..ebeb3d4268 100644--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts@@ -43,6 +43,7 @@ import {LLMToolDefinition,ModelParams,OpenAIModel,+ PROVIDERS_WITH_REQUIRED_USER_MESSAGE,ToolCallResponse,ToolCallResponseSchema,TraceSinkParams,@@ -60,6 +61,11 @@ import {} from "./utils";import { logger } from "../logger";import { executeAiSdkCompletion } from "./ai-sdk/executeAiSdkCompletion";+import {+ assertValidAnthropicVertexModelName,+ assertValidVertexLocation,+ isClaudeModel,+} from "./ai-sdk/providers/vertex";import {recordLlmExecutionDecision,resolveLlmExecutionDecision,@@ -103,13 +109,6 @@ function adapterSupportsReasoning(adapter: LLMAdapter): boolean {return ADAPTERS_WITH_REASONING_SUPPORT.has(adapter);}-const PROVIDERS_WITH_REQUIRED_USER_MESSAGE = [- LLMAdapter.VertexAI,- LLMAdapter.GoogleAIStudio,- LLMAdapter.Anthropic,- LLMAdapter.Bedrock,-];-const ANTHROPIC_ALWAYS_ADAPTIVE_THINKING_MODELS = ["claude-fable-5","claude-mythos-5",@@ -129,14 +128,6 @@ const ANTHROPIC_SAMPLING_PARAM_NORMALIZATION_MODELS = ["claude-haiku-4-5",] as const;-const ANTHROPIC_VERTEX_MODEL_NAME_PATTERN = /^[A-Za-z0-9_.@-]+$/;--// Vertex region identifiers are lowercase alphanumerics plus hyphens-// (e.g. "us-east5", "europe-west1") with the special "global"/"us"/"eu"-// endpoints. Disallowing every URL delimiter keeps an attacker-controlled-// location from reshaping the Vertex host the SDKs build from it.-const VERTEX_LOCATION_PATTERN = /^[a-z0-9-]+$/;-function isAnthropicAlwaysAdaptiveThinkingModel(modelName: string): boolean {return ANTHROPIC_ALWAYS_ADAPTIVE_THINKING_MODELS.some((model) =>modelName.includes(model),@@ -196,21 +187,6 @@ function normalizeAnthropicSamplingParams(}}-function isClaudeModel(modelName: string): boolean {- return modelName.toLowerCase().includes("claude");-}--function assertValidAnthropicVertexModelName(modelName: string) {- if (- !ANTHROPIC_VERTEX_MODEL_NAME_PATTERN.test(modelName) ||- modelName.includes("..")- ) {- throw new Error(- "Invalid Anthropic Vertex AI model name. Model names must be a single Vertex model ID segment.",- );- }-}-function shouldNormalizeContentBlocks(modelParams: ModelParams): boolean {return (adapterSupportsReasoning(modelParams.adapter) ||@@ -379,9 +355,10 @@ export async function fetchLLMCompletion(// internal tracing is captured natively and routed through the regular OTel// ingestion pipeline instead of the LangChain callback handler.const executionDecision = resolveLlmExecutionDecision({- adapter: modelParams.adapter,- providerOptions: modelParams.providerOptions,+ modelParams,llmConnectionConfig: config,+ baseURL,+ shouldUseLangfuseAPIKey,enabledAdapters: env.LANGFUSE_LLM_COMPLETION_AI_SDK_ADAPTERS,});recordLlmExecutionDecision(executionDecision);@@ -398,11 +375,12 @@ export async function fetchLLMCompletion(apiKey,baseURL,extraHeaders,+ llmConnectionConfig: config,+ shouldUseLangfuseAPIKey,maxRetries,timeoutMs,- fetch: secureLlmFetch("OpenAI LLM base URL"),- apiMode: executionDecision.openAIApiMode,- translatedProviderOptions: executionDecision.translatedProviderOptions,+ createFetch: secureLlmFetch,+ decision: executionDecision,traceSinkParams,});}@@ -597,11 +575,7 @@ export async function fetchLLMCompletion(// 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.- if (location !== undefined && !VERTEX_LOCATION_PATTERN.test(location)) {- throw new Error(- "Invalid Vertex AI location. Locations must be a single Vertex region identifier.",- );- }+ assertValidVertexLocation(location);// Handle both explicit credentials and default provider chain (ADC)// Only allow default provider chain in self-hosted or internal AI featuresdiff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.tsindex 246a17563e..77b295493a 100644--- a/packages/shared/src/server/llm/types.ts+++ b/packages/shared/src/server/llm/types.ts@@ -245,6 +245,15 @@ 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.+export const PROVIDERS_WITH_REQUIRED_USER_MESSAGE: readonly LLMAdapter[] = [+ LLMAdapter.VertexAI,+ LLMAdapter.GoogleAIStudio,+ LLMAdapter.Anthropic,+ LLMAdapter.Bedrock,+];+export const TextPromptContentSchema = z.string().min(1, "Enter a prompt");export const PromptContentSchema = z.union([diff --git a/packages/shared/vitest.config.ts b/packages/shared/vitest.config.tsindex 6fd890bdb5..cf12b8fcbf 100644--- a/packages/shared/vitest.config.ts+++ b/packages/shared/vitest.config.ts@@ -5,5 +5,13 @@ export default defineConfig({dir: "./src",include: ["**/*.test.ts"],pool: "forks",+ server: {+ deps: {+ // Process the Vertex provider through vite so vi.mock can replace its+ // google-auth-library import (externalized deps bypass the mock+ // registry) — required by the AI SDK request-shape tests.+ inline: ["@ai-sdk/google-vertex"],+ },+ },},});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 023e49acac..bafb7b390a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -152,6 +152,21 @@ importers:packages/shared:dependencies:+ '@ai-sdk/amazon-bedrock':+ specifier: ^5.0.8+ version: 5.0.8([email protected])+ '@ai-sdk/anthropic':+ specifier: ^4.0.5+ version: 4.0.5([email protected])+ '@ai-sdk/azure':+ specifier: ^4.0.5+ version: 4.0.5([email protected])+ '@ai-sdk/google':+ specifier: ^4.0.6+ version: 4.0.6([email protected])+ '@ai-sdk/google-vertex':+ specifier: ^5.0.8+ version: 5.0.8([email protected])'@ai-sdk/openai':specifier: ^4.0.0version: 4.0.4([email protected])@@ -173,6 +188,9 @@ importers:'@aws-sdk/client-sesv2':specifier: ^3.1013.0version: 3.1045.0+ '@aws-sdk/credential-providers':+ specifier: ^3.1056.0+ version: 3.1056.0'@aws-sdk/lib-storage':specifier: ^3.1013.0version: 3.1024.0(@aws-sdk/[email protected])@@ -1212,6 +1230,12 @@ packages:peerDependencies:zod: 4.3.6+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-E4TozODmCKGS5VlCBnCR1Iffd0e0hkcbjpjzlqvxQPTJlw0hm9sJ3vltAIRU3wTKVTn0BfZiKzYylu2CAEyP6g==}+ engines: {node: '>=22'}+ peerDependencies:+ zod: 4.3.6+'@ai-sdk/[email protected]':resolution: {integrity: sha512-7HPgFv91YFFYyZapM/Vy3tRbBq/hL44omh0vz/WikiU7fJFxdOjCeg6Nb089lxM7+qBe7blZsoSRJ7gfAkEo1w==}engines: {node: '>=18'}@@ -1224,6 +1248,24 @@ packages:peerDependencies:zod: 4.3.6+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-JyJYKWGYz8vfoQ1pCm48a9zgX3Gvb2/6iGHb+8pEelpqnOiUq3aDHVq+nYMf9VepqcjCuH0JSOwBrKiPg/PD9w==}+ engines: {node: '>=22'}+ peerDependencies:+ zod: 4.3.6++ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-/zVpvIbQEtFIWSb49bbWJ6xB3eQsJGibStCruTc/3SRfeQw8sco/1sCLsmCTK/+W0aeyv+iswCcPjBJBAXbNUw==}+ engines: {node: '>=22'}+ peerDependencies:+ zod: 4.3.6++ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-OCfJ8GEcDMbPESx1ijKDE1QKLst08dWsbR/gDbrzJV+NtAi1UkcrkiP7OclmWGuHEBMdZ7rHbM+muCXy+9mFsg==}+ engines: {node: '>=22'}+ peerDependencies:+ zod: 4.3.6+'@ai-sdk/[email protected]':resolution: {integrity: sha512-2Ue0jetdlGQNv8zzYkZHgQQUfoeBp+Vu97L5UAF+HHJ/EggvY2lvO19Mq0G4YEPvc2Xt77QdDz5gGySxDSMpMQ==}engines: {node: '>=18'}@@ -1236,18 +1278,36 @@ packages:peerDependencies:zod: 4.3.6+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-WRu4srlMC5l2DygS1q6Tb8Dqgcwwrdu9Lb/u+0LaLMJZK/zzfhO3bGpGpNxiIsv+k9GYQxvAc3o9NpPcgX9I5g==}+ engines: {node: '>=22'}+ peerDependencies:+ zod: 4.3.6+'@ai-sdk/[email protected]':resolution: {integrity: sha512-Lhw1742RXc+4pRIvqVXa0jdl5+qdpmw8lj0lm6OchUg9rVGHzymlaxe7CDiYX5U2af4jbjKeTY22LDi3bIycgQ==}engines: {node: '>=18'}peerDependencies:zod: 4.3.6+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-YJnWlHVqG6Lq3NY5Z0hs1+8+P4GFTBLPkmnuFIGdsYi19qB7C36IpK2JOzdkyE47waVJuu6tq/d0rFyHZzY2MQ==}+ engines: {node: '>=22'}+ peerDependencies:+ zod: 4.3.6+'@ai-sdk/[email protected]':resolution: {integrity: sha512-9y9GuGcZ9/+pMIHfpOCJgZVp+AZMv6TkjX2NVT17SQZvTF2N8LXuCXyoUPyi1PxIxzxl0n463LxxaB2O6olC+Q==}engines: {node: '>=18'}peerDependencies:zod: 4.3.6+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-+mDaUS0q460pVs3oW2/Ps/vj4M2EZnYr1v6ng8TmzxnZPrYBuK7PGQIfckqFdWIdUI/gG8BXcaf8vukLKyGU6Q==}+ engines: {node: '>=22'}+ peerDependencies:+ zod: 4.3.6+'@ai-sdk/[email protected]':resolution: {integrity: sha512-EFC0rpo1wfe4HIz5KZCE72edP2J7fOeR7wPXzjCDljaTRB1wectKDIKRLowpU4F0mbcJ+XScAsoYNPK/Z20aVQ==}engines: {node: '>=18'}@@ -1260,6 +1320,12 @@ packages:peerDependencies:zod: 4.3.6+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-a9cYQNAKAbkMTt6bHAvDuLv3klwtJT9m0A6x7s8EZlf1ebcxadg/1CONaYh1GA80ZRA9UQHJUS2wHoOphkQQkg==}+ engines: {node: '>=22'}+ peerDependencies:+ zod: 4.3.6+'@ai-sdk/[email protected]':resolution: {integrity: sha512-ubkAJ+xODouwtmN1tYlvTPphH1hPOBfZaEQe8U7skGvFAnIRs9PPpsq57bC2+Ky/MB4yzhd6YOsxTAx9sGpazw==}engines: {node: '>=18'}@@ -1272,6 +1338,12 @@ packages:peerDependencies:zod: 4.3.6+ '@ai-sdk/[email protected]':+ resolution: {integrity: sha512-El0JOXXGcHFe6+owJ1UV0VgB9XtdivP8vcZni+rUIt6lt+cBHCnUdddaA6LE2avJGJ5AD0uXSY+uAvRL2tSvgw==}+ engines: {node: '>=22'}+ peerDependencies:+ zod: 4.3.6+'@ai-sdk/[email protected]':resolution: {integrity: sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg==}engines: {node: '>=18'}@@ -4942,6 +5014,10 @@ packages:resolution: {integrity: sha512-Kt8phUg45M15EjhYAbZ+fFikYneijLu9Liugz8ZsYz2i8j0hzGv27LWKpEHYRfvj+LyCOSijpcR/2i8RouV+cA==}engines: {node: '>=18.0.0'}+ '@smithy/[email protected]':+ resolution: {integrity: sha512-sEvpvkBVoMxjoek35XyJFn2ZD3EJ1RpiZrT47WaZodxzAIWS44zkdvbqGE/ZlugtjiQp62cffYZ9ldyRkjAGnA==}+ engines: {node: '>=18.0.0'}+'@smithy/[email protected]':resolution: {integrity: sha512-tHhdiWZfG1ZIh2YcRfPJmY2gHcBmqbAzqm3ER4TIDFYsSEqTD5tICT7cgQ/kI8LRakxp12myOYyK68XPn7MnHw==}engines: {node: '>=18.0.0'}@@ -4950,6 +5026,10 @@ packages:resolution: {integrity: sha512-FE3bZdEl62ojmy8x4FHqxq2+BuOHlcxiH5vaZ6aqHJr3AIZzwF5jfx8dEiU/X0a8RboyNDjmXjlbr8AdEyLgiA==}engines: {node: '>=18.0.0'}+ '@smithy/[email protected]':+ resolution: {integrity: sha512-rasV+96Obv6tEhWPKWaehEhR+MEd2/lE/rdOYcmSMh6tJiQdoZg4v21p37Y1A7DMZOFgFDUX/3eNl/J3+MJDdA==}+ engines: {node: '>=18.0.0'}+'@smithy/[email protected]':resolution: {integrity: sha512-XUSuMxlTxV5pp4VpqZf6Sa3vT/Q75FVkLSpSSE3KkWBvAQWeuWt1msTv8fJfgA4/jcJhrbrbMzN1AC/hvPmm5A==}engines: {node: '>=18.0.0'}@@ -5062,6 +5142,10 @@ packages:resolution: {integrity: sha512-P+otAxbV4CqBybp7EkcJCrig63yE2E7PuNVOmilVMRcx/O+QDzGULTrKsq4DV13gSfak9ObPrWaHl/9bL5YcWw==}engines: {node: '>=18.0.0'}+ '@smithy/[email protected]':+ resolution: {integrity: sha512-x3L0XSACF6UYzKpa9biqiRMgvH5+wnFFew9Tm/grFYqgaupPwx/+ojDPpPJM8dZON3S9tjz5U+PQYsCBd1Mw5Q==}+ engines: {node: '>=18.0.0'}+'@smithy/[email protected]':resolution: {integrity: sha512-I5tCWs/ndLrJrbvlnsN1cOt8PVAbQEqg0nNeQqebD5ynQcbhgch9uA7KmpX9vfq/vEudq0iVYAOxt+4aBkUlWA==}engines: {node: '>=18.0.0'}@@ -5130,6 +5214,10 @@ packages:resolution: {integrity: sha512-75MeYpjdWRe8M5E3AW0O4Cx3UadweS+cwdXjwYGBW5h/gxxnbeZ877sLPX/ZJA9GVTlL/qG0dXP29JWFCD1Ayw==}engines: {node: '>=18.0.0'}+ '@smithy/[email protected]':+ resolution: {integrity: sha512-ZS7Y5X8mU9qRSsqwOeGKw86WWtPsRxa396kX2HyhYwADRqFHJ0cb3p2uFk6QnFF3BluUUBHTZJpPA9QuEl0tlg==}+ engines: {node: '>=18.0.0'}+'@smithy/[email protected]':resolution: {integrity: sha512-2zqq5o/oizvMaFUlNiTyZ7dbgYv1a893aGut2uaxtbzTx/VYYnRxWzDHuD/ftgcw94ffenua+ZNLrbqwUYE+Bg==}engines: {node: '>=18.0.0'}@@ -11912,6 +12000,17 @@ snapshots:aws4fetch: 1.0.20zod: 4.3.6+ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/anthropic': 4.0.5([email protected])+ '@ai-sdk/openai': 4.0.5([email protected])+ '@ai-sdk/provider': 4.0.1+ '@ai-sdk/provider-utils': 5.0.3([email protected])+ '@smithy/eventstream-codec': 4.4.5+ '@smithy/util-utf8': 4.4.5+ aws4fetch: 1.0.20+ zod: 4.3.6+'@ai-sdk/[email protected]([email protected])':dependencies:'@ai-sdk/provider': 2.0.3@@ -11924,6 +12023,26 @@ snapshots:'@ai-sdk/provider-utils': 4.0.27([email protected])zod: 4.3.6+ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 4.0.1+ '@ai-sdk/provider-utils': 5.0.3([email protected])+ zod: 4.3.6++ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/deepseek': 3.0.3([email protected])+ '@ai-sdk/openai': 4.0.5([email protected])+ '@ai-sdk/provider': 4.0.1+ '@ai-sdk/provider-utils': 5.0.3([email protected])+ zod: 4.3.6++ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 4.0.1+ '@ai-sdk/provider-utils': 5.0.3([email protected])+ zod: 4.3.6+'@ai-sdk/[email protected]([email protected])':dependencies:'@ai-sdk/provider': 2.0.3@@ -11938,12 +12057,30 @@ snapshots:'@vercel/oidc': 3.2.0zod: 4.3.6+ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/anthropic': 4.0.5([email protected])+ '@ai-sdk/google': 4.0.6([email protected])+ '@ai-sdk/openai-compatible': 3.0.3([email protected])+ '@ai-sdk/provider': 4.0.1+ '@ai-sdk/provider-utils': 5.0.3([email protected])+ google-auth-library: 10.6.2+ zod: 4.3.6+ transitivePeerDependencies:+ - supports-color+'@ai-sdk/[email protected]([email protected])':dependencies:'@ai-sdk/provider': 2.0.3'@ai-sdk/provider-utils': 4.0.27([email protected])zod: 4.3.6+ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 4.0.1+ '@ai-sdk/provider-utils': 5.0.3([email protected])+ zod: 4.3.6+'@ai-sdk/[email protected]([email protected])':dependencies:'@ai-sdk/provider': 2.0.0@@ -11951,6 +12088,12 @@ snapshots:pkce-challenge: 5.0.1zod: 4.3.6+ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 4.0.1+ '@ai-sdk/provider-utils': 5.0.3([email protected])+ zod: 4.3.6+'@ai-sdk/[email protected]([email protected])':dependencies:'@ai-sdk/provider': 2.0.3@@ -11963,6 +12106,12 @@ snapshots:'@ai-sdk/provider-utils': 5.0.2([email protected])zod: 4.3.6+ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 4.0.1+ '@ai-sdk/provider-utils': 5.0.3([email protected])+ zod: 4.3.6+'@ai-sdk/[email protected]([email protected])':dependencies:'@ai-sdk/provider': 3.0.10@@ -11978,6 +12127,14 @@ snapshots:eventsource-parser: 3.0.8zod: 4.3.6+ '@ai-sdk/[email protected]([email protected])':+ dependencies:+ '@ai-sdk/provider': 4.0.1+ '@standard-schema/spec': 1.1.0+ '@workflow/serde': 4.1.0+ eventsource-parser: 3.0.8+ zod: 4.3.6+'@ai-sdk/[email protected]':dependencies:json-schema: 0.4.0@@ -12127,7 +12284,7 @@ snapshots:'@aws-sdk/util-user-agent-browser': 3.972.11'@aws-sdk/util-user-agent-node': 3.973.25'@smithy/config-resolver': 4.5.0- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0'@smithy/eventstream-serde-browser': 4.2.12'@smithy/eventstream-serde-config-resolver': 4.3.12'@smithy/eventstream-serde-node': 4.2.12@@ -12143,7 +12300,7 @@ snapshots:'@smithy/node-http-handler': 4.5.1'@smithy/protocol-http': 5.4.0'@smithy/smithy-client': 4.13.0- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1'@smithy/url-parser': 4.3.0'@smithy/util-base64': 4.3.2'@smithy/util-body-length-browser': 4.2.2@@ -12178,7 +12335,7 @@ snapshots:'@aws-sdk/util-user-agent-browser': 3.972.11'@aws-sdk/util-user-agent-node': 3.973.25'@smithy/config-resolver': 4.5.0- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0'@smithy/eventstream-serde-browser': 4.2.12'@smithy/eventstream-serde-config-resolver': 4.3.12'@smithy/eventstream-serde-node': 4.2.12@@ -12194,7 +12351,7 @@ snapshots:'@smithy/node-http-handler': 4.5.1'@smithy/protocol-http': 5.4.0'@smithy/smithy-client': 4.13.0- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1'@smithy/url-parser': 4.3.0'@smithy/util-base64': 4.3.2'@smithy/util-body-length-browser': 4.2.2@@ -12263,10 +12420,10 @@ snapshots:'@aws-sdk/core': 3.974.15'@aws-sdk/credential-provider-node': 3.972.47'@aws-sdk/types': 3.973.9- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0'@smithy/fetch-http-handler': 5.4.5'@smithy/node-http-handler': 4.7.5- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -12285,7 +12442,7 @@ snapshots:'@aws-sdk/util-user-agent-browser': 3.972.11'@aws-sdk/util-user-agent-node': 3.973.25'@smithy/config-resolver': 4.5.0- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0'@smithy/fetch-http-handler': 5.4.5'@smithy/hash-node': 4.3.0'@smithy/invalid-dependency': 4.3.0@@ -12298,7 +12455,7 @@ snapshots:'@smithy/node-http-handler': 4.5.1'@smithy/protocol-http': 5.4.0'@smithy/smithy-client': 4.13.0- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1'@smithy/url-parser': 4.3.0'@smithy/util-base64': 4.3.2'@smithy/util-body-length-browser': 4.2.2@@ -12446,41 +12603,41 @@ snapshots:'@aws-sdk/types': 3.973.9'@aws-sdk/xml-builder': 3.972.26'@aws/lambda-invoke-store': 0.2.4- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0'@smithy/signature-v4': 5.4.5- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1bowser: 2.14.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/nested-clients': 3.997.13'@aws-sdk/types': 3.973.9- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/core': 3.974.15'@aws-sdk/types': 3.973.9- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/core': 3.974.15'@aws-sdk/types': 3.973.9- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0'@smithy/fetch-http-handler': 5.4.5'@smithy/node-http-handler': 4.7.5- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -12494,9 +12651,9 @@ snapshots:'@aws-sdk/credential-provider-web-identity': 3.972.45'@aws-sdk/nested-clients': 3.997.13'@aws-sdk/types': 3.973.9- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0'@smithy/credential-provider-imds': 4.3.6- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -12504,8 +12661,8 @@ snapshots:'@aws-sdk/core': 3.974.15'@aws-sdk/nested-clients': 3.997.13'@aws-sdk/types': 3.973.9- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -12517,17 +12674,17 @@ snapshots:'@aws-sdk/credential-provider-sso': 3.972.45'@aws-sdk/credential-provider-web-identity': 3.972.45'@aws-sdk/types': 3.973.9- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0'@smithy/credential-provider-imds': 4.3.6- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/core': 3.974.15'@aws-sdk/types': 3.973.9- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -12536,8 +12693,8 @@ snapshots:'@aws-sdk/nested-clients': 3.997.13'@aws-sdk/token-providers': 3.1056.0'@aws-sdk/types': 3.973.9- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -12545,8 +12702,8 @@ snapshots:'@aws-sdk/core': 3.974.15'@aws-sdk/nested-clients': 3.997.13'@aws-sdk/types': 3.973.9- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -12564,16 +12721,16 @@ snapshots:'@aws-sdk/credential-provider-web-identity': 3.972.45'@aws-sdk/nested-clients': 3.997.13'@aws-sdk/types': 3.973.9- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0'@smithy/credential-provider-imds': 4.3.6- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.973.9'@smithy/eventstream-codec': 4.2.12- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected](@aws-sdk/[email protected])':@@ -12594,7 +12751,7 @@ snapshots:'@aws-sdk/util-arn-parser': 3.972.3'@smithy/node-config-provider': 4.4.0'@smithy/protocol-http': 5.4.0- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1'@smithy/util-config-provider': 4.2.2tslib: 2.8.1@@ -12602,14 +12759,14 @@ snapshots:dependencies:'@aws-sdk/types': 3.973.9'@smithy/protocol-http': 5.4.0- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.973.9'@smithy/protocol-http': 5.4.0- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -12623,7 +12780,7 @@ snapshots:'@smithy/is-array-buffer': 4.2.2'@smithy/node-config-provider': 4.4.0'@smithy/protocol-http': 5.4.0- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1'@smithy/util-middleware': 4.3.0'@smithy/util-stream': 4.6.0'@smithy/util-utf8': 4.2.2@@ -12632,28 +12789,28 @@ snapshots:'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.973.9- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.973.9- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.973.9- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.973.9'@aws/lambda-invoke-store': 0.2.4- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -12661,12 +12818,12 @@ snapshots:'@aws-sdk/core': 3.974.15'@aws-sdk/types': 3.973.9'@aws-sdk/util-arn-parser': 3.972.3- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0'@smithy/node-config-provider': 4.4.0'@smithy/protocol-http': 5.4.0'@smithy/signature-v4': 5.4.5'@smithy/smithy-client': 4.13.0- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1'@smithy/util-config-provider': 4.2.2'@smithy/util-middleware': 4.3.0'@smithy/util-stream': 4.6.0@@ -12676,7 +12833,7 @@ snapshots:'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.973.9- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -12684,8 +12841,8 @@ snapshots:'@aws-sdk/core': 3.974.15'@aws-sdk/types': 3.973.9'@aws-sdk/util-endpoints': 3.996.9- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -12697,7 +12854,7 @@ snapshots:'@smithy/fetch-http-handler': 5.4.5'@smithy/protocol-http': 5.4.0'@smithy/signature-v4': 5.4.5- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1'@smithy/util-base64': 4.3.2'@smithy/util-hex-encoding': 4.2.2'@smithy/util-utf8': 4.2.2@@ -12710,17 +12867,17 @@ snapshots:'@aws-sdk/core': 3.974.15'@aws-sdk/signature-v4-multi-region': 3.996.30'@aws-sdk/types': 3.973.9- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0'@smithy/fetch-http-handler': 5.4.5'@smithy/node-http-handler': 4.7.5- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.973.9- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -12738,7 +12895,7 @@ snapshots:dependencies:'@aws-sdk/types': 3.973.9'@smithy/signature-v4': 5.4.5- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -12748,7 +12905,7 @@ snapshots:'@aws-sdk/types': 3.973.9'@smithy/property-provider': 4.3.0'@smithy/shared-ini-file-loader': 4.5.0- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -12756,13 +12913,13 @@ snapshots:'@aws-sdk/core': 3.974.15'@aws-sdk/nested-clients': 3.997.13'@aws-sdk/types': 3.973.9- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -12772,15 +12929,15 @@ snapshots:'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.973.9- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.973.9'@smithy/querystring-builder': 4.2.12- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':@@ -12790,7 +12947,7 @@ snapshots:'@aws-sdk/[email protected]':dependencies:'@aws-sdk/types': 3.973.9- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1bowser: 2.14.1tslib: 2.8.1@@ -12798,13 +12955,13 @@ snapshots:dependencies:'@aws-sdk/middleware-user-agent': 3.972.39'@aws-sdk/types': 3.973.9- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@aws-sdk/[email protected]':dependencies:- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1fast-xml-parser: 5.7.3tslib: 2.8.1@@ -16257,78 +16414,88 @@ snapshots:'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':dependencies:'@aws-crypto/crc32': 5.2.0- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1+ tslib: 2.8.1++ '@smithy/[email protected]':+ dependencies:+ '@smithy/types': 4.15.1tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@smithy/[email protected]':dependencies:'@aws-crypto/crc32': 5.2.0- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1'@smithy/util-hex-encoding': 4.2.2tslib: 2.8.1+ '@smithy/[email protected]':+ dependencies:+ '@smithy/core': 3.29.0+ tslib: 2.8.1+'@smithy/[email protected]':dependencies:'@smithy/eventstream-serde-universal': 4.2.12- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@smithy/[email protected]':dependencies:'@smithy/eventstream-serde-universal': 4.2.12- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@smithy/[email protected]':dependencies:'@smithy/eventstream-codec': 4.2.12- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@smithy/[email protected]':dependencies:'@smithy/chunked-blob-reader': 5.2.2'@smithy/chunked-blob-reader-native': 4.2.3- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1'@smithy/util-utf8': 4.2.2tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':@@ -16341,17 +16508,17 @@ snapshots:'@smithy/[email protected]':dependencies:- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1'@smithy/util-utf8': 4.2.2tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0'@smithy/is-array-buffer': 4.2.2'@smithy/node-config-provider': 4.4.0'@smithy/protocol-http': 5.4.0- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1'@smithy/util-config-provider': 4.2.2'@smithy/util-middleware': 4.3.0'@smithy/util-utf8': 4.2.2@@ -16360,32 +16527,32 @@ snapshots:'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':@@ -16397,50 +16564,54 @@ snapshots:'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1'@smithy/util-uri-escape': 4.2.2tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5- '@smithy/types': 4.14.2+ '@smithy/core': 3.29.0+ '@smithy/types': 4.15.1tslib: 2.8.1'@smithy/[email protected]':dependencies:tslib: 2.8.1+ '@smithy/[email protected]':+ dependencies:+ tslib: 2.8.1+'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':@@ -16473,17 +16644,17 @@ snapshots:'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':@@ -16492,17 +16663,17 @@ snapshots:'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':dependencies:- '@smithy/core': 3.24.5+ '@smithy/core': 3.29.0tslib: 2.8.1'@smithy/[email protected]':@@ -16519,9 +16690,14 @@ snapshots:'@smithy/util-buffer-from': 4.2.2tslib: 2.8.1+ '@smithy/[email protected]':+ dependencies:+ '@smithy/core': 3.29.0+ tslib: 2.8.1+'@smithy/[email protected]':dependencies:- '@smithy/types': 4.14.2+ '@smithy/types': 4.15.1tslib: 2.8.1'@stablelib/[email protected]': {}