🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(model-runtime): route Azure transcription via deployments path (#20117)
YuTengjing6d5c7fded1dc
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex 861adcbb8c9..70a99a64440 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -1369,6 +1369,14 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an}}+ /**+ * Client used for `audio.transcriptions`. Providers whose transcription+ * endpoint differs from their chat base URL (e.g. Azure deployments) override it.+ */+ protected getTranscriptionClient(): OpenAI {+ return this.client;+ }+async transcribe(payload: ASRPayload, options?: ASROptions): Promise<ASRResponse> {const log = debug(`${this.logPrefix}:transcribe`);const { file, fileName, model, language, prompt, responseFormat, temperature } = payload;@@ -1381,7 +1389,7 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = anconst uploadFile =file instanceof File ? file : new File([file], fileName || 'audio', { type: file.type });- const transcription = await this.client.audio.transcriptions.create(+ const transcription = await this.getTranscriptionClient().audio.transcriptions.create({file: uploadFile,language,diff --git a/packages/model-runtime/src/providers/azureOpenai/index.test.ts b/packages/model-runtime/src/providers/azureOpenai/index.test.tsindex 8600b2d9d92..670561a846f 100644--- a/packages/model-runtime/src/providers/azureOpenai/index.test.ts+++ b/packages/model-runtime/src/providers/azureOpenai/index.test.ts@@ -527,6 +527,125 @@ describe('LobeAzureOpenAI', () => {});});+ describe('transcribe', () => {+ const file = new File([new Uint8Array([1, 2, 3])], 'speech.m4a', { type: 'audio/mp4' });++ /** The SDK probes FormData support with a `data:` fetch before the real POST. */+ const getTranscriptionRequest = (fetch: Mock): [string, RequestInit] => {+ const calls = fetch.mock.calls.filter(([, init]) => init?.method === 'POST');+ expect(calls).toHaveLength(1);+ return calls[0] as [string, RequestInit];+ };++ beforeEach(() => {+ vi.spyOn(getModelPricingModule, 'getModelPricing').mockResolvedValue(undefined);+ });++ const createTranscribeInstance = (+ fetch: Mock,+ options: { baseURL?: string; modelIdMapping?: Record<string, string> } & Record<+ string,+ unknown+ > = {},+ ) =>+ new LobeAzureOpenAI({+ apiKey: 'test_key',+ fetch,+ maxRetries: 0,+ ...options,+ baseURL: options.baseURL ?? 'https://test.cognitiveservices.azure.com/',+ });++ it('should call the deployments transcription path with api-version and api-key', async () => {+ const fetch = vi.fn().mockResolvedValue(+ Response.json({+ text: 'ä½ å¥½ä¸–ç•Œ',+ usage: { input_tokens: 151, output_tokens: 12, total_tokens: 163, type: 'tokens' },+ }),+ );+ const onUsage = vi.fn();+ const runtime = createTranscribeInstance(fetch);++ const result = await runtime.transcribe({ file, model: 'gpt-4o-transcribe' }, { onUsage });++ expect(result).toEqual({ text: 'ä½ å¥½ä¸–ç•Œ' });+ const [url, init] = getTranscriptionRequest(fetch);+ const requestURL = new URL(url);+ expect(requestURL.origin + requestURL.pathname).toBe(+ 'https://test.cognitiveservices.azure.com/openai/deployments/gpt-4o-transcribe/audio/transcriptions',+ );+ expect(requestURL.searchParams.get('api-version')).toBe('2025-03-01-preview');+ expect(new Headers(init.headers).get('api-key')).toBe('test_key');+ expect(onUsage).toHaveBeenCalledWith(+ expect.objectContaining({ inputAudioTokens: 151, totalInputTokens: 151 }),+ );+ });++ it('should use the mapped deployment name and keep a custom openai path prefix', async () => {+ const fetch = vi.fn().mockResolvedValue(Response.json({ text: 'ok' }));+ const runtime = createTranscribeInstance(fetch, {+ baseURL: 'https://test.openai.azure.com/openai/v1/',+ modelIdMapping: { 'gpt-4o-mini-transcribe': 'prod-mini-transcribe' },+ });++ await runtime.transcribe({ file, model: 'gpt-4o-mini-transcribe' });++ const requestURL = new URL(getTranscriptionRequest(fetch)[0]);+ expect(requestURL.pathname).toBe(+ '/openai/deployments/prod-mini-transcribe/audio/transcriptions',+ );+ });++ it('should forward client options such as dangerouslyAllowBrowser (client BYOK path)', async () => {+ // The OpenAI SDK refuses to construct a client in a browser without this flag.+ vi.stubGlobal('window', { document: {} });+ try {+ const fetch = vi.fn().mockResolvedValue(Response.json({ text: 'ok' }));+ const runtime = createTranscribeInstance(fetch, { dangerouslyAllowBrowser: true });++ await expect(runtime.transcribe({ file, model: 'gpt-4o-transcribe' })).resolves.toEqual({+ text: 'ok',+ });+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it('should keep chat requests on the v1 surface', async () => {+ const fetch = vi.fn().mockResolvedValue(Response.json({ text: 'ok' }));+ const runtime = createTranscribeInstance(fetch);++ await runtime.transcribe({ file, model: 'gpt-4o-transcribe' });++ expect(runtime.baseURL).toBe('https://test.cognitiveservices.azure.com/openai/v1');+ expect(runtime.client.baseURL).toBe('https://test.cognitiveservices.azure.com/openai/v1');+ });++ it('should attach the deployment id and deployments endpoint to DeploymentNotFound errors', async () => {+ const fetch = vi+ .fn()+ .mockResolvedValue(+ Response.json(+ { error: { code: 'DeploymentNotFound', message: 'Deployment not found' } },+ { status: 404 },+ ),+ );+ const runtime = createTranscribeInstance(fetch, {+ modelIdMapping: { 'gpt-4o-transcribe': 'prod-transcribe' },+ });++ await expect(runtime.transcribe({ file, model: 'gpt-4o-transcribe' })).rejects.toMatchObject({+ error: expect.objectContaining({+ code: 'DeploymentNotFound',+ deployId: 'prod-transcribe',+ }),+ // Transcription bypasses the `/openai/v1` baseURL, so the error must not report it.+ endpoint: 'https://***.cognitiveservices.azure.com/openai',+ provider: 'azure',+ });+ });+ });+describe('createImage', () => {beforeEach(() => {// ensure images namespace exists and is spy-ablediff --git a/packages/model-runtime/src/providers/azureOpenai/index.ts b/packages/model-runtime/src/providers/azureOpenai/index.tsindex 25b798024fd..182be3224e2 100644--- a/packages/model-runtime/src/providers/azureOpenai/index.ts+++ b/packages/model-runtime/src/providers/azureOpenai/index.ts@@ -1,11 +1,18 @@import debug from 'debug';import { ModelProvider } from 'model-bank';import type OpenAI from 'openai';+import { AzureOpenAI } from 'openai';import { pruneReasoningPayload } from '../../core/contextBuilders/openai';import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';import { refineErrorCode } from '../../errors';-import type { ChatMethodOptions, ChatStreamPayload } from '../../types';+import type {+ ASROptions,+ ASRPayload,+ ASRResponse,+ ChatMethodOptions,+ ChatStreamPayload,+} from '../../types';import { AgentRuntimeErrorType } from '../../types/error';import type { CreateImagePayload } from '../../types/image';import { AgentRuntimeError } from '../../utils/createError';@@ -73,6 +80,15 @@ const normalizeAzureBaseURL = (value?: string) => {return url.toString().replace(/\/$/, '');};+/**+ * Azure's `/openai/v1` compatible surface returns 404 `DeploymentNotFound` for+ * transcription deployments (`gpt-4o-transcribe` family), so transcription must+ * use the classic `/openai/deployments/{deployment}/audio/transcriptions` path,+ * which requires an explicit `api-version`.+ * @see https://learn.microsoft.com/azure/ai-foundry/openai/reference-preview+ */+const AZURE_TRANSCRIPTION_API_VERSION = '2025-03-01-preview';+const maskSensitiveUrl = (url: string) => {const regex = /^(https:\/\/)([^.]+)(\.(?:openai\.azure\.com|cognitiveservices\.azure\.com).*)$/;@@ -196,6 +212,8 @@ const BaseAzureOpenAI = createOpenAICompatibleRuntime({});export class LobeAzureOpenAI extends BaseAzureOpenAI {+ private transcriptionClient?: AzureOpenAI;+constructor(options: Record<string, any> = {}) {const { endpoint, ...rest } = options;const baseURL = normalizeAzureBaseURL(rest.baseURL ?? endpoint);@@ -214,6 +232,45 @@ export class LobeAzureOpenAI extends BaseAzureOpenAI {}}+ async transcribe(payload: ASRPayload, options?: ASROptions): Promise<ASRResponse> {+ try {+ return await super.transcribe(payload, options);+ } catch (error) {+ const payloadError = this.attachDeploymentId(error, this.getMappedModelId(payload.model));++ // `handleError` reports `this.baseURL` (`/openai/v1`), but transcription went to the+ // deployments path — report the endpoint that was actually called.+ throw payloadError && typeof payloadError === 'object'+ ? { ...payloadError, endpoint: maskSensitiveUrl(this.transcriptionBaseURL) }+ : payloadError;+ }+ }++ /** `this.baseURL` is normalized to `.../openai/v1`; deployments live under `.../openai`. */+ private get transcriptionBaseURL() {+ return this.baseURL.replace(/\/v1$/, '');+ }++ /**+ * `AzureOpenAI` rewrites `/audio/transcriptions` to+ * `/deployments/{model}/audio/transcriptions` using the request `model`+ * (already mapped to the deployment name) and appends `api-version`.+ *+ * Forwards every client option the chat client received (e.g. `dangerouslyAllowBrowser`+ * for the client BYOK runtime, `maxRetries`, `timeout`); only the endpoint and+ * `api-version` differ.+ */+ protected getTranscriptionClient(): OpenAI {+ this.transcriptionClient ??= new AzureOpenAI({+ ...this._options,+ apiKey: this._options.apiKey,+ apiVersion: AZURE_TRANSCRIPTION_API_VERSION,+ baseURL: this.transcriptionBaseURL,+ });++ return this.transcriptionClient;+ }+async createImage(payload: CreateImagePayload) {const { model, params } = payload;const requestModel = this.getMappedModelId(model);