Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🔨 chore(model-runtime): support azure openai router runtime (#13823)

YuTengjing697ac3bf6e09
diff --git a/locales/en-US/modelProvider.json b/locales/en-US/modelProvider.json
index 5fc12f4bcf1..6d36e24fd1a 100644
--- a/locales/en-US/modelProvider.json
+++ b/locales/en-US/modelProvider.json
@@ -3,8 +3,8 @@
"azure.azureApiVersion.fetch": "Fetch List",
"azure.azureApiVersion.title": "Azure API Version",
"azure.empty": "Please enter a model ID to add the first model",
- "azure.endpoint.desc": "When checking resources from the Azure portal, you can find this value in the 'Keys and Endpoints' section",
- "azure.endpoint.placeholder": "https://docs-test-001.openai.azure.com",
+ "azure.endpoint.desc": "When checking resources from the Azure portal, you can find this value in the 'Keys and Endpoints' section. Azure OpenAI endpoints from the Responses API path are also supported.",
+ "azure.endpoint.placeholder": "https://your-resource.cognitiveservices.azure.com/openai/responses",
"azure.endpoint.title": "Azure API Address",
"azure.modelListPlaceholder": "Select or add the OpenAI model you deployed",
"azure.title": "Azure OpenAI",
diff --git a/locales/zh-CN/modelProvider.json b/locales/zh-CN/modelProvider.json
index 724ac72978a..abe5d7d1032 100644
--- a/locales/zh-CN/modelProvider.json
+++ b/locales/zh-CN/modelProvider.json
@@ -3,8 +3,8 @@
"azure.azureApiVersion.fetch": "获取列表",
"azure.azureApiVersion.title": "Azure API Version",
"azure.empty": "请输入模型 ID 添加第一个模型",
- "azure.endpoint.desc": "从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值",
- "azure.endpoint.placeholder": "https://docs-test-001.openai.azure.com",
+ "azure.endpoint.desc": "从 Azure 门户检查资源时,可在“密钥和终结点”部分中找到此值。也支持 Azure OpenAI Responses API 路径形式的终结点。",
+ "azure.endpoint.placeholder": "https://your-resource.cognitiveservices.azure.com/openai/responses",
"azure.endpoint.title": "Azure API 地址",
"azure.modelListPlaceholder": "请选择或添加你部署的 OpenAI 模型",
"azure.title": "Azure OpenAI",
diff --git a/packages/model-bank/src/aiModels/azure.ts b/packages/model-bank/src/aiModels/azure.ts
index 373967107ff..52ca281c3ac 100644
--- a/packages/model-bank/src/aiModels/azure.ts
+++ b/packages/model-bank/src/aiModels/azure.ts
@@ -1,6 +1,232 @@
import type { AIChatModelCard, AIImageModelCard } from '../types/aiModel';
const azureChatModels: AIChatModelCard[] = [
+ {
+ abilities: {
+ functionCall: true,
+ reasoning: true,
+ search: true,
+ structuredOutput: true,
+ vision: true,
+ },
+ config: {
+ deploymentName: 'gpt-5.4',
+ },
+ contextWindowTokens: 1_050_000,
+ description:
+ 'GPT-5.4 is the frontier model for complex professional work with highest reasoning capability.',
+ displayName: 'GPT-5.4',
+ enabled: true,
+ id: 'gpt-5.4',
+ maxOutput: 128_000,
+ pricing: {
+ units: [
+ {
+ name: 'textInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 2.5, upTo: 272_000 },
+ { rate: 5, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
+ {
+ name: 'textInput_cacheRead',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 0.25, upTo: 272_000 },
+ { rate: 0.5, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
+ {
+ name: 'textOutput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 15, upTo: 272_000 },
+ { rate: 22.5, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
+ ],
+ },
+ releasedAt: '2026-03-05',
+ settings: {
+ extendParams: ['gpt5_2ReasoningEffort', 'textVerbosity'],
+ searchImpl: 'params',
+ },
+ type: 'chat',
+ },
+ {
+ abilities: {
+ functionCall: true,
+ reasoning: true,
+ search: true,
+ vision: true,
+ },
+ config: {
+ deploymentName: 'gpt-5.4-pro',
+ },
+ contextWindowTokens: 1_050_000,
+ description:
+ 'GPT-5.4 Pro uses more compute to think harder and provide consistently better answers, available in the Responses API only.',
+ displayName: 'GPT-5.4 Pro',
+ id: 'gpt-5.4-pro',
+ maxOutput: 128_000,
+ pricing: {
+ units: [
+ {
+ name: 'textInput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 30, upTo: 272_000 },
+ { rate: 60, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
+ {
+ name: 'textOutput',
+ strategy: 'tiered',
+ tiers: [
+ { rate: 180, upTo: 272_000 },
+ { rate: 270, upTo: 'infinity' },
+ ],
+ unit: 'millionTokens',
+ },
+ ],
+ },
+ releasedAt: '2026-03-05',
+ settings: {
+ extendParams: ['gpt5_2ProReasoningEffort', 'textVerbosity'],
+ searchImpl: 'params',
+ },
+ type: 'chat',
+ },
+ {
+ abilities: {
+ functionCall: true,
+ reasoning: true,
+ search: true,
+ structuredOutput: true,
+ vision: true,
+ },
+ config: {
+ deploymentName: 'gpt-5.4-mini',
+ },
+ contextWindowTokens: 400_000,
+ description:
+ "GPT-5.4 mini is OpenAI's strongest mini model for coding, computer use, and subagents.",
+ displayName: 'GPT-5.4 mini',
+ enabled: true,
+ id: 'gpt-5.4-mini',
+ maxOutput: 128_000,
+ pricing: {
+ units: [
+ { name: 'textInput', rate: 0.75, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textInput_cacheRead', rate: 0.075, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 4.5, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+ },
+ releasedAt: '2026-03-18',
+ settings: {
+ extendParams: ['gpt5_2ReasoningEffort', 'textVerbosity'],
+ searchImpl: 'params',
+ },
+ type: 'chat',
+ },
+ {
+ abilities: {
+ functionCall: true,
+ reasoning: true,
+ search: true,
+ structuredOutput: true,
+ vision: true,
+ },
+ config: {
+ deploymentName: 'gpt-5.4-nano',
+ },
+ contextWindowTokens: 400_000,
+ description:
+ "GPT-5.4 nano is OpenAI's cheapest GPT-5.4-class model for simple high-volume tasks.",
+ displayName: 'GPT-5.4 nano',
+ enabled: true,
+ id: 'gpt-5.4-nano',
+ maxOutput: 128_000,
+ pricing: {
+ units: [
+ { name: 'textInput', rate: 0.2, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textInput_cacheRead', rate: 0.02, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 1.25, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+ },
+ releasedAt: '2026-03-18',
+ settings: {
+ extendParams: ['gpt5_2ReasoningEffort', 'textVerbosity'],
+ searchImpl: 'params',
+ },
+ type: 'chat',
+ },
+ {
+ abilities: {
+ functionCall: true,
+ reasoning: true,
+ search: true,
+ structuredOutput: true,
+ vision: true,
+ },
+ config: {
+ deploymentName: 'gpt-5.2',
+ },
+ contextWindowTokens: 400_000,
+ description:
+ 'GPT-5.2 is a flagship model for coding and agentic workflows with stronger reasoning and long-context performance.',
+ displayName: 'GPT-5.2',
+ id: 'gpt-5.2',
+ maxOutput: 128_000,
+ pricing: {
+ units: [
+ { name: 'textInput', rate: 1.75, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textInput_cacheRead', rate: 0.175, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 14, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+ },
+ releasedAt: '2025-12-11',
+ settings: {
+ extendParams: ['gpt5_2ReasoningEffort', 'textVerbosity'],
+ searchImpl: 'params',
+ },
+ type: 'chat',
+ },
+ {
+ abilities: {
+ functionCall: true,
+ reasoning: true,
+ search: true,
+ vision: true,
+ },
+ config: {
+ deploymentName: 'gpt-5.1',
+ },
+ contextWindowTokens: 400_000,
+ description:
+ 'GPT-5.1 is a flagship model optimized for coding and agent tasks with configurable reasoning effort and longer context.',
+ displayName: 'GPT-5.1',
+ id: 'gpt-5.1',
+ maxOutput: 128_000,
+ pricing: {
+ units: [
+ { name: 'textInput', rate: 1.25, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textInput_cacheRead', rate: 0.125, strategy: 'fixed', unit: 'millionTokens' },
+ { name: 'textOutput', rate: 10, strategy: 'fixed', unit: 'millionTokens' },
+ ],
+ },
+ releasedAt: '2025-11-13',
+ settings: {
+ extendParams: ['gpt5_1ReasoningEffort', 'textVerbosity'],
+ searchImpl: 'params',
+ },
+ type: 'chat',
+ },
{
abilities: {
functionCall: true,
diff --git a/packages/model-runtime/src/core/ModelRuntime.test.ts b/packages/model-runtime/src/core/ModelRuntime.test.ts
index dc25f47ed6f..2f072af45f6 100644
--- a/packages/model-runtime/src/core/ModelRuntime.test.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.test.ts
@@ -29,9 +29,10 @@ const specialProviders = [
id: ModelProvider.Azure,
payload: {
apiKey: 'user-azure-key',
- baseURL: 'user-azure-endpoint',
+ baseURL: 'https://user-azure.openai.azure.com',
apiVersion: '2024-06-01',
},
+ runtimeBaseURL: 'https://user-azure.openai.azure.com/openai/v1',
},
{
id: ModelProvider.AzureAI,
@@ -58,7 +59,7 @@ const specialProviders = [
},
];
-const testRuntime = (providerId: string, payload?: any) => {
+const testRuntime = (providerId: string, payload?: any, runtimeBaseURL?: string) => {
describe(`${providerId} provider runtime`, () => {
it('should initialize correctly', async () => {
const jwtPayload: ClientSecretPayload = { apiKey: 'user-key', ...payload };
@@ -68,7 +69,7 @@ const testRuntime = (providerId: string, payload?: any) => {
expect(runtime['_runtime']).toBeInstanceOf(providerRuntimeMap[providerId]);
if (payload?.baseURL) {
- expect(runtime['_runtime'].baseURL).toBe(payload.baseURL);
+ expect(runtime['_runtime'].baseURL).toBe(runtimeBaseURL ?? payload.baseURL);
}
});
});
@@ -93,7 +94,9 @@ describe('ModelRuntime', () => {
testRuntime(provider);
});
- specialProviders.forEach(({ id, payload }) => testRuntime(id, payload));
+ specialProviders.forEach(({ id, payload, runtimeBaseURL }) =>
+ testRuntime(id, payload, runtimeBaseURL),
+ );
});
describe('ModelRuntime chat method', () => {
diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.ts
index 6dafe1b13d2..4f183524c18 100644
--- a/packages/model-runtime/src/core/ModelRuntime.ts
+++ b/packages/model-runtime/src/core/ModelRuntime.ts
@@ -296,7 +296,6 @@ export class ModelRuntime {
LobeBedrockAIParams &
LobeCloudflareParams & {
apiKey?: string;
- apiVersion?: string;
baseURL?: string;
userId?: string;
}
diff --git a/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts b/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts
index ee20838939e..a8d97683705 100644
--- a/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts
@@ -3,6 +3,7 @@ import type { LobeRuntimeAI } from '../BaseAI';
export type ApiType =
| 'anthropic'
| 'azure'
+ | 'azureopenai'
| 'bedrock'
| 'cloudflare'
| 'deepseek'
diff --git a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts
index 9062769a7d0..e9c6bacf65f 100644
--- a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts
@@ -1,5 +1,6 @@
import { LobeAnthropicAI } from '../../providers/anthropic';
import { LobeAzureAI } from '../../providers/azureai';
+import { LobeAzureOpenAI } from '../../providers/azureOpenai';
import { LobeBedrockAI } from '../../providers/bedrock';
import { LobeCloudflareAI } from '../../providers/cloudflare';
import { LobeDeepSeekAI } from '../../providers/deepseek';
@@ -19,6 +20,7 @@ import type { ApiType, RuntimeClass } from './apiTypes';
export const baseRuntimeMap = {
anthropic: LobeAnthropicAI,
azure: LobeAzureAI,
+ azureopenai: LobeAzureOpenAI,
bedrock: LobeBedrockAI,
cloudflare: LobeCloudflareAI,
deepseek: LobeDeepSeekAI,
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
index bfba0e73541..4dce2cd9a7e 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
@@ -256,7 +256,11 @@ export const createRouterRuntime = ({
}> {
const { apiType: optionApiType, id: channelId, remark, ...optionOverrides } = optionItem;
const resolvedApiType = optionApiType ?? router.apiType;
- const finalOptions = { ...this._params, ...this._options, ...optionOverrides };
+ const finalOptions = {
+ ...this._params,
+ ...this._options,
+ ...optionOverrides,
+ };
/**
* Vertex AI uses GoogleGenAI credentials flow rather than API keys.
diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
index 9720f96259b..72a24b9f768 100644
--- a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.test.ts
@@ -1,6 +1,7 @@
import type { ModelTokensUsage } from '@lobechat/types';
import type { Pricing } from 'model-bank';
import anthropicChatModels from 'model-bank/anthropic';
+import azureChatModels from 'model-bank/azure';
import googleChatModels from 'model-bank/google';
import openaiChatModels from 'model-bank/openai';
import { describe, expect, it } from 'vitest';
@@ -366,6 +367,47 @@ describe('computeChatPricing', () => {
});
});
+ describe('Azure', () => {
+ it('uses total input tokens to select GPT-5.4 tiered rates', () => {
+ const pricing = azureChatModels.find(
+ (model: { id: string }) => model.id === 'gpt-5.4',
+ )?.pricing;
+ expect(pricing).toBeDefined();
+
+ const usage: ModelTokensUsage = {
+ inputCachedTokens: 299_000,
+ inputCacheMissTokens: 1_000,
+ inputTextTokens: 300_000,
+ outputTextTokens: 10,
+ totalInputTokens: 300_000,
+ totalOutputTokens: 10,
+ totalTokens: 300_010,
+ };
+
+ const result = computeChatCost(pricing, usage);
+ expect(result).toBeDefined();
+ expect(result?.issues).toHaveLength(0);
+
+ const input = result?.breakdown.find((item) => item.unit.name === 'textInput');
+ expect(input?.quantity).toBe(1_000);
+ expect(input?.credits).toBe(5_000);
+ expect(input?.segments).toEqual([{ quantity: 1_000, rate: 5, credits: 5_000 }]);
+
+ const cached = result?.breakdown.find((item) => item.unit.name === 'textInput_cacheRead');
+ expect(cached?.quantity).toBe(299_000);
+ expect(cached?.credits).toBe(149_500);
+ expect(cached?.segments).toEqual([{ quantity: 299_000, rate: 0.5, credits: 149_500 }]);
+
+ const output = result?.breakdown.find((item) => item.unit.name === 'textOutput');
+ expect(output?.quantity).toBe(10);
+ expect(output?.credits).toBe(225);
+ expect(output?.segments).toEqual([{ quantity: 10, rate: 22.5, credits: 225 }]);
+
+ expect(result?.totalCredits).toBe(154_725);
+ expect(result?.totalCost).toBeCloseTo(0.154725, 6);
+ });
+ });
+
describe('Anthropic', () => {
it('handles lookup pricing with TTL for Claude Opus 4.1', () => {
const pricing = anthropicChatModels.find(
diff --git a/packages/model-runtime/src/providers/azureOpenai/index.test.ts b/packages/model-runtime/src/providers/azureOpenai/index.test.ts
index 72456452654..aa6d1b981de 100644
--- a/packages/model-runtime/src/providers/azureOpenai/index.test.ts
+++ b/packages/model-runtime/src/providers/azureOpenai/index.test.ts
@@ -1,10 +1,12 @@
// @vitest-environment node
-import { AzureOpenAI } from 'openai';
+import OpenAI from 'openai';
import type { Mock } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import * as openaiCompatibleFactoryModule from '../../core/openaiCompatibleFactory';
+import * as nonStreamToStreamModule from '../../core/openaiCompatibleFactory/nonStreamToStream';
+import * as streamsModule from '../../core/streams';
import * as debugStreamModule from '../../utils/debugStream';
+import * as getModelPricingModule from '../../utils/getModelPricing';
import { LobeAzureOpenAI } from './index';
const bizErrorType = 'ProviderBizError';
@@ -20,13 +22,13 @@ describe('LobeAzureOpenAI', () => {
instance = new LobeAzureOpenAI({
baseURL: 'https://test.openai.azure.com/',
apiKey: 'test_key',
- apiVersion: '2023-03-15-preview',
});
// 使用 vi.spyOn 来模拟 streamChatCompletions 方法
vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
new ReadableStream() as any,
);
+ vi.spyOn(instance['client'].responses, 'create').mockResolvedValue(new ReadableStream() as any);
});
afterEach(() => {
@@ -45,12 +47,11 @@ describe('LobeAzureOpenAI', () => {
it('should create an instance of OpenAIClient with correct parameters', () => {
const baseURL = 'https://test.openai.azure.com/';
const apiKey = 'test_key';
- const apiVersion = '2023-03-15-preview';
- const instance = new LobeAzureOpenAI({ baseURL, apiKey, apiVersion });
+ const instance = new LobeAzureOpenAI({ baseURL, apiKey });
- expect(instance.client).toBeInstanceOf(AzureOpenAI);
- expect(instance.baseURL).toBe(baseURL);
+ expect(instance.client).toBeInstanceOf(OpenAI);
+ expect(instance.baseURL).toBe('https://test.openai.azure.com/openai/v1');
});
});
@@ -74,99 +75,184 @@ describe('LobeAzureOpenAI', () => {
});
describe('streaming response', () => {
- it('should handle multiple data chunks correctly', async () => {
- const data = [
- {
- choices: [],
- created: 0,
- id: '',
- model: '',
- object: '',
- prompt_filter_results: [
- {
- prompt_index: 0,
- content_filter_results: {
- hate: { filtered: false, severity: 'safe' },
- self_harm: { filtered: false, severity: 'safe' },
- sexual: { filtered: false, severity: 'safe' },
- violence: { filtered: false, severity: 'safe' },
- },
- },
- ],
- },
- {
- choices: [
- {
- content_filter_results: {
- hate: { filtered: false, severity: 'safe' },
- self_harm: { filtered: false, severity: 'safe' },
- sexual: { filtered: false, severity: 'safe' },
- violence: { filtered: false, severity: 'safe' },
- },
- delta: { content: '你' },
- finish_reason: null,
- index: 0,
- logprobs: null,
- },
- ],
- created: 1715516381,
- id: 'chatcmpl-9O2SzeGv5xy6yz0TcQNA1DHHLJ8N1',
- model: 'gpt-35-turbo-16k',
- object: 'chat.completion.chunk',
- system_fingerprint: null,
- },
- {
- choices: [
- {
- content_filter_results: {
- hate: { filtered: false, severity: 'safe' },
- self_harm: { filtered: false, severity: 'safe' },
- sexual: { filtered: false, severity: 'safe' },
- violence: { filtered: false, severity: 'safe' },
- },
- delta: { content: '好' },
- finish_reason: null,
- index: 0,
- logprobs: null,
- },
- ],
- created: 1715516381,
- id: 'chatcmpl-9O2SzeGv5xy6yz0TcQNA1DHHLJ8N1',
- model: 'gpt-35-turbo-16k',
- object: 'chat.completion.chunk',
- system_fingerprint: null,
- },
- {
- choices: [
- {
- content_filter_results: {
- hate: { filtered: false, severity: 'safe' },
- self_harm: { filtered: false, severity: 'safe' },
- sexual: { filtered: false, severity: 'safe' },
- violence: { filtered: false, severity: 'safe' },
- },
- delta: { content: '!' },
- finish_reason: null,
- index: 0,
- logprobs: null,
- },
- ],
- created: 1715516381,
- id: 'chatcmpl-9O2SzeGv5xy6yz0TcQNA1DHHLJ8N1',
- model: 'gpt-35-turbo-16k',
- object: 'chat.completion.chunk',
- system_fingerprint: null,
- },
- ];
-
- const mockStream = new ReadableStream({
- start(controller) {
- data.forEach((chunk) => controller.enqueue(chunk));
- controller.close();
- },
+ it('should use responses API and append web_search tool when enabledSearch is true', async () => {
+ const mockProdStream = new ReadableStream() as any;
+ const mockDebugStream = new ReadableStream() as any;
+ const mockPricing = { units: [] };
+
+ instance = new LobeAzureOpenAI({
+ apiKey: 'test_key',
+ baseURL: 'https://test.openai.azure.com/',
+ id: 'lobehub',
+ });
+
+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
+ new ReadableStream() as any,
+ );
+ vi.spyOn(instance['client'].responses, 'create').mockResolvedValue({
+ tee: () => [mockProdStream, mockDebugStream],
+ } as any);
+ vi.spyOn(getModelPricingModule, 'getModelPricing').mockResolvedValue(mockPricing as any);
+ vi.spyOn(streamsModule, 'OpenAIResponsesStream').mockReturnValue(new ReadableStream());
+
+ await instance.chat({
+ enabledSearch: true,
+ messages: [{ role: 'user', content: "Search for today's OpenAI news." }],
+ model: 'gpt-5.4',
+ reasoning_effort: 'medium',
+ stream: true,
+ top_p: 0.9,
+ verbosity: 'high',
+ } as any);
+
+ expect(instance['client'].chat.completions.create).not.toHaveBeenCalled();
+
+ const createCall = (instance['client'].responses.create as Mock).mock.calls[0][0];
+
+ expect(createCall.input).toBeDefined();
+ expect(createCall.model).toBe('gpt-5.4');
+ expect(createCall.reasoning).toEqual({ effort: 'medium', summary: 'auto' });
+ expect(createCall.store).toBe(false);
+ expect(createCall.stream).toBe(true);
+ expect(createCall.text).toEqual({ verbosity: 'high' });
+ expect(createCall.top_p).toBeUndefined();
+ expect(createCall.tools).toEqual(
+ expect.arrayContaining([expect.objectContaining({ type: 'web_search' })]),
+ );
+
+ expect(streamsModule.OpenAIResponsesStream).toHaveBeenCalledWith(
+ mockProdStream,
+ expect.objectContaining({
+ inputStartAt: expect.any(Number),
+ payload: {
+ model: 'gpt-5.4',
+ pricing: mockPricing,
+ provider: 'lobehub',
+ },
+ }),
+ );
+ });
+
+ it('should use deploymentName for Azure Responses API requests while keeping logical model for pricing', async () => {
+ const mockProdStream = new ReadableStream() as any;
+ const mockDebugStream = new ReadableStream() as any;
+ const mockPricing = { units: [] };
+
+ instance = new LobeAzureOpenAI({
+ apiKey: 'test_key',
+ baseURL: 'https://test.openai.azure.com/',
+ id: 'lobehub',
});
+
vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue(
- mockStream as any,
+ new ReadableStream() as any,
+ );
+ vi.spyOn(instance['client'].responses, 'create').mockResolvedValue({
+ tee: () => [mockProdStream, mockDebugStream],
+ } as any);
+ vi.spyOn(getModelPricingModule, 'getModelPricing').mockResolvedValue(mockPricing as any);
+ vi.spyOn(streamsModule, 'OpenAIResponsesStream').mockReturnValue(new ReadableStream());
+
+ await instance.chat({
+ deploymentName: 'prod-gpt-54',
+ messages: [{ role: 'user', content: 'Hello' }],
+ model: 'gpt-5.4',
+ stream: true,
+ } as any);
+
+ expect(instance['client'].chat.completions.create).not.toHaveBeenCalled();
+
+ const createCall = (instance['client'].responses.create as Mock).mock.calls[0][0];
+
+ expect(createCall.model).toBe('prod-gpt-54');
+ expect(createCall.reasoning).toEqual({ summary: 'auto' });
+ expect(createCall.deploymentName).toBeUndefined();
+
+ expect(streamsModule.OpenAIResponsesStream).toHaveBeenCalledWith(
+ mockProdStream,
+ expect.objectContaining({
+ payload: {
+ model: 'gpt-5.4',
+ pricing: mockPricing,
+ provider: 'lobehub',
+ },
+ }),
+ );
+ });
+
+ it('should strip unsupported params for Azure reasoning models and include usage in stream options', async () => {
+ const mockProdStream = new ReadableStream() as any;
+ const mockDebugStream = new ReadableStream() as any;
+ const mockPricing = { units: [] };
+
+ instance = new LobeAzureOpenAI({
+ apiKey: 'test_key',
+ baseURL: 'https://test.openai.azure.com/',
+ id: 'lobehub',
+ });
+
+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue({
+ tee: () => [mockProdStream, mockDebugStream],
+ } as any);
+ vi.spyOn(getModelPricingModule, 'getModelPricing').mockResolvedValue(mockPricing as any);
+ vi.spyOn(streamsModule, 'OpenAIStream').mockReturnValue(new ReadableStream());
+
+ await instance.chat({
+ frequency_penalty: 0.4,
+ logit_bias: { '42': 1 },
+ logprobs: true,
+ max_tokens: 256,
+ messages: [{ role: 'system', content: 'You are helpful.' }],
+ model: 'o3',
+ presence_penalty: 0.3,
+ reasoning_effort: 'minimal',
+ temperature: 0.7,
+ top_logprobs: 2,
+ top_p: 0.9,
+ } as any);
+
+ const createCall = (instance['client'].chat.completions.create as Mock).mock.calls[0][0];
+
+ expect(createCall.frequency_penalty).toBeUndefined();
+ expect(createCall.logit_bias).toBeUndefined();
+ expect(createCall.logprobs).toBeUndefined();
+ expect(createCall.max_tokens).toBeUndefined();
+ expect(createCall.messages[0].role).toBe('developer');
+ expect(createCall.presence_penalty).toBeUndefined();
+ expect(createCall.reasoning_effort).toBe('low');
+ expect(createCall.stream).toBe(true);
+ expect(createCall.stream_options).toEqual({ include_usage: true });
+ expect(createCall.temperature).toBeUndefined();
+ expect(createCall.top_logprobs).toBeUndefined();
+ expect(createCall.top_p).toBeUndefined();
+
+ expect(getModelPricingModule.getModelPricing).toHaveBeenCalledWith('o3', 'lobehub');
+ expect(streamsModule.OpenAIStream).toHaveBeenCalledWith(
+ mockProdStream,
+ expect.objectContaining({
+ inputStartAt: expect.any(Number),
+ payload: {
+ model: 'o3',
+ pricing: mockPricing,
+ provider: 'lobehub',
+ },
+ }),
+ );
+ });
+
+ it('should handle multiple data chunks correctly', async () => {
+ const mockProdStream = new ReadableStream() as any;
+ const mockDebugStream = new ReadableStream() as any;
+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue({
+ tee: () => [mockProdStream, mockDebugStream],
+ } as any);
+ vi.spyOn(streamsModule, 'OpenAIStream').mockReturnValue(
+ new ReadableStream({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode('event: text\ndata: "你好!"\n\n'));
+ controller.close();
+ },
+ }),
);
const result = await instance.chat({
@@ -180,40 +266,30 @@ describe('LobeAzureOpenAI', () => {
messages: [{ role: 'user', content: '你好' }],
});
- const decoder = new TextDecoder();
- const reader = result.body!.getReader();
- const stream: string[] = [];
-
- while (true) {
- const { value, done } = await reader.read();
- if (done) break;
- stream.push(decoder.decode(value));
- }
-
- expect(stream).toEqual(
- [
- 'id: ',
- 'event: data',
- 'data: {"choices":[],"created":0,"id":"","model":"","object":"","prompt_filter_results":[{"prompt_index":0,"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}]}\n',
- 'id: chatcmpl-9O2SzeGv5xy6yz0TcQNA1DHHLJ8N1',
- 'event: text',
- 'data: "你"\n',
- 'id: chatcmpl-9O2SzeGv5xy6yz0TcQNA1DHHLJ8N1',
- 'event: text',
- 'data: "好"\n',
- 'id: chatcmpl-9O2SzeGv5xy6yz0TcQNA1DHHLJ8N1',
- 'event: text',
- 'data: "!"\n',
- ].map((item) => `${item}\n`),
+ expect(result).toBeInstanceOf(Response);
+ expect(streamsModule.OpenAIStream).toHaveBeenCalledWith(
+ mockProdStream,
+ expect.objectContaining({
+ inputStartAt: expect.any(Number),
+ payload: expect.objectContaining({
+ model: 'gpt-35-turbo-16k',
+ provider: 'azure',
+ }),
+ }),
);
});
it('should handle non-streaming response', async () => {
- vi.spyOn(openaiCompatibleFactoryModule, 'transformResponseToStream').mockImplementation(
- () => {
- return new ReadableStream();
- },
- );
+ vi.spyOn(nonStreamToStreamModule, 'transformResponseToStream').mockImplementation(() => {
+ return new ReadableStream();
+ });
+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue({
+ choices: [],
+ created: 1715516381,
+ id: 'chatcmpl-non-stream',
+ model: 'gpt-35-turbo-16k',
+ object: 'chat.completion',
+ } as any);
// Act
await instance.chat({
stream: false,
@@ -223,16 +299,21 @@ describe('LobeAzureOpenAI', () => {
});
// Assert
- expect(openaiCompatibleFactoryModule.transformResponseToStream).toHaveBeenCalled();
+ expect(nonStreamToStreamModule.transformResponseToStream).toHaveBeenCalled();
});
});
it('should handle o1 series models without streaming', async () => {
- vi.spyOn(openaiCompatibleFactoryModule, 'transformResponseToStream').mockImplementation(
- () => {
- return new ReadableStream();
- },
- );
+ vi.spyOn(nonStreamToStreamModule, 'transformResponseToStream').mockImplementation(() => {
+ return new ReadableStream();
+ });
+ vi.spyOn(instance['client'].chat.completions, 'create').mockResolvedValue({
+ choices: [],
+ created: 1715516381,
+ id: 'chatcmpl-o1',
+ model: 'o1-preview',
+ object: 'chat.completion',
+ } as any);
// Act
await instance.chat({
@@ -242,7 +323,7 @@ describe('LobeAzureOpenAI', () => {
});
// Assert
- expect(openaiCompatibleFactoryModule.transformResponseToStream).toHaveBeenCalled();
+ expect(nonStreamToStreamModule.transformResponseToStream).toHaveBeenCalled();
});
describe('Error', () => {
@@ -265,7 +346,7 @@ describe('LobeAzureOpenAI', () => {
} catch (e) {
// Assert
expect(e).toEqual({
- endpoint: 'https://***.openai.azure.com/',
+ endpoint: 'https://***.openai.azure.com/openai/v1',
error: {
code: 'DeploymentNotFound',
message: 'Deployment not found',
@@ -293,7 +374,7 @@ describe('LobeAzureOpenAI', () => {
} catch (e) {
// Assert
expect(e).toEqual({
- endpoint: 'https://***.openai.azure.com/',
+ endpoint: 'https://***.openai.azure.com/openai/v1',
errorType: 'AgentRuntimeError',
provider: 'azure',
error: {
@@ -310,20 +391,15 @@ describe('LobeAzureOpenAI', () => {
it('should call debugStream when DEBUG_CHAT_COMPLETION is 1', async () => {
// Arrange
const mockProdStream = new ReadableStream() as any;
- const mockDebugStream = new ReadableStream({
- start(controller) {
- controller.enqueue('Debug stream content');
- controller.close();
- },
- }) as any;
- mockDebugStream.toReadableStream = () => mockDebugStream;
+ const mockDebugStream = new ReadableStream() as any;
(instance['client'].chat.completions.create as Mock).mockResolvedValue({
- tee: () => [mockProdStream, { toReadableStream: () => mockDebugStream }],
+ tee: () => [mockProdStream, mockDebugStream],
});
process.env.DEBUG_AZURE_CHAT_COMPLETION = '1';
vi.spyOn(debugStreamModule, 'debugStream').mockImplementation(() => Promise.resolve());
+ vi.spyOn(streamsModule, 'OpenAIStream').mockReturnValue(new ReadableStream());
// Act
await instance.chat({
@@ -407,7 +483,7 @@ describe('LobeAzureOpenAI', () => {
await expect(
instance.createImage({ model: 'gpt-image-1', params: { prompt: 'moon' } }),
).rejects.toMatchObject({
- endpoint: 'https://***.openai.azure.com/',
+ endpoint: 'https://***.openai.azure.com/openai/v1',
errorType: 'AgentRuntimeError',
provider: 'azure',
error: {
@@ -426,7 +502,7 @@ describe('LobeAzureOpenAI', () => {
await expect(
instance.createImage({ model: 'gpt-image-1', params: { prompt: 'stars' } }),
).rejects.toEqual({
- endpoint: 'https://***.openai.azure.com/',
+ endpoint: 'https://***.openai.azure.com/openai/v1',
errorType: 'AgentRuntimeError',
provider: 'azure',
error: {
@@ -454,6 +530,27 @@ describe('LobeAzureOpenAI', () => {
expect(editSpy).toHaveBeenCalledTimes(1);
const arg = vi.mocked(editSpy).mock.calls[0][0] as any;
expect(arg).not.toHaveProperty('size');
+ expect(arg).toHaveProperty('input_fidelity', 'high');
+ expect(res).toEqual({ imageUrl: url });
+ });
+
+ it('should not send input_fidelity for gpt-image-2 edit requests', async () => {
+ const url = 'https://example.com/gpt-image-2-edited.png';
+ const editSpy = vi
+ .spyOn(instance['client'].images, 'edit')
+ .mockResolvedValue({ data: [{ url }] } as any);
+
+ const helpers = await import('../../core/contextBuilders/openai');
+ vi.spyOn(helpers, 'convertImageUrlToFile').mockResolvedValue({} as any);
+
+ const res = await instance.createImage({
+ model: 'gpt-image-2',
+ params: { prompt: 'edit', imageUrl: 'https://example.com/in.png' },
+ });
+
+ expect(editSpy).toHaveBeenCalledTimes(1);
+ const arg = vi.mocked(editSpy).mock.calls[0][0] as any;
+ expect(arg).not.toHaveProperty('input_fidelity');
expect(res).toEqual({ imageUrl: url });
});
@@ -487,56 +584,4 @@ describe('LobeAzureOpenAI', () => {
expect(arg).not.toHaveProperty('image');
});
});
-
- describe('private method', () => {
- describe('tocamelCase', () => {
- it('should convert string to camel case', () => {
- const key = 'image_url';
-
- const camelCaseKey = instance['tocamelCase'](key);
-
- expect(camelCaseKey).toEqual('imageUrl');
- });
- });
-
- describe('camelCaseKeys', () => {
- it('should convert object keys to camel case', () => {
- const obj = {
- frequency_penalty: 0,
- messages: [
- {
- role: 'user',
- content: [
- {
- type: 'image_url',
- image_url: {
- url: '<image URL>',
- },
- },
- ],
- },
- ],
- };
-
- const newObj = instance['camelCaseKeys'](obj);
-
- expect(newObj).toEqual({
- frequencyPenalty: 0,
- messages: [
- {
- role: 'user',
- content: [
- {
- type: 'image_url',
- imageUrl: {
- url: '<image URL>',
- },
- },
- ],
- },
- ],
- });
- });
- });
- });
});
diff --git a/packages/model-runtime/src/providers/azureOpenai/index.ts b/packages/model-runtime/src/providers/azureOpenai/index.ts
index 2ddf9f762fd..fabb4a556f3 100644
--- a/packages/model-runtime/src/providers/azureOpenai/index.ts
+++ b/packages/model-runtime/src/providers/azureOpenai/index.ts
@@ -1,243 +1,267 @@
import debug from 'debug';
import { ModelProvider } from 'model-bank';
import type OpenAI from 'openai';
-import { AzureOpenAI } from 'openai';
-import type { Stream } from 'openai/streaming';
-
-import { systemToUserModels } from '../../const/models';
-import type { LobeRuntimeAI } from '../../core/BaseAI';
-import { convertImageUrlToFile, convertOpenAIMessages } from '../../core/contextBuilders/openai';
-import { transformResponseToStream } from '../../core/openaiCompatibleFactory';
-import { OpenAIStream } from '../../core/streams';
-import type {
- ChatMethodOptions,
- ChatStreamPayload,
- Embeddings,
- EmbeddingsOptions,
- EmbeddingsPayload,
-} from '../../types';
+
+import { responsesAPIModels, systemToUserModels } from '../../const/models';
+import { pruneReasoningPayload } from '../../core/contextBuilders/openai';
+import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';
+import type { ChatMethodOptions, ChatStreamPayload } from '../../types';
import { AgentRuntimeErrorType } from '../../types/error';
-import type { CreateImagePayload, CreateImageResponse } from '../../types/image';
+import type { CreateImagePayload } from '../../types/image';
import { AgentRuntimeError } from '../../utils/createError';
-import { debugStream } from '../../utils/debugStream';
-import { StreamingResponse } from '../../utils/response';
import { sanitizeError } from '../../utils/sanitizeError';
const azureImageLogger = debug('lobe-image:azure');
-export class LobeAzureOpenAI implements LobeRuntimeAI {
- client: AzureOpenAI;
-
- constructor(params: { apiKey?: string; apiVersion?: string; baseURL?: string } = {}) {
- if (!params.apiKey || !params.baseURL)
- throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidProviderAPIKey);
-
- this.client = new AzureOpenAI({
- apiKey: params.apiKey,
- apiVersion: params.apiVersion,
- dangerouslyAllowBrowser: true,
- endpoint: params.baseURL,
- });
-
- this.baseURL = params.baseURL;
- }
-
- baseURL: string;
-
- async chat(payload: ChatStreamPayload, options?: ChatMethodOptions) {
- // Remove internal apiMode parameter to prevent sending to Azure OpenAI API
-
- const { messages, model, apiMode: _, ...params } = payload;
- // o1 series models on Azure OpenAI does not support streaming currently
- const enableStreaming = model.includes('o1') ? false : (params.stream ?? true);
-
- const updatedMessages = messages.map((message) => ({
- ...message,
- role:
- // Convert 'system' role to 'user' or 'developer' based on the model
- (model.includes('o1') || model.includes('o3') || model.includes('gpt-5')) &&
- message.role === 'system'
- ? [...systemToUserModels].some((sub) => model.includes(sub))
- ? 'user'
- : 'developer'
- : message.role,
- }));
+const azureSearchContextSize = process.env.OPENAI_SEARCH_CONTEXT_SIZE;
+
+const isAzureReasoningModel = (model: string) =>
+ model.includes('gpt-5') || model.includes('o1') || model.includes('o3');
+
+const supportsImageInputFidelity = (model: string) => /^gpt-image-1(?:$|[-.])/.test(model);
+
+const transformAzureSystemMessages = (messages: ChatStreamPayload['messages'], model: string) =>
+ messages.map((message) => ({
+ ...message,
+ role:
+ isAzureReasoningModel(model) && message.role === 'system'
+ ? [...systemToUserModels].some((sub) => model.includes(sub))
+ ? 'user'
+ : 'developer'
+ : message.role,
+ }));
+
+const appendAzureSearchTool = (
+ tools: ChatStreamPayload['tools'],
+ enabledSearch?: boolean,
+): ChatStreamPayload['tools'] => {
+ if (!enabledSearch) return tools;
+
+ return [
+ ...(tools || []),
+ {
+ type: 'web_search',
+ ...(azureSearchContextSize && {
+ search_context_size: azureSearchContextSize,
+ }),
+ } as any,
+ ];
+};
+
+const normalizeAzureBaseURL = (value?: string) => {
+ if (!value) return value;
+
+ const url = new URL(value);
+ const normalizedPathname = url.pathname.replace(/\/+$/, '');
+ const hasOpenAISegment = normalizedPathname.split('/').includes('openai');
+
+ url.pathname = hasOpenAISegment
+ ? '/openai/v1'
+ : `${normalizedPathname === '/' ? '' : normalizedPathname}/openai/v1`;
+ url.search = '';
+ url.hash = '';
+
+ return url.toString().replace(/\/$/, '');
+};
+
+const maskSensitiveUrl = (url: string) => {
+ const regex = /^(https:\/\/)([^.]+)(\.(?:openai\.azure\.com|cognitiveservices\.azure\.com).*)$/;
+
+ return url.replace(regex, (match, protocol, subdomain, rest) => `${protocol}***${rest}`);
+};
+
+const BaseAzureOpenAI = createOpenAICompatibleRuntime({
+ chatCompletion: {
+ handlePayload: (payload) => {
+ const { deploymentName, enabledSearch, model, ...rest } = payload;
+ const requestModel = deploymentName ?? model;
+
+ if (responsesAPIModels.has(model) || enabledSearch) {
+ return {
+ ...rest,
+ apiMode: 'responses',
+ enabledSearch,
+ model: requestModel,
+ } as ChatStreamPayload;
+ }
- try {
- // Create parameters with proper typing for OpenAI SDK, handling reasoning_effort compatibility
- const { reasoning_effort, ...otherParams } = params;
+ const updatedMessages = transformAzureSystemMessages(payload.messages, model);
+ const azureChatParams = rest as typeof rest & { logit_bias?: Record<string, number> };
+
+ const {
+ frequency_penalty,
+ logit_bias,
+ logprobs,
+ max_tokens,
+ presence_penalty,
+ reasoning_effort,
+ temperature,
+ top_logprobs,
+ top_p,
+ ...otherParams
+ } = azureChatParams;
- // Convert 'minimal' to 'low' for OpenAI SDK compatibility
const compatibleReasoningEffort = reasoning_effort === 'minimal' ? 'low' : reasoning_effort;
-
- const baseParams = {
- messages: await convertOpenAIMessages(
- updatedMessages as OpenAI.ChatCompletionMessageParam[],
- ),
- model,
+ // Azure GPT-5 / o1 / o3 reasoning models reject sampling/penalty params, so we drop
+ // them entirely for reasoning models and only pass them through for regular chat.
+ const supportedSamplingParams = isAzureReasoningModel(model)
+ ? {}
+ : {
+ frequency_penalty,
+ logit_bias,
+ logprobs,
+ max_tokens,
+ presence_penalty,
+ temperature,
+ top_logprobs,
+ top_p,
+ };
+
+ return {
...otherParams,
- max_completion_tokens: undefined,
- tool_choice: params.tools ? ('auto' as const) : undefined,
- };
-
- // Add reasoning_effort only if it exists and cast to proper type
- const openaiParams = compatibleReasoningEffort
- ? {
- ...baseParams,
- reasoning_effort: compatibleReasoningEffort as 'low' | 'medium' | 'high',
- }
- : baseParams;
-
- const response = enableStreaming
- ? await this.client.chat.completions.create({ ...openaiParams, stream: true })
- : await this.client.chat.completions.create({ ...openaiParams, stream: false });
- if (enableStreaming) {
- const stream = response as Stream<OpenAI.ChatCompletionChunk>;
- const [prod, debug] = stream.tee();
- if (process.env.DEBUG_AZURE_CHAT_COMPLETION === '1') {
- debugStream(debug.toReadableStream()).catch(console.error);
- }
- return StreamingResponse(OpenAIStream(prod, { callbacks: options?.callback }), {
- headers: options?.headers,
- });
- } else {
- const stream = transformResponseToStream(response as OpenAI.ChatCompletion);
- return StreamingResponse(
- OpenAIStream(stream, { callbacks: options?.callback, enableStreaming: false }),
- {
- headers: options?.headers,
- },
- );
+ ...supportedSamplingParams,
+ messages: updatedMessages as OpenAI.Chat.ChatCompletionMessageParam[],
+ model: requestModel,
+ reasoning_effort: compatibleReasoningEffort as 'low' | 'medium' | 'high' | undefined,
+ stream: model.includes('o1') ? false : (payload.stream ?? true),
+ } as any;
+ },
+ useResponseModels: [...responsesAPIModels],
+ },
+ debug: {
+ chatCompletion: () => process.env.DEBUG_AZURE_CHAT_COMPLETION === '1',
+ responses: () => process.env.DEBUG_AZURE_RESPONSES === '1',
+ },
+ provider: ModelProvider.Azure,
+ responses: {
+ handlePayload: (payload) => {
+ const { deploymentName, enabledSearch, model, tools, verbosity, ...rest } = payload;
+ const requestModel = deploymentName ?? model;
+ const updatedMessages = transformAzureSystemMessages(payload.messages, model);
+ const azureTools = appendAzureSearchTool(tools, enabledSearch);
+ const responseText = verbosity
+ ? payload.text
+ ? { ...payload.text, verbosity }
+ : { verbosity }
+ : payload.text;
+
+ if (isAzureReasoningModel(model)) {
+ const reasoning = payload.reasoning
+ ? { ...payload.reasoning, summary: 'auto' }
+ : { summary: 'auto' };
+
+ return pruneReasoningPayload({
+ ...rest,
+ messages: updatedMessages,
+ model: requestModel,
+ reasoning,
+ stream: payload.stream ?? true,
+ text: responseText,
+ tools: azureTools as any,
+ } as ChatStreamPayload) as ChatStreamPayload;
}
- } catch (e) {
- return this.handleError(e, model);
- }
+
+ return {
+ ...rest,
+ messages: updatedMessages,
+ model: requestModel,
+ text: responseText,
+ tools: azureTools,
+ } as ChatStreamPayload;
+ },
+ },
+});
+
+export class LobeAzureOpenAI extends BaseAzureOpenAI {
+ constructor(options: Record<string, any> = {}) {
+ const { endpoint, ...rest } = options;
+ const baseURL = normalizeAzureBaseURL(rest.baseURL ?? endpoint);
+
+ super({
+ ...rest,
+ ...(baseURL ? { baseURL } : {}),
+ });
}
- async embeddings(payload: EmbeddingsPayload, options?: EmbeddingsOptions): Promise<Embeddings[]> {
+ async chat(payload: ChatStreamPayload, options?: ChatMethodOptions) {
try {
- const res = await this.client.embeddings.create(
- { ...payload, encoding_format: 'float', user: options?.user },
- { headers: options?.headers, signal: options?.signal },
- );
-
- if (res.usage && options?.onUsage) {
- const { convertOpenAIUsage } = await import('../../core/usageConverters/openai');
- const { getModelPricing } = await import('../../utils/getModelPricing');
- const pricing = await getModelPricing(payload.model, ModelProvider.Azure);
- await options.onUsage(
- convertOpenAIUsage(res.usage as any, {
- model: payload.model,
- pricing,
- provider: ModelProvider.Azure,
- }),
- );
- }
-
- return res.data.map((item) => item.embedding);
+ return await super.chat(payload, options);
} catch (error) {
- return this.handleError(error, payload.model);
+ throw this.attachDeploymentId(error, payload.deploymentName ?? payload.model);
}
}
- // Create image using Azure OpenAI Images API (gpt-image-1 or DALL·E deployments)
- async createImage(payload: CreateImagePayload): Promise<CreateImageResponse> {
+ async createImage(payload: CreateImagePayload) {
const { model, params } = payload;
azureImageLogger('Creating image with model: %s and params: %O', model, params);
try {
- // Clone params and remap imageUrls/imageUrl -> image
const userInput: Record<string, any> = { ...params };
+ const hasImageUrlsInput =
+ Array.isArray(userInput.imageUrls) && userInput.imageUrls.length > 0;
+ const hasSingleImageUrlInput = userInput.imageUrl && !userInput.image;
- // Convert imageUrls to 'image' for edit API
- if (Array.isArray(userInput.imageUrls) && userInput.imageUrls.length > 0) {
- const imageFiles = await Promise.all(
- userInput.imageUrls.map((url: string) => convertImageUrlToFile(url)),
- );
- userInput.image = imageFiles.length === 1 ? imageFiles[0] : imageFiles;
- }
+ if (hasImageUrlsInput || hasSingleImageUrlInput) {
+ const { convertImageUrlToFile } = await import('../../core/contextBuilders/openai');
- // Backward compatibility: single imageUrl -> image
- if (userInput.imageUrl && !userInput.image) {
- userInput.image = await convertImageUrlToFile(userInput.imageUrl);
+ if (hasImageUrlsInput) {
+ const imageFiles = await Promise.all(
+ userInput.imageUrls.map((url: string) => convertImageUrlToFile(url)),
+ );
+ userInput.image = imageFiles.length === 1 ? imageFiles[0] : imageFiles;
+ } else if (hasSingleImageUrlInput) {
+ userInput.image = await convertImageUrlToFile(userInput.imageUrl);
+ }
}
- // Remove non-API parameters to avoid unknown_parameter errors
delete userInput.imageUrls;
delete userInput.imageUrl;
const isImageEdit = Boolean(userInput.image);
+ azureImageLogger('Is Image Edit: %s', isImageEdit);
- azureImageLogger('Is Image Edit: ' + isImageEdit);
- // Azure/OpenAI Images: remove unsupported/auto values where appropriate
if (userInput.size === 'auto') delete userInput.size;
- // Build options: do not force response_format for gpt-image-1
- const options: any = {
+ // gpt-image-2 rejects input_fidelity because it is always high fidelity by default.
+ // Keep the parameter limited to the gpt-image-1 family, matching OpenAI-compatible runtime.
+ const shouldUseInputFidelity = isImageEdit && supportsImageInputFidelity(model);
+
+ const azureImageOptions: Record<string, any> = {
model,
n: 1,
- ...(isImageEdit ? { input_fidelity: 'high' } : {}),
+ ...(shouldUseInputFidelity ? { input_fidelity: 'high' } : {}),
...userInput,
};
- // For generate, ensure no 'image' field is sent
- if (!isImageEdit) delete options.image;
+ if (!isImageEdit) delete azureImageOptions.image;
- // Call Azure Images API
- const img = isImageEdit
- ? await this.client.images.edit(options)
- : await this.client.images.generate(options);
+ const imageResponse = isImageEdit
+ ? await this.client.images.edit(azureImageOptions as any)
+ : await this.client.images.generate(azureImageOptions as any);
- // Normalize possible string JSON response -- Sometimes Azure Image API returns a text/plain Content-Type
- let result: any = img as any;
+ let result: any = imageResponse;
if (typeof result === 'string') {
- try {
- result = JSON.parse(result);
- } catch {
- const truncated = result.length > 500 ? result.slice(0, 500) + '...[truncated]' : result;
- azureImageLogger(
- `Failed to parse string response from images API. Raw response: ${truncated}`,
- );
- throw new Error('Invalid image response: expected JSON string but parsing failed');
- }
+ result = JSON.parse(result);
} else if (result && typeof result === 'object') {
- // Handle common Azure REST shapes
- if (typeof (result as any).bodyAsText === 'string') {
- try {
- result = JSON.parse((result as any).bodyAsText);
- } catch {
- const rawText = (result as any).bodyAsText;
- const truncated =
- rawText.length > 500 ? rawText.slice(0, 500) + '...[truncated]' : rawText;
- azureImageLogger(
- `Failed to parse bodyAsText from images API. Raw response: ${truncated}`,
- );
- throw new Error('Invalid image response: bodyAsText not valid JSON');
- }
- } else if (typeof (result as any).body === 'string') {
- try {
- result = JSON.parse((result as any).body);
- } catch {
- azureImageLogger('Failed to parse body from images API response');
- throw new Error('Invalid image response: body not valid JSON');
- }
+ if (typeof result.bodyAsText === 'string') {
+ result = JSON.parse(result.bodyAsText);
+ } else if (typeof result.body === 'string') {
+ result = JSON.parse(result.body);
}
}
- // Validate response
- if (!result || !result.data || !Array.isArray(result.data) || result.data.length === 0) {
+ if (!result || !Array.isArray(result.data) || result.data.length === 0) {
throw new Error(
`Invalid image response: missing or empty data array. Response: ${JSON.stringify(result)}`,
);
}
- const imageData: any = result.data[0];
- if (!imageData)
+ const imageData = result.data[0];
+ if (!imageData) {
throw new Error('Invalid image response: first data item is null or undefined');
+ }
- // Prefer base64 if provided, otherwise URL
if (imageData.b64_json) {
- const mimeType = 'image/png';
- return { imageUrl: `data:${mimeType};base64,${imageData.b64_json}` };
+ return { imageUrl: `data:image/png;base64,${imageData.b64_json}` };
}
if (imageData.url) {
@@ -245,75 +269,55 @@ export class LobeAzureOpenAI implements LobeRuntimeAI {
}
throw new Error('Invalid image response: missing both b64_json and url fields');
- } catch (e) {
- return this.handleError(e, model);
+ } catch (error) {
+ throw this.handleError(error);
}
}
- protected handleError(e: any, model?: string): never {
- let error = e as { [key: string]: any; code: string; message: string };
+ protected handleError(error: any) {
+ let normalizedError = error as { [key: string]: any; code?: string; message?: string };
- if (error.code) {
- switch (error.code) {
- case 'DeploymentNotFound': {
- error = { ...error, deployId: model };
- }
- }
- } else {
- error = {
- cause: error.cause,
- message: error.message,
- name: error.name,
- } as any;
+ if (!normalizedError.code) {
+ normalizedError = {
+ cause: normalizedError.cause,
+ message: normalizedError.message,
+ name: normalizedError.name,
+ };
}
- const errorType = error.code
- ? AgentRuntimeErrorType.ProviderBizError
- : AgentRuntimeErrorType.AgentRuntimeError;
-
- // Sanitize error to remove sensitive information like API keys from headers
- const sanitizedError = sanitizeError(error);
-
- throw AgentRuntimeError.chat({
- endpoint: this.maskSensitiveUrl(this.baseURL),
- error: sanitizedError,
- errorType,
+ return AgentRuntimeError.chat({
+ endpoint: maskSensitiveUrl(this.baseURL),
+ error: sanitizeError(normalizedError),
+ errorType: normalizedError.code
+ ? AgentRuntimeErrorType.ProviderBizError
+ : AgentRuntimeErrorType.AgentRuntimeError,
provider: ModelProvider.Azure,
});
}
- // Convert object keys to camel case, copy from `@azure/openai` in `node_modules/@azure/openai/dist/index.cjs`
- private camelCaseKeys = (obj: any): any => {
- if (typeof obj !== 'object' || !obj) return obj;
- if (Array.isArray(obj)) {
- return obj.map((v) => this.camelCaseKeys(v));
- } else {
- for (const key of Object.keys(obj)) {
- const value = obj[key];
- const newKey = this.tocamelCase(key);
- if (newKey !== key) {
- delete obj[key];
- }
- obj[newKey] = typeof obj[newKey] === 'object' ? this.camelCaseKeys(value) : value;
- }
- return obj;
+ /**
+ * Keep DeploymentNotFound payload backwards-compatible because callers and
+ * tests rely on the failed deployment/model id being present in the error body.
+ */
+ private attachDeploymentId(error: any, model?: string) {
+ if (
+ model &&
+ error &&
+ typeof error === 'object' &&
+ error.error &&
+ typeof error.error === 'object' &&
+ error.error.code === 'DeploymentNotFound' &&
+ !error.error.deployId
+ ) {
+ return {
+ ...error,
+ error: {
+ ...error.error,
+ deployId: model,
+ },
+ };
}
- };
-
- private tocamelCase = (str: string) => {
- return str
- .toLowerCase()
- .replaceAll(/(_[a-z])/g, (group) => group.toUpperCase().replace('_', ''));
- };
-
- private maskSensitiveUrl = (url: string) => {
- // Use a regex to match the content between 'https://' and '.openai.azure.com/'
- const regex = /^(https:\/\/)([^.]+)(\.openai\.azure\.com\/.*)$/;
-
- // Use a replacement function
- return url.replace(regex, (match, protocol, subdomain, rest) => {
- // Replace the subdomain with '***'
- return `${protocol}***${rest}`;
- });
- };
+
+ return error;
+ }
}
diff --git a/packages/model-runtime/src/types/chat.ts b/packages/model-runtime/src/types/chat.ts
index ff0053d7b62..ca172bd2ae7 100644
--- a/packages/model-runtime/src/types/chat.ts
+++ b/packages/model-runtime/src/types/chat.ts
@@ -61,6 +61,10 @@ export interface OpenAIChatMessage {
*/
export interface ChatStreamPayload {
apiMode?: 'chatCompletion' | 'responses';
+ /**
+ * @title Provider deployment name
+ */
+ deploymentName?: string;
effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max';
/**
* Enable context caching
diff --git a/packages/types/src/openai/chat.ts b/packages/types/src/openai/chat.ts
index c6e318092b3..014a5a2989e 100644
--- a/packages/types/src/openai/chat.ts
+++ b/packages/types/src/openai/chat.ts
@@ -61,6 +61,10 @@ export interface OpenAIChatMessage {
* @title Chat Stream Payload
*/
export interface ChatStreamPayload {
+ /**
+ * Provider deployment name
+ */
+ deploymentName?: string;
/**
* Whether search is enabled
*/
diff --git a/src/locales/default/modelProvider.ts b/src/locales/default/modelProvider.ts
index f813a58e89f..2f334b2d00b 100644
--- a/src/locales/default/modelProvider.ts
+++ b/src/locales/default/modelProvider.ts
@@ -5,8 +5,9 @@ export default {
'azure.azureApiVersion.title': 'Azure API Version',
'azure.empty': 'Please enter a model ID to add the first model',
'azure.endpoint.desc':
- "When checking resources from the Azure portal, you can find this value in the 'Keys and Endpoints' section",
- 'azure.endpoint.placeholder': 'https://docs-test-001.openai.azure.com',
+ "When checking resources from the Azure portal, you can find this value in the 'Keys and Endpoints' section. Azure OpenAI endpoints from the Responses API path are also supported.",
+ 'azure.endpoint.placeholder':
+ 'https://your-resource.cognitiveservices.azure.com/openai/responses',
'azure.endpoint.title': 'Azure API Address',
'azure.modelListPlaceholder': 'Select or add the OpenAI model you deployed',
'azure.title': 'Azure OpenAI',
diff --git a/src/routes/(main)/settings/provider/detail/azure/index.tsx b/src/routes/(main)/settings/provider/detail/azure/index.tsx
index e6eba1a60d7..e8094fd9d4b 100644
--- a/src/routes/(main)/settings/provider/detail/azure/index.tsx
+++ b/src/routes/(main)/settings/provider/detail/azure/index.tsx
@@ -1,7 +1,5 @@
'use client';
-import { AutoComplete, Markdown } from '@lobehub/ui';
-import { createStaticStyles } from 'antd-style';
import { ModelProvider } from 'model-bank';
import { AzureProviderCard } from 'model-bank/modelProviders';
import { useTranslation } from 'react-i18next';
@@ -14,18 +12,6 @@ import { KeyVaultsConfigKey, LLMProviderApiTokenKey, LLMProviderBaseUrlKey } fro
import { type ProviderItem } from '../../type';
import ProviderDetail from '../default';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- markdown: css`
- p {
- color: ${cssVar.colorTextDescription} !important;
- }
- `,
- tip: css`
- font-size: 12px;
- color: ${cssVar.colorTextDescription};
- `,
-}));
-
const providerKey = ModelProvider.Azure;
const useProviderCard = (): ProviderItem => {
@@ -67,29 +53,6 @@ const useProviderCard = (): ProviderItem => {
label: t('azure.endpoint.title'),
name: [KeyVaultsConfigKey, LLMProviderBaseUrlKey],
},
- {
- children: isLoading ? (
- <SkeletonInput />
- ) : (
- <AutoComplete
- placeholder={'20XX-XX-XX'}
- options={[
- '2024-10-21',
- '2024-06-01',
- '2025-01-01-preview',
- '2024-09-01-preview',
- '2024-10-01-preview',
- ].map((i) => ({ label: i, value: i }))}
- />
- ),
- desc: (
- <Markdown className={styles.markdown} fontSize={12} variant={'chat'}>
- {t('azure.azureApiVersion.desc')}
- </Markdown>
- ),
- label: t('azure.azureApiVersion.title'),
- name: [KeyVaultsConfigKey, 'apiVersion'],
- },
],
checkModel,
modelList: {
diff --git a/src/server/modules/ModelRuntime/index.test.ts b/src/server/modules/ModelRuntime/index.test.ts
index a8174fb8e98..027ed8f65ab 100644
--- a/src/server/modules/ModelRuntime/index.test.ts
+++ b/src/server/modules/ModelRuntime/index.test.ts
@@ -36,7 +36,7 @@ vi.mock('@/envs/llm', () => ({
GOOGLE_API_KEY: 'test-google-key',
AZURE_API_KEY: 'test-azure-key',
- AZURE_ENDPOINT: 'endpoint',
+ AZURE_ENDPOINT: 'https://test-azure.openai.azure.com',
ZHIPU_API_KEY: 'test.zhipu-key',
MOONSHOT_API_KEY: 'test-moonshot-key',
@@ -80,26 +80,26 @@ describe('initModelRuntimeWithUserPayload method', () => {
it('Azure AI provider: with apikey, endpoint and apiversion', async () => {
const jwtPayload: ClientSecretPayload = {
apiKey: 'user-azure-key',
- baseURL: 'user-azure-endpoint',
+ baseURL: 'https://user-azure.openai.azure.com',
azureApiVersion: '2024-06-01',
};
const runtime = await initModelRuntimeWithUserPayload(ModelProvider.Azure, jwtPayload);
expect(runtime).toBeInstanceOf(ModelRuntime);
expect(runtime['_runtime']).toBeInstanceOf(LobeAzureOpenAI);
- expect(runtime['_runtime'].baseURL).toBe(jwtPayload.baseURL);
+ expect(runtime['_runtime'].baseURL).toBe('https://user-azure.openai.azure.com/openai/v1');
});
it('Custom provider should use runtimeProvider to init', async () => {
const jwtPayload: ClientSecretPayload = {
apiKey: 'user-azure-key',
azureApiVersion: '2024-06-01',
- baseURL: 'user-azure-endpoint',
+ baseURL: 'https://user-azure.openai.azure.com',
runtimeProvider: ModelProvider.Azure,
};
const runtime = await initModelRuntimeWithUserPayload('custom-provider', jwtPayload);
expect(runtime).toBeInstanceOf(ModelRuntime);
expect(runtime['_runtime']).toBeInstanceOf(LobeAzureOpenAI);
- expect(runtime['_runtime'].baseURL).toBe(jwtPayload.baseURL);
+ expect(runtime['_runtime'].baseURL).toBe('https://user-azure.openai.azure.com/openai/v1');
});
it('ZhiPu AI provider: with apikey', async () => {
@@ -518,7 +518,7 @@ describe('buildPayloadFromKeyVaults', () => {
});
});
- it('Azure: returns apiKey, baseURL, azureApiVersion and runtimeProvider', () => {
+ it('Azure: returns apiKey, baseURL and runtimeProvider', () => {
const keyVaults = {
apiKey: 'azure-api-key',
baseURL: 'https://my-azure.openai.azure.com',
@@ -529,7 +529,6 @@ describe('buildPayloadFromKeyVaults', () => {
expect(payload).toEqual({
apiKey: 'azure-api-key',
- azureApiVersion: '2024-06-01',
baseURL: 'https://my-azure.openai.azure.com',
runtimeProvider: ModelProvider.Azure,
});
@@ -645,7 +644,7 @@ describe('buildPayloadFromKeyVaults', () => {
});
describe('custom provider with sdkType should include provider-specific fields', () => {
- it('custom provider with Azure sdkType includes azureApiVersion', () => {
+ it('custom provider with Azure sdkType keeps apiKey and baseURL only', () => {
const keyVaults = {
apiKey: 'custom-azure-key',
baseURL: 'https://custom-azure.openai.azure.com',
@@ -654,7 +653,8 @@ describe('buildPayloadFromKeyVaults', () => {
// Simulates a custom provider where runtimeProvider is resolved to 'azure'
const payload = buildPayloadFromKeyVaults(keyVaults, ModelProvider.Azure);
- expect(payload.azureApiVersion).toBe('2024-06-01');
+ expect(payload.apiKey).toBe('custom-azure-key');
+ expect(payload.baseURL).toBe('https://custom-azure.openai.azure.com');
expect(payload.runtimeProvider).toBe(ModelProvider.Azure);
});
diff --git a/src/server/modules/ModelRuntime/index.ts b/src/server/modules/ModelRuntime/index.ts
index e3686f83e3a..9c3e296682b 100644
--- a/src/server/modules/ModelRuntime/index.ts
+++ b/src/server/modules/ModelRuntime/index.ts
@@ -62,7 +62,7 @@ const resolveRuntimeProvider = (provider: string, sdkType?: string): string => {
*
* For custom providers, we use runtimeProvider (sdkType) to determine which fields
* to include in the payload. This ensures that provider-specific fields like
- * cloudflareBaseURLOrAccountID or azureApiVersion are correctly forwarded.
+ * cloudflareBaseURLOrAccountID are correctly forwarded.
*
* @param keyVaults - The keyVaults object from database (already decrypted)
* @param runtimeProvider - The runtime provider (sdkType) to use for building payload
@@ -92,7 +92,6 @@ export const buildPayloadFromKeyVaults = (
case ModelProvider.Azure: {
return {
apiKey: keyVaults.apiKey,
- azureApiVersion: keyVaults.apiVersion,
baseURL: keyVaults.baseURL || keyVaults.endpoint,
runtimeProvider,
};
@@ -194,11 +193,10 @@ const getParamsFromPayload = (provider: string, payload: ClientSecretPayload) =>
}
case ModelProvider.Azure: {
- const { AZURE_API_KEY, AZURE_API_VERSION, AZURE_ENDPOINT } = llmConfig;
+ const { AZURE_API_KEY, AZURE_ENDPOINT } = llmConfig;
const apiKey = apiKeyManager.pick(payload?.apiKey || AZURE_API_KEY);
const baseURL = payload?.baseURL || AZURE_ENDPOINT;
- const apiVersion = payload?.azureApiVersion || AZURE_API_VERSION;
- return { apiKey, apiVersion, baseURL };
+ return { apiKey, baseURL };
}
case ModelProvider.AzureAI: {
diff --git a/src/services/__tests__/_auth.test.ts b/src/services/__tests__/_auth.test.ts
index fe03d002182..b8fd1793838 100644
--- a/src/services/__tests__/_auth.test.ts
+++ b/src/services/__tests__/_auth.test.ts
@@ -103,8 +103,6 @@ describe('getProviderAuthPayload', () => {
const payload = getProviderAuthPayload(ModelProvider.Azure, mockAzureConfig);
expect(payload).toEqual({
apiKey: mockAzureConfig.apiKey,
- azureApiVersion: mockAzureConfig.apiVersion,
- apiVersion: mockAzureConfig.apiVersion,
baseURL: mockAzureConfig.endpoint,
});
});
diff --git a/src/services/_auth.ts b/src/services/_auth.ts
index 739004f7673..bcd30e9adfe 100644
--- a/src/services/_auth.ts
+++ b/src/services/_auth.ts
@@ -51,10 +51,6 @@ export const getProviderAuthPayload = (
case ModelProvider.Azure: {
return {
apiKey: clientApiKeyManager.pick(keyVaults.apiKey),
-
- apiVersion: keyVaults.apiVersion,
- /** @deprecated */
- azureApiVersion: keyVaults.apiVersion,
baseURL: keyVaults.baseURL || keyVaults.endpoint,
};
}
diff --git a/src/services/chat/chat.test.ts b/src/services/chat/chat.test.ts
index e72a06385c9..5769f691638 100644
--- a/src/services/chat/chat.test.ts
+++ b/src/services/chat/chat.test.ts
@@ -3,6 +3,7 @@ import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
import { type ChatStreamPayload, type LobeTool, type UIChatMessage } from '@lobechat/types';
import { ChatErrorType } from '@lobechat/types';
import { act } from '@testing-library/react';
+import { ModelProvider } from 'model-bank';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { DEFAULT_AGENT_CONFIG } from '@/const/settings';
@@ -10,7 +11,7 @@ import * as toolEngineeringModule from '@/helpers/toolEngineering';
import { agentDocumentService } from '@/services/agentDocument';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
-import { aiModelSelectors } from '@/store/aiInfra';
+import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';
import { useChatStore } from '@/store/chat';
import { useToolStore } from '@/store/tool';
import { settingsSelectors } from '@/store/user/selectors';
@@ -118,6 +119,7 @@ beforeEach(async () => {
() => ({ searchMode: 'off' }) as any,
);
useAgentStore.setState({ activeAgentId: undefined, agentDocumentsMap: {} } as any);
+ useAiInfraStore.setState({ enabledAiModels: [] });
useChatStore.setState({ activeAgentId: undefined } as any);
});
@@ -1614,6 +1616,37 @@ describe('ChatService', () => {
);
});
+ it('should preserve Azure Responses-only logical model and pass deploymentName separately', async () => {
+ useAiInfraStore.setState({
+ enabledAiModels: [
+ {
+ config: { deploymentName: 'prod-gpt-54' },
+ id: 'gpt-5.4',
+ providerId: ModelProvider.Azure,
+ },
+ ],
+ } as any);
+
+ const params: Partial<ChatStreamPayload> = {
+ messages: [],
+ model: 'gpt-5.4',
+ provider: ModelProvider.Azure,
+ };
+
+ await chatService.getChatCompletion(params, {});
+
+ const payload = JSON.parse(mockFetchSSE.mock.calls[0][1].body);
+
+ expect(payload).toEqual(
+ expect.objectContaining({
+ apiMode: 'chatCompletion',
+ deploymentName: 'prod-gpt-54',
+ messages: [],
+ model: 'gpt-5.4',
+ }),
+ );
+ });
+
it('should return InvalidAccessCode error when enableFetchOnClient is true and auth is enabled but user is not signed in', async () => {
// Mock fetchSSE to call onErrorHandle with the error
const { fetchSSE } = await import('@lobechat/fetch-sse');
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index f4961eca3d6..7bfa8fce9e9 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -3,8 +3,8 @@ import { KLAVIS_SERVER_TYPES, LOBEHUB_SKILL_PROVIDERS } from '@lobechat/const';
import { type OfficialToolItem } from '@lobechat/context-engine';
import { type FetchSSEOptions } from '@lobechat/fetch-sse';
import { fetchSSE, standardizeAnimationStyle } from '@lobechat/fetch-sse';
-import { type ChatCompletionErrorPayload } from '@lobechat/model-runtime';
-import { AgentRuntimeError } from '@lobechat/model-runtime';
+import type { ChatCompletionErrorPayload } from '@lobechat/model-runtime';
+import { AgentRuntimeError, responsesAPIModels } from '@lobechat/model-runtime';
import {
type RuntimeInitialContext,
type RuntimeStepContext,
@@ -352,18 +352,14 @@ class ChatService {
// =================== process model =================== //
// ===================================================== //
let model = res.model || DEFAULT_AGENT_CONFIG.model;
+ const deploymentName = providersWithDeploymentName.has(provider)
+ ? findDeploymentName(model, provider)
+ : undefined;
+ const shouldUseDeploymentField =
+ provider === ModelProvider.Azure && responsesAPIModels.has(model);
- // if the provider is Azure, get the deployment name as the request model
- const providersWithDeploymentName = [
- ModelProvider.Azure,
- ModelProvider.Volcengine,
- ModelProvider.AzureAI,
- ModelProvider.Qwen,
- ModelProvider.KimiCodingPlan,
- ] as string[];
-
- if (providersWithDeploymentName.includes(provider)) {
- model = findDeploymentName(model, provider);
+ if (!shouldUseDeploymentField && deploymentName) {
+ model = deploymentName;
}
// When user explicitly disables Responses API, set apiMode to 'chatCompletion'
@@ -388,7 +384,14 @@ class ChatService {
stream: chatConfig.enableStreaming !== false, // Default to true if not set
...DEFAULT_AGENT_CONFIG.params,
},
- { ...res, apiMode, model },
+ {
+ ...res,
+ apiMode,
+ ...(shouldUseDeploymentField &&
+ deploymentName &&
+ deploymentName !== model && { deploymentName }),
+ model,
+ },
);
// Convert null to undefined for model params to prevent sending null values to API
diff --git a/src/services/chat/mecha/clientModelRuntime.test.ts b/src/services/chat/mecha/clientModelRuntime.test.ts
index a5fc1979236..87d3b818546 100644
--- a/src/services/chat/mecha/clientModelRuntime.test.ts
+++ b/src/services/chat/mecha/clientModelRuntime.test.ts
@@ -121,11 +121,10 @@ describe('ModelRuntimeOnClient', () => {
expect(runtime['_runtime'].baseURL).toBe('user-openai-endpoint');
});
- it('Azure provider: with apiKey, apiVersion, endpoint', async () => {
+ it('Azure provider: with apiKey and endpoint', async () => {
await mockProviderKeyVaults(ModelProvider.Azure, {
apiKey: 'user-azure-key',
- endpoint: 'user-azure-endpoint',
- apiVersion: '2024-06-01',
+ endpoint: 'https://user-azure.openai.azure.com',
});
const runtime = await initializeWithClientStore({
@@ -134,6 +133,7 @@ describe('ModelRuntimeOnClient', () => {
});
expect(runtime).toBeInstanceOf(ModelRuntime);
expect(runtime['_runtime']).toBeInstanceOf(LobeAzureOpenAI);
+ expect(runtime['_runtime'].baseURL).toBe('https://user-azure.openai.azure.com/openai/v1');
});
it('Google provider: with apiKey', async () => {