🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(llm): allow custom OpenAI provider options (#15085)
Hassieb Pakzadb445e2ff6414
diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 5c247d08ca..a215a858af 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -100,6 +100,7 @@"@ai-sdk/google": "^4.0.6","@ai-sdk/google-vertex": "^5.0.8","@ai-sdk/openai": "^4.0.0",+ "@ai-sdk/openai-compatible": "^3.0.3","@aws-sdk/client-cloudwatch": "catalog:","@aws-sdk/client-lambda": "catalog:","@aws-sdk/client-s3": "catalog:",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.tsindex 6501fd96ae..2423d2cbf8 100644--- a/packages/shared/src/server/llm/ai-sdk/providers/azure.test.ts+++ b/packages/shared/src/server/llm/ai-sdk/providers/azure.test.ts@@ -25,15 +25,49 @@ describe("translateAzureBaseURL", () => {});});+ it("strips deployment-specific base URLs", () => {+ expect(+ translateAzureBaseURL(+ "https://my-instance.openai.azure.com/openai/deployments/gpt4o-deployment",+ ),+ ).toEqual({+ ok: true,+ value: "https://my-instance.openai.azure.com/openai",+ });+ });++ it("strips full chat completion base URLs", () => {+ expect(+ translateAzureBaseURL(+ "https://my-instance.openai.azure.com/openai/deployments/gpt4o-deployment/chat/completions?api-version=2025-02-01-preview",+ ),+ ).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", () => {+ it("passes through base URLs without the /deployments suffix", () => {expect(- translateAzureBaseURL("https://my-proxy.example.com/openai").ok,- ).toBe(false);+ translateAzureBaseURL("https://my-proxy.example.com/openai"),+ ).toEqual({+ ok: true,+ value: "https://my-proxy.example.com/openai",+ });+ });++ it("does not strip non-deployments path segments containing deployments", () => {+ expect(+ translateAzureBaseURL("https://my-proxy.example.com/deployments-proxy"),+ ).toEqual({+ ok: true,+ value: "https://my-proxy.example.com/deployments-proxy",+ });});});diff --git a/packages/shared/src/server/llm/ai-sdk/providers/azure.ts b/packages/shared/src/server/llm/ai-sdk/providers/azure.tsindex 660dda3166..ebdba123fc 100644--- a/packages/shared/src/server/llm/ai-sdk/providers/azure.ts+++ b/packages/shared/src/server/llm/ai-sdk/providers/azure.ts@@ -11,13 +11,19 @@ export type AzureBaseURLTranslation =| { ok: false; reason: string };/**- * Langfuse stores the Azure base path as- * `https://{instance}.openai.azure.com/openai/deployments`, with the- * deployment and chat-completions path appended at request time. The AI SDK's- * `useDeploymentBasedUrls` mode appends `/deployments/{deployment}{path}` to- * its `baseURL`, so the stored URL maps by stripping the trailing- * `/deployments` segment. Any other shape has no AI SDK equivalent and is- * rejected rather than silently changing the request URL.+ * Langfuse historically passed Azure base paths directly to LangChain as+ * `azureOpenAIBasePath`. Existing connections therefore contain several valid+ * shapes:+ *+ * - `https://{instance}.openai.azure.com/openai`+ * - `https://{instance}.openai.azure.com/openai/deployments`+ * - `https://{instance}.openai.azure.com/openai/deployments/{deployment}`+ * - a proxy-specific prefix that is not an Azure resource URL+ *+ * The AI SDK's deployment-based mode appends+ * `/deployments/{deployment}{path}` to its `baseURL`, so any persisted URL that+ * already contains `/deployments` is normalized back to its parent prefix.+ * Unknown custom prefixes are passed through for proxy compatibility.*/export function translateAzureBaseURL(baseURL: string | null | undefined,@@ -27,14 +33,21 @@ export function translateAzureBaseURL(}const trimmed = trimTrailingSlashes(baseURL);- if (!trimmed.endsWith("/deployments")) {+ const [pathWithoutQuery] = trimmed.split(/[?#]/, 1);+ const pathSegments = pathWithoutQuery.split("/");+ const deploymentsIndex = pathSegments.findIndex(+ (segment) => segment === "deployments",+ );+ if (deploymentsIndex >= 0) {return {- ok: false,- reason: "Azure base URL does not end with /deployments",+ ok: true,+ value: trimTrailingSlashes(+ pathSegments.slice(0, deploymentsIndex).join("/"),+ ),};}- return { ok: true, value: trimmed.slice(0, -"/deployments".length) };+ return { ok: true, value: trimmed };}export function buildAzureModel(params: {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..6b1e9f3f25 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@@ -1,6 +1,9 @@import { describe, expect, it } from "vitest";-import { translateOpenAIProviderOptions } from "./openai";+import {+ isOpenAICompatibleEndpoint,+ translateOpenAIProviderOptions,+} from "./openai";describe("translateOpenAIProviderOptions", () => {it("returns undefined for empty input", () => {@@ -69,4 +72,45 @@ describe("translateOpenAIProviderOptions", () => {unknownKeys: ["response_format", "some_custom_param"],});});++ it("preserves compatible-provider wire keys while passing through unknown keys", () => {+ const result = translateOpenAIProviderOptions(+ {+ reasoning_effort: "high",+ service_tier: "flex",+ parallel_tool_calls: false,+ logit_bias: { "42": 1 },+ thinkingBudget: 1024,+ thinkingLevel: "high",+ },+ { passthroughUnknown: true, target: "openai-compatible" },+ );++ expect(result).toEqual({+ ok: true,+ value: {+ reasoningEffort: "high",+ service_tier: "flex",+ parallel_tool_calls: false,+ logit_bias: { "42": 1 },+ thinkingBudget: 1024,+ thinkingLevel: "high",+ },+ });+ });+});++describe("isOpenAICompatibleEndpoint", () => {+ it("recognizes custom OpenAI-compatible endpoints", () => {+ expect(isOpenAICompatibleEndpoint(undefined)).toBe(false);+ expect(isOpenAICompatibleEndpoint(null)).toBe(false);+ expect(isOpenAICompatibleEndpoint("https://api.openai.com/v1")).toBe(false);+ expect(+ isOpenAICompatibleEndpoint("https://openai-compatible.example.com/v1"),+ ).toBe(true);+ });++ it("does not enable passthrough mode for malformed URLs", () => {+ expect(isOpenAICompatibleEndpoint("localhost:8080")).toBe(false);+ });});diff --git a/packages/shared/src/server/llm/ai-sdk/providers/openai.ts b/packages/shared/src/server/llm/ai-sdk/providers/openai.tsindex c4031be26c..649fe49143 100644--- a/packages/shared/src/server/llm/ai-sdk/providers/openai.ts+++ b/packages/shared/src/server/llm/ai-sdk/providers/openai.ts@@ -1,4 +1,5 @@import { createOpenAI } from "@ai-sdk/openai";+import { createOpenAICompatible } from "@ai-sdk/openai-compatible";import type { LanguageModel } from "ai";import { processOpenAIBaseURL } from "../../utils";@@ -22,6 +23,22 @@ export function buildOpenAIModel(params: {modelName: modelId,});+ if (+ apiMode === "chat-completions" &&+ isOpenAICompatibleEndpoint(processedBaseURL)+ ) {+ const provider = createOpenAICompatible({+ name: "openai",+ apiKey,+ baseURL: processedBaseURL,+ headers: extraHeaders,+ fetch: params.fetch,+ supportsStructuredOutputs: true,+ });++ return provider.languageModel(modelId);+ }+const provider = createOpenAI({apiKey,baseURL: processedBaseURL ?? undefined,@@ -37,15 +54,34 @@ export function buildOpenAIModel(params: {: provider.chat(modelId);}+export function isOpenAICompatibleEndpoint(+ baseURL: string | null | undefined,+): baseURL is string {+ if (!baseURL) return false;++ try {+ const url = new URL(baseURL.replace("{model}", "model"));+ if (!["http:", "https:"].includes(url.protocol) || !url.hostname) {+ return false;+ }++ const hostname = url.hostname;+ return hostname !== "api.openai.com";+ } catch {+ return false;+ }+}+/*** Translation of Langfuse `modelParams.providerOptions` to AI SDK OpenAI* provider options.** Persisted provider options contain snake_case OpenAI request-body fields.* The AI SDK instead accepts a typed, camelCase whitelist under- * `providerOptions.openai` and silently drops unknown keys. Silent dropping is- * unacceptable: the compatibility boundary rejects any key it cannot- * translate.+ * `providerOptions.openai` and may silently drop unknown keys. Silent dropping+ * is unacceptable for first-party OpenAI, so the compatibility boundary rejects+ * unknown keys there. OpenAI-compatible endpoints can have provider-specific+ * option surfaces, so callers may opt into best-effort unknown-key passthrough.*/const OPENAI_PROVIDER_OPTION_KEY_MAP: Record<string, string> = {// snake_case persisted OpenAI request-body fields@@ -67,26 +103,63 @@ const OPENAI_PROVIDER_OPTION_KEY_MAP: Record<string, string> = {textVerbosity: "textVerbosity",};+const OPENAI_COMPATIBLE_PROVIDER_OPTION_KEY_MAP: Record<string, string> = {+ // Keep request-body fields in wire shape for the compatible provider. It+ // spreads unknown options directly into the body instead of using OpenAI's+ // stricter camelCase option schema.+ service_tier: "service_tier",+ parallel_tool_calls: "parallel_tool_calls",+ logit_bias: "logit_bias",+ max_completion_tokens: "max_completion_tokens",+ store: "store",+ user: "user",+ serviceTier: "service_tier",+ parallelToolCalls: "parallel_tool_calls",+ logitBias: "logit_bias",+ maxCompletionTokens: "max_completion_tokens",+ // These two are special compatible-provider options. Keeping them camelCase+ // lets the provider emit `reasoning_effort` and `verbosity` in the body.+ reasoning_effort: "reasoningEffort",+ reasoningEffort: "reasoningEffort",+ text_verbosity: "textVerbosity",+ verbosity: "textVerbosity",+ textVerbosity: "textVerbosity",+};+export function translateOpenAIProviderOptions(providerOptions: Record<string, unknown> | undefined,+ options?: {+ passthroughUnknown?: boolean;+ target?: "openai" | "openai-compatible";+ },): TranslatedProviderOptions {if (!providerOptions || Object.keys(providerOptions).length === 0) {return { ok: true, value: undefined };}+ const keyMap =+ options?.target === "openai-compatible"+ ? OPENAI_COMPATIBLE_PROVIDER_OPTION_KEY_MAP+ : OPENAI_PROVIDER_OPTION_KEY_MAP;const translated: Record<string, unknown> = {};const unknownKeys: string[] = [];for (const [key, value] of Object.entries(providerOptions)) {if (key === "openai" && isPlainObject(value)) {- // Nested `openai` object is treated as already AI SDK-shaped.- Object.assign(translated, value);+ for (const [nestedKey, nestedValue] of Object.entries(value)) {+ const mappedKey = keyMap[nestedKey] ?? nestedKey;+ translated[mappedKey] = nestedValue;+ }continue;}- const mappedKey = OPENAI_PROVIDER_OPTION_KEY_MAP[key];+ const mappedKey = keyMap[key];if (mappedKey === undefined) {- unknownKeys.push(key);+ if (options?.passthroughUnknown) {+ translated[key] = value;+ } else {+ unknownKeys.push(key);+ }continue;}diff --git a/packages/shared/src/server/llm/ai-sdk/requestShape.test.ts b/packages/shared/src/server/llm/ai-sdk/requestShape.test.tsindex ed6fdf2930..8ef6b0c28d 100644--- a/packages/shared/src/server/llm/ai-sdk/requestShape.test.ts+++ b/packages/shared/src/server/llm/ai-sdk/requestShape.test.ts@@ -8,7 +8,11 @@ import {LLMAdapter,type ModelParams,} from "../types";-import { generateLLMText, mapLegacyLLMCompletionParams } from "../llmText";+import {+ createLLMOutput,+ generateLLMText,+ mapLegacyLLMCompletionParams,+} from "../llmText";// Request-shape coverage exercises the real provider packages while replacing// the separately tested secure transport with a capture fetch.@@ -160,6 +164,7 @@ async function runCompletion(params: {baseURL?: string | null;extraHeaders?: Record<string, string>;llmConnectionConfig?: Record<string, string | boolean>;+ output?: ReturnType<typeof createLLMOutput>;response: unknown;}) {const { calls, fetch } = createCaptureFetch(params.response);@@ -178,6 +183,7 @@ async function runCompletion(params: {},}),timeout: 10_000,+ output: params.output,});expect(calls).toHaveLength(1);@@ -234,6 +240,88 @@ describe("AI SDK request shapes", () => {expect(request.body.model).toBe("gpt-4o");});+ it("OpenAI-compatible chat completions: preserves custom provider options on the wire", async () => {+ const { result, request } = await runCompletion({+ modelParams: {+ provider: "openai",+ adapter: LLMAdapter.OpenAI,+ model: "custom-reasoning-model",+ max_tokens: 64,+ providerOptions: {+ reasoning_effort: "high",+ service_tier: "flex",+ parallel_tool_calls: false,+ logit_bias: { "42": 1 },+ thinkingBudget: 1024,+ thinkingLevel: "high",+ },+ },+ apiKey: "custom-key",+ baseURL: "https://openai-compatible.example.com/v1",+ response: OPENAI_CHAT_RESPONSE,+ });++ expect(result.text).toBe("ok");+ expect(request.url).toBe(+ "https://openai-compatible.example.com/v1/chat/completions",+ );+ expect(request.headers.get("authorization")).toBe("Bearer custom-key");+ expect(request.body.model).toBe("custom-reasoning-model");+ expect(request.body.max_tokens).toBe(64);+ expect(request.body.reasoning_effort).toBe("high");+ expect(request.body.service_tier).toBe("flex");+ expect(request.body.parallel_tool_calls).toBe(false);+ expect(request.body.logit_bias).toEqual({ "42": 1 });+ expect(request.body.serviceTier).toBeUndefined();+ expect(request.body.parallelToolCalls).toBeUndefined();+ expect(request.body.logitBias).toBeUndefined();+ expect(request.body.thinkingBudget).toBe(1024);+ expect(request.body.thinkingLevel).toBe("high");+ });++ it("OpenAI-compatible chat completions: preserves JSON schema response_format", async () => {+ const { result, request } = await runCompletion({+ modelParams: {+ provider: "openai",+ adapter: LLMAdapter.OpenAI,+ model: "custom-schema-model",+ },+ apiKey: "custom-key",+ baseURL: "https://openai-compatible.example.com/v1",+ output: createLLMOutput({+ type: "object",+ properties: { answer: { type: "string" } },+ required: ["answer"],+ additionalProperties: false,+ }),+ response: {+ ...OPENAI_CHAT_RESPONSE,+ choices: [+ {+ index: 0,+ message: { role: "assistant", content: '{"answer":"ok"}' },+ finish_reason: "stop",+ },+ ],+ },+ });++ expect(result.output).toEqual({ answer: "ok" });+ expect(request.body.response_format).toMatchObject({+ type: "json_schema",+ json_schema: {+ strict: true,+ name: "response",+ schema: {+ type: "object",+ properties: { answer: { type: "string" } },+ required: ["answer"],+ additionalProperties: false,+ },+ },+ });+ });+it("Azure: stored deployment URL with pinned api-version and api-key header", async () => {const { request } = await runCompletion({modelParams: {@@ -258,6 +346,26 @@ describe("AI SDK request shapes", () => {expect(request.body.max_tokens).toBe(64);});+ it("Azure: deployment-specific stored URL is normalized before request construction", 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/gpt4o-deployment",+ 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");+ });+it("OpenAI chat completions: gpt-5.4 mini keeps non-reasoning request params", async () => {const { request } = await runCompletion({modelParams: {diff --git a/packages/shared/src/server/llm/llmText.test.ts b/packages/shared/src/server/llm/llmText.test.tsindex d9dd5147ce..2ae60c91f6 100644--- a/packages/shared/src/server/llm/llmText.test.ts+++ b/packages/shared/src/server/llm/llmText.test.ts@@ -416,6 +416,87 @@ describe("legacy compatibility boundary", () => {});});+ it("passes unknown OpenAI provider options through for OpenAI-compatible endpoints", () => {+ const mapped = mapLegacyLLMCompletionParams({+ messages: legacyMessages,+ modelParams: {+ provider: "openai",+ adapter: LLMAdapter.OpenAI,+ model: "openai-compatible-reasoning-model",+ providerOptions: {+ reasoning_effort: "high",+ service_tier: "flex",+ parallel_tool_calls: false,+ thinkingBudget: 1024,+ thinkingLevel: "high",+ },+ },+ connection: {+ ...encryptedConnection,+ baseURL: "https://openai-compatible.example.com/v1",+ },+ });++ expect(mapped.providerOptions).toEqual({+ openai: {+ reasoningEffort: "high",+ service_tier: "flex",+ parallel_tool_calls: false,+ thinkingBudget: 1024,+ thinkingLevel: "high",+ },+ });+ });++ it("keeps strict OpenAI option handling for Responses API custom base URLs", () => {+ expect(() =>+ mapLegacyLLMCompletionParams({+ messages: legacyMessages,+ modelParams: {+ provider: "openai",+ adapter: LLMAdapter.OpenAI,+ model: "gpt-4o",+ providerOptions: { thinkingBudget: 1024 },+ },+ connection: {+ ...encryptedConnection,+ baseURL: "https://openai-proxy.example.com/v1",+ config: { useResponsesApi: true },+ },+ }),+ ).toThrow(+ expect.objectContaining<Partial<LLMCompletionError>>({+ name: "LLMCompletionError",+ responseStatusCode: 400,+ isRetryable: false,+ }),+ );+ });++ it("keeps rejecting unknown OpenAI provider options for first-party OpenAI", () => {+ expect(() =>+ mapLegacyLLMCompletionParams({+ messages: legacyMessages,+ modelParams: {+ provider: "openai",+ adapter: LLMAdapter.OpenAI,+ model: "gpt-4o",+ providerOptions: { thinkingBudget: 1024 },+ },+ connection: {+ ...encryptedConnection,+ baseURL: "https://api.openai.com/v1",+ },+ }),+ ).toThrow(+ expect.objectContaining<Partial<LLMCompletionError>>({+ name: "LLMCompletionError",+ responseStatusCode: 400,+ isRetryable: false,+ }),+ );+ });+it("rejects options that cannot be translated instead of falling back", () => {expect(() =>mapLegacyLLMCompletionParams({@@ -441,10 +522,7 @@ describe("legacy compatibility boundary", () => {await expect(generateLLMText({model: { adapter: LLMAdapter.Azure, id: "deployment" },- connection: {- ...encryptedConnection,- baseURL: "https://example.com/openai",- },+ connection: encryptedConnection,messages: [...messages],}),).rejects.toMatchObject({diff --git a/packages/shared/src/server/llm/llmText.ts b/packages/shared/src/server/llm/llmText.tsindex f02741328f..65d81b2a08 100644--- a/packages/shared/src/server/llm/llmText.ts+++ b/packages/shared/src/server/llm/llmText.ts@@ -37,7 +37,10 @@ import { buildAiSdkModel } from "./ai-sdk/providers";import { translateAnthropicProviderOptions } from "./ai-sdk/providers/anthropic";import { translateBedrockProviderOptions } from "./ai-sdk/providers/bedrock";import { translateGoogleProviderOptions } from "./ai-sdk/providers/google";-import { translateOpenAIProviderOptions } from "./ai-sdk/providers/openai";+import {+ isOpenAICompatibleEndpoint,+ translateOpenAIProviderOptions,+} from "./ai-sdk/providers/openai";import type {LLMCredentialSource,TranslatedProviderOptions,@@ -520,7 +523,10 @@ export function mapLegacyLLMCompletionParams(params: {credentialSource?: LLMCredentialSource;}): LegacyLLMTextOptions {const { modelParams } = params;- const providerOptions = translateLegacyProviderOptions(modelParams);+ const providerOptions = translateLegacyProviderOptions({+ modelParams,+ connection: params.connection,+ });return {model: { adapter: modelParams.adapter, id: modelParams.model },@@ -536,16 +542,24 @@ export function mapLegacyLLMCompletionParams(params: {};}-function translateLegacyProviderOptions(- modelParams: ModelParams,-): ProviderOptions | undefined {+function translateLegacyProviderOptions(params: {+ modelParams: ModelParams;+ connection: LLMConnection;+}): ProviderOptions | undefined {+ const { modelParams, connection } = params;let namespace: string;let translated: TranslatedProviderOptions;switch (modelParams.adapter) {case LLMAdapter.OpenAI: {namespace = "openai";- translated = translateOpenAIProviderOptions(modelParams.providerOptions);+ const useOpenAICompatibleChat =+ connection.config?.useResponsesApi !== true &&+ isOpenAICompatibleEndpoint(connection.baseURL);+ translated = translateOpenAIProviderOptions(modelParams.providerOptions, {+ passthroughUnknown: useOpenAICompatibleChat,+ target: useOpenAICompatibleChat ? "openai-compatible" : "openai",+ });if (translated.ok &&isOpenAINonReasoningChatModel(modelParams.model) &&diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6f100440d1..40f4617973 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -197,6 +197,9 @@ importers:'@ai-sdk/openai':specifier: ^4.0.0version: 4.0.5([email protected])+ '@ai-sdk/openai-compatible':+ specifier: ^3.0.3+ version: 3.0.3([email protected])'@aws-sdk/client-cloudwatch':specifier: 'catalog:'version: 3.1056.0