@ai-sdk/azure 4.0.86 → 4.0.89
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/dist/index.d.ts +20 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +257 -13
- package/dist/index.js.map +1 -1
- package/docs/04-azure.mdx +103 -18
- package/package.json +5 -5
- package/src/azure-openai-provider.ts +103 -18
- package/src/azure-speech-model-options.ts +33 -0
- package/src/azure-speech-speech-model-options.ts +27 -0
- package/src/azure-speech-speech-model.ts +282 -0
- package/src/azure-speech-transcription-model.ts +6 -5
- package/src/azure-transcription-model-options.ts +13 -3
- package/src/index.ts +1 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/azure-openai-tools.ts","../src/azure-speech-transcription-model-options.ts","../src/azure-transcription-model-options.ts","../src/azure-speech-transcription-model.ts","../src/version.ts","../src/azure-openai-provider.ts"],"sourcesContent":["import {\n codeInterpreter,\n fileSearch,\n imageGeneration,\n webSearch,\n webSearchPreview,\n} from '@ai-sdk/openai/internal';\n\nexport const azureOpenaiTools: {\n codeInterpreter: typeof codeInterpreter;\n fileSearch: typeof fileSearch;\n imageGeneration: typeof imageGeneration;\n webSearch: typeof webSearch;\n webSearchPreview: typeof webSearchPreview;\n} = {\n codeInterpreter,\n fileSearch,\n imageGeneration,\n webSearch,\n webSearchPreview,\n};\n","import {\n lazySchema,\n zodSchema,\n type InferSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n// Strict objects reject unknown keys (e.g. `diarization.maxSpeakers`, which\n// MAI-Transcribe-2 does not support) instead of silently dropping them.\nexport const azureSpeechTranscriptionModelOptionsShape = () => ({\n /**\n * Timing granularity. Defaults to `segment` so that transcription results\n * include timed segments (Azure's own default is `none`).\n */\n timestamps: z.enum(['word', 'segment', 'none']).optional(),\n\n /**\n * `verbatim` keeps fillers and false starts, `clean` removes them.\n * Azure defaults to `verbatim`.\n */\n transcribeStyle: z.enum(['verbatim', 'clean']).optional(),\n\n /**\n * Forces a single language, e.g. `['en']`. Omit for automatic language\n * detection and code switching.\n */\n locales: z.array(z.string()).length(1).optional(),\n\n /**\n * Speaker diarization. Speaker IDs are available in provider metadata.\n */\n diarization: z.strictObject({ enabled: z.boolean() }).optional(),\n\n /**\n * Keyword biasing for names and domain terminology.\n */\n phraseList: z.strictObject({ phrases: z.array(z.string()) }).optional(),\n});\n\nexport const azureSpeechTranscriptionModelOptions = lazySchema(() =>\n zodSchema(z.strictObject(azureSpeechTranscriptionModelOptionsShape())),\n);\n\nexport type AzureTranscriptionModelSpeechOptions = InferSchema<\n typeof azureSpeechTranscriptionModelOptions\n>;\n","import {\n lazySchema,\n zodSchema,\n type InferSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { azureSpeechTranscriptionModelOptionsShape } from './azure-speech-transcription-model-options';\n\nexport const azureTranscriptionModelOptions = lazySchema(() =>\n zodSchema(\n z.strictObject({\n /**\n * API to use. Defaults to Speech for MAI-Transcribe-2, OpenAI otherwise.\n */\n api: z.enum(['openai', 'speech']).optional(),\n ...azureSpeechTranscriptionModelOptionsShape(),\n }),\n ),\n);\n\nexport type AzureTranscriptionModelOptions = InferSchema<\n typeof azureTranscriptionModelOptions\n>;\n\nexport function isMAITranscribe2(modelId: string): boolean {\n return modelId.toLowerCase() === 'mai-transcribe-2';\n}\n","import type { TranscriptionModelV4 } from '@ai-sdk/provider';\nimport {\n combineHeaders,\n convertBase64ToUint8Array,\n createJsonErrorResponseHandler,\n createJsonResponseHandler,\n mediaTypeToExtension,\n postFormDataToApi,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport type { AzureTranscriptionProviderMetadata } from './azure-transcription-provider-metadata';\nimport type { AzureTranscriptionModelSpeechOptions } from './azure-speech-transcription-model-options';\nimport { isMAITranscribe2 } from './azure-transcription-model-options';\n\nexport class AzureSpeechTranscriptionModel implements TranscriptionModelV4 {\n readonly specificationVersion = 'v4';\n readonly provider = 'azure.transcription';\n\n constructor(\n readonly modelId: string,\n private readonly config: {\n url: () => string;\n headers: () => Record<string, string | undefined>;\n fetch?: FetchFunction;\n },\n ) {}\n\n async doGenerate(\n options: Parameters<TranscriptionModelV4['doGenerate']>[0],\n azureOptions: AzureTranscriptionModelSpeechOptions = {},\n ): Promise<Awaited<ReturnType<TranscriptionModelV4['doGenerate']>>> {\n const timestamp = new Date();\n const formData = new FormData();\n formData.append(\n 'audio',\n new Blob(\n [\n typeof options.audio === 'string'\n ? convertBase64ToUint8Array(options.audio)\n : options.audio,\n ],\n { type: options.mediaType },\n ),\n `audio.${mediaTypeToExtension(options.mediaType)}`,\n );\n formData.append(\n 'definition',\n JSON.stringify({\n enhancedMode: {\n enabled: true,\n model: isMAITranscribe2(this.modelId)\n ? 'MAI-Transcribe-2'\n : this.modelId,\n modelOptions: {\n timestamps: azureOptions.timestamps ?? 'segment',\n transcribeStyle: azureOptions.transcribeStyle,\n },\n },\n locales: azureOptions.locales,\n diarization: azureOptions.diarization,\n phraseList: azureOptions.phraseList,\n }),\n );\n\n const { value, rawValue, responseHeaders } = await postFormDataToApi({\n url: this.config.url(),\n headers: combineHeaders(this.config.headers(), options.headers),\n formData,\n abortSignal: options.abortSignal,\n fetch: this.config.fetch,\n failedResponseHandler: createJsonErrorResponseHandler({\n errorSchema: z.union([\n z.object({ error: z.object({ message: z.string() }) }),\n z.object({ message: z.string() }),\n ]),\n errorToMessage: data =>\n 'error' in data ? data.error.message : data.message,\n }),\n successfulResponseHandler: createJsonResponseHandler(responseSchema),\n });\n\n const phrases = value.phrases ?? [];\n // Consider every reported locale so mixed results (e.g. en + fil) are not\n // collapsed to one language; only ISO-639-1 codes are reported.\n const languages = new Set(\n phrases.flatMap(phrase =>\n phrase.locale ? [phrase.locale.split('-')[0].toLowerCase()] : [],\n ),\n );\n const [language] = languages;\n const reportedLanguage =\n languages.size === 1 && /^[a-z]{2}$/.test(language)\n ? language\n : undefined;\n\n return {\n text: value.combinedPhrases.map(phrase => phrase.text).join(' '),\n segments: phrases.flatMap(phrase =>\n phrase.offsetMilliseconds != null && phrase.durationMilliseconds != null\n ? [\n {\n text: phrase.text,\n startSecond: phrase.offsetMilliseconds / 1000,\n endSecond:\n (phrase.offsetMilliseconds + phrase.durationMilliseconds) /\n 1000,\n },\n ]\n : [],\n ),\n language: reportedLanguage,\n durationInSeconds:\n value.durationMilliseconds != null\n ? value.durationMilliseconds / 1000\n : undefined,\n warnings: [],\n providerMetadata: {\n azure: { phrases },\n } satisfies AzureTranscriptionProviderMetadata,\n response: {\n timestamp,\n modelId: this.modelId,\n headers: responseHeaders,\n body: rawValue,\n },\n };\n }\n}\n\nconst responseSchema = z.object({\n combinedPhrases: z.array(z.object({ text: z.string() })),\n durationMilliseconds: z.number().nullish(),\n phrases: z\n .array(\n z.object({\n text: z.string(),\n offsetMilliseconds: z.number().nullish(),\n durationMilliseconds: z.number().nullish(),\n locale: z.string().nullish(),\n speaker: z.number().nullish(),\n confidence: z.number().nullish(),\n words: z\n .array(\n z.object({\n text: z.string(),\n offsetMilliseconds: z.number().nullish(),\n durationMilliseconds: z.number().nullish(),\n }),\n )\n .nullish(),\n }),\n )\n .nullish(),\n});\n","// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n","import {\n OpenAIChatLanguageModel,\n OpenAICompletionLanguageModel,\n OpenAIEmbeddingModel,\n OpenAIImageModel,\n OpenAIResponsesLanguageModel,\n OpenAISpeechModel,\n OpenAITranscriptionModel,\n} from '@ai-sdk/openai/internal';\nimport { DeepSeekChatLanguageModel } from '@ai-sdk/deepseek/internal';\nimport {\n InvalidArgumentError,\n UnsupportedFunctionalityError,\n type EmbeddingModelV4,\n type LanguageModelV4,\n type ProviderV4,\n type ImageModelV4,\n type SpeechModelV4,\n type TranscriptionModelV4,\n} from '@ai-sdk/provider';\nimport {\n loadApiKey,\n loadSetting,\n normalizeHeaders,\n parseProviderOptions,\n serializeModelOptions,\n WORKFLOW_DESERIALIZE,\n WORKFLOW_SERIALIZE,\n withoutTrailingSlash,\n withUserAgentSuffix,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { azureOpenaiTools } from './azure-openai-tools';\nimport { AzureSpeechTranscriptionModel } from './azure-speech-transcription-model';\nimport {\n azureTranscriptionModelOptions,\n isMAITranscribe2,\n} from './azure-transcription-model-options';\nimport { VERSION } from './version';\n\nexport interface AzureOpenAIProvider extends ProviderV4 {\n (deploymentId: string): LanguageModelV4;\n\n /**\n * Creates an Azure OpenAI responses API model for text generation.\n */\n languageModel(deploymentId: string): LanguageModelV4;\n\n /**\n * Creates an Azure OpenAI chat model for text generation.\n */\n chat(deploymentId: string): LanguageModelV4;\n\n /**\n * Creates an Azure-hosted DeepSeek chat model for text generation.\n */\n deepseek(deploymentId: string): LanguageModelV4;\n\n /**\n * Creates an Azure OpenAI responses API model for text generation.\n */\n responses(deploymentId: string): LanguageModelV4;\n\n /**\n * Creates an Azure OpenAI completion model for text generation.\n */\n completion(deploymentId: string): LanguageModelV4;\n\n /**\n * Creates an Azure OpenAI model for text embeddings.\n */\n embedding(deploymentId: string): EmbeddingModelV4;\n\n /**\n * Creates an Azure OpenAI model for text embeddings.\n */\n embeddingModel(deploymentId: string): EmbeddingModelV4;\n\n /**\n * @deprecated Use `embedding` instead.\n */\n textEmbedding(deploymentId: string): EmbeddingModelV4;\n\n /**\n * @deprecated Use `embeddingModel` instead.\n */\n textEmbeddingModel(deploymentId: string): EmbeddingModelV4;\n\n /**\n * Creates an Azure OpenAI DALL-E model for image generation.\n */\n image(deploymentId: string): ImageModelV4;\n\n /**\n * Creates an Azure OpenAI DALL-E model for image generation.\n */\n imageModel(deploymentId: string): ImageModelV4;\n\n /**\n * Creates an Azure transcription model. MAI-Transcribe-2 uses the Speech API\n * by default; other IDs use OpenAI. Override with providerOptions.azure.api.\n */\n transcription(deploymentId: string): TranscriptionModelV4;\n\n /**\n * Creates an Azure transcription model. Alias of `transcription`.\n */\n transcriptionModel(deploymentId: string): TranscriptionModelV4;\n\n /**\n * Creates an Azure OpenAI model for speech generation.\n */\n speech(deploymentId: string): SpeechModelV4;\n\n /**\n * AzureOpenAI-specific tools.\n */\n tools: typeof azureOpenaiTools;\n}\n\nexport interface AzureOpenAIProviderSettings {\n /**\n * Name of the Azure OpenAI resource. Either this or `baseURL` can be used.\n *\n * The resource name is used in the assembled URL: `https://{resourceName}.openai.azure.com/openai/v1{path}`.\n * It must be a single DNS label (letters, digits, and hyphens).\n */\n resourceName?: string;\n\n /**\n * Use a different URL prefix for API calls, e.g. to use proxy servers. Either this or `resourceName` can be used.\n * When a baseURL is provided, the resourceName is ignored.\n *\n * With an unversioned Azure OpenAI baseURL, the resolved URL is `{baseURL}/v1{path}`.\n * Azure OpenAI base URLs that already end in `/openai/v1` are used as-is.\n * With a non-Azure custom gateway baseURL, the resolved URL is `{baseURL}{path}`.\n */\n baseURL?: string;\n\n /**\n * API key for authenticating requests.\n */\n apiKey?: string;\n\n /**\n * A function that returns an access token for Microsoft Entra\n * (formerly known as Azure Active Directory), which will be invoked\n * on every request.\n */\n tokenProvider?: (() => Promise<string>) | undefined;\n\n /**\n * Custom headers to include in the requests.\n */\n headers?: Record<string, string>;\n\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept requests,\n * or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\n * Custom api version to use. Defaults to `v1`.\n * Complete v1 base URLs are used as-is.\n */\n apiVersion?: string;\n\n /**\n * Use deployment-based URLs for specific model types. Set to true to use legacy deployment format:\n * `{baseURL}/deployments/{deploymentId}{path}?api-version={apiVersion}` instead of\n * `{baseURL}/v1{path}?api-version={apiVersion}`.\n */\n useDeploymentBasedUrls?: boolean;\n\n /**\n * URL prefix for Azure Speech transcription (MAI-Transcribe-2), e.g. a\n * regional endpoint like `https://eastus.api.cognitive.microsoft.com`.\n * Defaults to `https://{resourceName}.cognitiveservices.azure.com`.\n * Speech requests do not use `baseURL` or `apiVersion`.\n */\n speechBaseURL?: string;\n}\n\nfunction getAzureOpenAIBaseURLInfo(baseURL: string | undefined) {\n if (baseURL == null) {\n return {\n isAzureOpenAI: true,\n isFoundryProject: false,\n isVersioned: false,\n };\n }\n\n const url = new URL(baseURL);\n const hostname = url.hostname;\n const isAzureOpenAI =\n hostname.endsWith('.openai.azure.com') ||\n hostname.endsWith('.services.ai.azure.com') ||\n hostname.endsWith('.cognitiveservices.azure.com');\n const pathname = url.pathname.replace(/\\/+$/, '');\n\n return {\n isAzureOpenAI,\n isFoundryProject:\n hostname.endsWith('.services.ai.azure.com') &&\n pathname.startsWith('/api/projects/'),\n isVersioned: isAzureOpenAI && pathname.toLowerCase().endsWith('/openai/v1'),\n };\n}\n\n/**\n * Create an Azure OpenAI provider instance.\n */\nexport function createAzure(\n options: AzureOpenAIProviderSettings = {},\n): AzureOpenAIProvider {\n const tokenProvider = options.tokenProvider;\n\n if (options.apiKey && tokenProvider) {\n throw new InvalidArgumentError({\n argument: 'apiKey/tokenProvider',\n message:\n 'Both apiKey and tokenProvider were provided. Please use only one authentication method.',\n });\n }\n\n const getHeaders = (api: 'openai' | 'speech' = 'openai') => {\n const authHeaders = tokenProvider\n ? {}\n : {\n [api === 'speech' ? 'Ocp-Apim-Subscription-Key' : 'api-key']:\n loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: 'AZURE_API_KEY',\n description: api === 'speech' ? 'Azure Speech' : 'Azure OpenAI',\n }),\n };\n\n return withUserAgentSuffix(\n {\n ...authHeaders,\n ...options.headers,\n },\n `ai-sdk-azure/${VERSION}`,\n );\n };\n\n const fetch: FetchFunction | undefined = tokenProvider\n ? async (input, init) => {\n const headers = normalizeHeaders(init?.headers);\n\n if (headers.authorization == null) {\n headers.authorization = `Bearer ${await tokenProvider()}`;\n }\n\n return (options.fetch ?? globalThis.fetch)(input, {\n ...init,\n headers,\n });\n }\n : options.fetch;\n\n const getResourceName = () => {\n const resourceName = loadSetting({\n settingValue: options.resourceName,\n settingName: 'resourceName',\n environmentVariableName: 'AZURE_RESOURCE_NAME',\n description: 'Azure OpenAI resource name',\n });\n\n // The resource name becomes part of the request host, so only a DNS label\n // is accepted (e.g. `user@internal:8080/#` would rewrite the host).\n if (!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(resourceName)) {\n throw new InvalidArgumentError({\n argument: 'resourceName',\n message:\n 'Invalid Azure resource name. Expected a single DNS label (letters, digits, and hyphens). Use `baseURL` for custom endpoints.',\n });\n }\n\n return resourceName;\n };\n\n const apiVersion = options.apiVersion ?? 'v1';\n const {\n isAzureOpenAI,\n isFoundryProject,\n isVersioned: isAzureOpenAIVersioned,\n } = getAzureOpenAIBaseURLInfo(options.baseURL);\n\n const url = ({ path, modelId }: { path: string; modelId: string }) => {\n const baseUrlPrefix = withoutTrailingSlash(\n options.baseURL ?? `https://${getResourceName()}.openai.azure.com/openai`,\n );\n\n let fullUrl: URL;\n if (options.useDeploymentBasedUrls) {\n // Use deployment-based format for compatibility with certain Azure OpenAI models\n fullUrl = new URL(`${baseUrlPrefix}/deployments/${modelId}${path}`);\n } else if (!isAzureOpenAI || isAzureOpenAIVersioned) {\n // Custom gateways can own Azure routing and versioning themselves.\n // Complete Azure OpenAI v1 URLs also own their versioning.\n fullUrl = new URL(`${baseUrlPrefix}${path}`);\n } else {\n // Use v1 API format - no deployment ID in URL\n fullUrl = new URL(`${baseUrlPrefix}/v1${path}`);\n }\n\n if (\n options.useDeploymentBasedUrls ||\n (isAzureOpenAI && !isAzureOpenAIVersioned && !isFoundryProject)\n ) {\n fullUrl.searchParams.set('api-version', apiVersion);\n }\n\n return fullUrl.toString();\n };\n\n const createChatModel = (deploymentName: string) =>\n new OpenAIChatLanguageModel(deploymentName, {\n provider: 'azure.chat',\n url,\n headers: getHeaders,\n fetch,\n });\n\n const createDeepSeekModel = (deploymentName: string) =>\n new DeepSeekChatLanguageModel(deploymentName, {\n provider: 'azure.deepseek',\n url,\n headers: getHeaders,\n fetch,\n supportsPenaltySampling: true,\n supportsThinking: false,\n // json_object with thinking enabled makes Azure return the JSON in reasoning_content with empty content\n supportsStructuredOutputs: true,\n });\n\n const createCompletionModel = (modelId: string) =>\n new OpenAICompletionLanguageModel(modelId, {\n provider: 'azure.completion',\n url,\n headers: getHeaders,\n fetch,\n });\n\n const createEmbeddingModel = (modelId: string) =>\n new OpenAIEmbeddingModel(modelId, {\n provider: 'azure.embeddings',\n headers: getHeaders,\n url,\n fetch,\n });\n\n const createResponsesModel = (modelId: string) =>\n new OpenAIResponsesLanguageModel(modelId, {\n provider: 'azure.responses',\n url,\n headers: getHeaders,\n fetch,\n explicitMessageItemType: isFoundryProject,\n // Soft-deprecated. TODO: remove in v8\n fileIdPrefixes: ['assistant-'],\n });\n\n const createImageModel = (modelId: string) =>\n new OpenAIImageModel(modelId, {\n provider: 'azure.image',\n url,\n headers: getHeaders,\n fetch,\n // Azure model IDs are user-defined deployment names, so OpenAI model\n // family capabilities cannot be inferred from them.\n imageInputCapabilities: {\n supportsFileInputs: undefined,\n supportsMaskInputs: undefined,\n },\n });\n\n const createTranscriptionModel = (modelId: string) =>\n new AzureTranscriptionModel(\n modelId,\n options,\n new OpenAITranscriptionModel(modelId, {\n provider: 'azure.transcription',\n url,\n headers: getHeaders,\n fetch,\n }),\n new AzureSpeechTranscriptionModel(modelId, {\n url: () =>\n `${\n withoutTrailingSlash(options.speechBaseURL) ??\n `https://${getResourceName()}.cognitiveservices.azure.com`\n }/speechtotext/transcriptions:transcribe?api-version=2025-10-15`,\n headers: () => getHeaders('speech'),\n fetch,\n }),\n );\n\n const createSpeechModel = (modelId: string) =>\n new OpenAISpeechModel(modelId, {\n provider: 'azure.speech',\n url,\n headers: getHeaders,\n fetch,\n });\n\n const provider = function (deploymentId: string) {\n if (new.target) {\n throw new Error(\n 'The Azure OpenAI model function cannot be called with the new keyword.',\n );\n }\n\n return createResponsesModel(deploymentId);\n };\n\n provider.specificationVersion = 'v4' as const;\n provider.languageModel = createResponsesModel;\n provider.chat = createChatModel;\n provider.deepseek = createDeepSeekModel;\n provider.completion = createCompletionModel;\n provider.embedding = createEmbeddingModel;\n provider.embeddingModel = createEmbeddingModel;\n provider.textEmbedding = createEmbeddingModel;\n provider.textEmbeddingModel = createEmbeddingModel;\n provider.image = createImageModel;\n provider.imageModel = createImageModel;\n provider.responses = createResponsesModel;\n provider.transcription = createTranscriptionModel;\n provider.transcriptionModel = createTranscriptionModel;\n provider.speech = createSpeechModel;\n provider.tools = azureOpenaiTools;\n return provider;\n}\n\n/**\n * Default Azure OpenAI provider instance.\n */\nexport const azure = createAzure();\n\n// Resolves the API per request: providerOptions also reach this model via Gateway.\nclass AzureTranscriptionModel implements TranscriptionModelV4 {\n readonly specificationVersion = 'v4';\n readonly provider = 'azure.transcription';\n\n constructor(\n readonly modelId: string,\n private readonly config: AzureOpenAIProviderSettings,\n private readonly openai: OpenAITranscriptionModel,\n private readonly speech: AzureSpeechTranscriptionModel,\n ) {}\n\n static [WORKFLOW_SERIALIZE](model: AzureTranscriptionModel) {\n return serializeModelOptions({\n modelId: model.modelId,\n config: model.config,\n });\n }\n\n static [WORKFLOW_DESERIALIZE](options: {\n modelId: string;\n config: AzureOpenAIProviderSettings;\n }) {\n return createAzure(options.config).transcription(options.modelId);\n }\n\n async doGenerate(options: Parameters<TranscriptionModelV4['doGenerate']>[0]) {\n const { api, ...speechOptions } = await this.getOptions(\n options.providerOptions,\n );\n if (api === 'speech') {\n return this.speech.doGenerate(options, speechOptions);\n }\n\n const result = await this.openai.doGenerate(options);\n return {\n ...result,\n warnings: [\n ...result.warnings,\n ...Object.keys(speechOptions).map(key => ({\n type: 'unsupported' as const,\n feature: `providerOptions.azure.${key}`,\n details: 'This option requires the Azure Speech API.',\n })),\n ],\n };\n }\n\n async doStream(\n options: Parameters<NonNullable<TranscriptionModelV4['doStream']>>[0],\n ) {\n const { api } = await this.getOptions(options.providerOptions);\n if (api === 'speech') {\n throw new UnsupportedFunctionalityError({\n functionality: 'streaming transcription with the Azure Speech API',\n });\n }\n return this.openai.doStream(options);\n }\n\n private async getOptions(\n providerOptions: Parameters<\n TranscriptionModelV4['doGenerate']\n >[0]['providerOptions'],\n ) {\n const options = await parseProviderOptions({\n provider: 'azure',\n providerOptions,\n schema: azureTranscriptionModelOptions,\n });\n return {\n ...options,\n api:\n options?.api ?? (isMAITranscribe2(this.modelId) ? 'speech' : 'openai'),\n };\n }\n}\n"],"mappings":";;;;;;AAQA,MAAa,mBAMT;CACF;CACA;CACA;CACA;CACA;AACF;;;ACXA,MAAa,mDAAmD;;;;;CAK9D,YAAY,EAAE,KAAK;EAAC;EAAQ;EAAW;CAAM,CAAC,CAAC,CAAC,SAAS;;;;;CAMzD,iBAAiB,EAAE,KAAK,CAAC,YAAY,OAAO,CAAC,CAAC,CAAC,SAAS;;;;;CAMxD,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS;;;;CAKhD,aAAa,EAAE,aAAa,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,SAAS;;;;CAK/D,YAAY,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS;AACxE;AAEoD,iBAClD,UAAU,EAAE,aAAa,0CAA0C,CAAC,CAAC,CACvE;;;ACjCA,MAAa,iCAAiC,iBAC5C,UACE,EAAE,aAAa;;;;CAIb,KAAK,EAAE,KAAK,CAAC,UAAU,QAAQ,CAAC,CAAC,CAAC,SAAS;CAC3C,GAAG,0CAA0C;AAC/C,CAAC,CACH,CACF;AAMA,SAAgB,iBAAiB,SAA0B;CACzD,OAAO,QAAQ,YAAY,MAAM;AACnC;;;ACXA,IAAa,gC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KAAA,WAAA;CAOjB;CAEH,QAAQ,oBAAoB,OAAgC;EAC1D,OAAO,sBAAsB;GAC3B,SAAS,MAAM;GACf,QAAQ,MAAM;EAChB,CAAC;CACH;CAEA,QAAQ,sBAAsB,SAG3B;EACD,OAAO,YAAY,QAAQ,MAAM,CAAC,CAAC,cAAc,QAAQ,OAAO;CAClE;CAEA,MAAM,WAAW,SAA4D;EAC3E,MAAM,EAAE,KAAK,GAAG,kBAAkB,MAAM,KAAK,WAC3C,QAAQ,eACV;EACA,IAAI,QAAQ,UACV,OAAO,KAAK,OAAO,WAAW,SAAS,aAAa;EAGtD,MAAM,SAAS,MAAM,KAAK,OAAO,WAAW,OAAO;EACnD,OAAO;GACL,GAAG;GACH,UAAU,CACR,GAAG,OAAO,UACV,GAAG,OAAO,KAAK,aAAa,CAAC,CAAC,KAAI,SAAQ;IACxC,MAAM;IACN,SAAS,yBAAyB;IAClC,SAAS;GACX,EAAE,CACJ;EACF;CACF;CAEA,MAAM,SACJ,SACA;EACA,MAAM,EAAE,QAAQ,MAAM,KAAK,WAAW,QAAQ,eAAe;EAC7D,IAAI,QAAQ,UACV,MAAM,IAAI,8BAA8B,EACtC,eAAe,oDACjB,CAAC;EAEH,OAAO,KAAK,OAAO,SAAS,OAAO;CACrC;CAEA,MAAc,WACZ,iBAGA;EACA,MAAM,UAAU,MAAM,qBAAqB;GACzC,UAAU;GACV;GACA,QAAQ;EACV,CAAC;EACD,OAAO;GACL,GAAG;GACH,KACE,SAAS,QAAQ,iBAAiB,KAAK,OAAO,IAAI,WAAW;EACjE;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/azure-openai-tools.ts","../src/azure-speech-speech-model-options.ts","../src/azure-speech-model-options.ts","../src/azure-speech-speech-model.ts","../src/azure-speech-transcription-model-options.ts","../src/azure-transcription-model-options.ts","../src/azure-speech-transcription-model.ts","../src/version.ts","../src/azure-openai-provider.ts"],"sourcesContent":["import {\n codeInterpreter,\n fileSearch,\n imageGeneration,\n webSearch,\n webSearchPreview,\n} from '@ai-sdk/openai/internal';\n\nexport const azureOpenaiTools: {\n codeInterpreter: typeof codeInterpreter;\n fileSearch: typeof fileSearch;\n imageGeneration: typeof imageGeneration;\n webSearch: typeof webSearch;\n webSearchPreview: typeof webSearchPreview;\n} = {\n codeInterpreter,\n fileSearch,\n imageGeneration,\n webSearch,\n webSearchPreview,\n};\n","import {\n lazySchema,\n zodSchema,\n type InferSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport const azureSpeechSpeechModelOptionsShape = () => ({\n /**\n * Speaking style applied with `mstts:express-as`, e.g. `excited` or\n * `whispering`. Supported styles vary by voice.\n */\n style: z.string().min(1).optional(),\n\n /**\n * Intensity of `style`, from 0.01 to 2. Azure defaults to 1.\n */\n styleDegree: z.number().min(0.01).max(2).optional(),\n});\n\nexport const azureSpeechSpeechModelOptions = lazySchema(() =>\n zodSchema(z.strictObject(azureSpeechSpeechModelOptionsShape())),\n);\n\nexport type AzureSpeechModelSpeechOptions = InferSchema<\n typeof azureSpeechSpeechModelOptions\n>;\n","import {\n lazySchema,\n zodSchema,\n type InferSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { azureSpeechSpeechModelOptionsShape } from './azure-speech-speech-model-options';\n\nexport const azureSpeechModelOptions = lazySchema(() =>\n zodSchema(\n z.strictObject({\n /**\n * API to use. Defaults to Speech for MAI-Voice models, OpenAI otherwise.\n */\n api: z.enum(['openai', 'speech']).optional(),\n ...azureSpeechSpeechModelOptionsShape(),\n }),\n ),\n);\n\nexport type AzureSpeechModelOptions = InferSchema<\n typeof azureSpeechModelOptions\n>;\n\n// Azure voice-name suffixes by lowercase model ID.\nconst maiVoiceModels = new Map([\n ['mai-voice-2-flash', 'MAI-Voice-2-Flash'],\n ['mai-voice-2', 'MAI-Voice-2'],\n]);\n\nexport function getMAIVoiceModel(modelId: string) {\n return maiVoiceModels.get(modelId.toLowerCase());\n}\n","import {\n APICallError,\n type SharedV4Warning,\n type SpeechModelV4,\n} from '@ai-sdk/provider';\nimport {\n combineHeaders,\n createBinaryResponseHandler,\n extractResponseHeaders,\n postToApi,\n safeParseJSON,\n type FetchFunction,\n type ResponseHandler,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { getMAIVoiceModel } from './azure-speech-model-options';\nimport type { AzureSpeechModelSpeechOptions } from './azure-speech-speech-model-options';\n\nconst DEFAULT_VOICE = 'en-US-Harper';\n\n// Default voice per ISO 639-1 language; available on MAI-Voice-2 and\n// MAI-Voice-2-Flash.\nconst DEFAULT_VOICES = new Map([\n ['de', 'de-DE-Mia'],\n ['en', DEFAULT_VOICE],\n ['es', 'es-MX-Valeria'],\n ['fr', 'fr-FR-Soleil'],\n ['hi', 'hi-IN-Kavya'],\n ['hu', 'hu-HU-Lilla'],\n ['it', 'it-IT-Rosa'],\n ['ko', 'ko-KR-Haena'],\n ['nl', 'nl-NL-Fleur'],\n ['pt', 'pt-BR-Luana'],\n ['ro', 'ro-RO-Elena'],\n ['ru', 'ru-RU-Masha'],\n ['th', 'th-TH-Krit'],\n ['tr', 'tr-TR-Elif'],\n ['zh', 'zh-CN-Mei'],\n]);\nconst DEFAULT_OUTPUT_FORMAT = 'audio-24khz-160kbitrate-mono-mp3';\n\n// Shorthand formats for `outputFormat`; other X-Microsoft-OutputFormat values\n// (e.g. `audio-48khz-192kbitrate-mono-mp3`) are passed through unchanged.\nconst OUTPUT_FORMATS = new Map([\n ['mp3', DEFAULT_OUTPUT_FORMAT],\n ['opus', 'ogg-24khz-16bit-mono-opus'],\n ['pcm', 'raw-24khz-16bit-mono-pcm'],\n ['wav', 'riff-24khz-16bit-mono-pcm'],\n]);\nconst NATIVE_OUTPUT_FORMAT =\n /^(?:amr|audio|g722|ogg|raw|riff|webm)-[a-z0-9-]+$/;\n\n/**\n * Azure Speech text to speech with SSML. The model is appended to the voice\n * name, e.g. `en-US-Harper:MAI-Voice-2`.\n */\nexport class AzureSpeechSpeechModel implements SpeechModelV4 {\n readonly specificationVersion = 'v4';\n readonly provider = 'azure.speech';\n\n constructor(\n readonly modelId: string,\n private readonly config: {\n url: () => string;\n headers: () => Record<string, string | undefined>;\n fetch?: FetchFunction;\n _internal?: { currentDate?: () => Date };\n },\n ) {}\n\n async doGenerate(\n options: Parameters<SpeechModelV4['doGenerate']>[0],\n azureOptions: AzureSpeechModelSpeechOptions = {},\n ): Promise<Awaited<ReturnType<SpeechModelV4['doGenerate']>>> {\n const currentDate = this.config._internal?.currentDate?.() ?? new Date();\n const warnings: SharedV4Warning[] = [];\n const { style, styleDegree } = azureOptions;\n\n if (options.instructions != null) {\n warnings.push({\n type: 'unsupported',\n feature: 'instructions',\n details: 'Use providerOptions.azure.style to control speaking style.',\n });\n }\n const { voice, languageWarning } = resolveVoice(\n options.voice,\n options.language,\n );\n if (languageWarning != null) {\n warnings.push({\n type: 'unsupported',\n feature: 'language',\n details: languageWarning,\n });\n }\n if (styleDegree != null && style == null) {\n warnings.push({\n type: 'unsupported',\n feature: 'providerOptions.azure.styleDegree',\n details: 'styleDegree requires style.',\n });\n }\n\n let outputFormat = DEFAULT_OUTPUT_FORMAT;\n if (options.outputFormat != null) {\n const format = options.outputFormat.toLowerCase();\n const shorthand = OUTPUT_FORMATS.get(format);\n if (shorthand != null) {\n outputFormat = shorthand;\n } else if (NATIVE_OUTPUT_FORMAT.test(format)) {\n outputFormat = format;\n } else {\n warnings.push({\n type: 'unsupported',\n feature: 'outputFormat',\n details: `Unsupported output format: ${options.outputFormat}. Using mp3 instead.`,\n });\n }\n }\n\n const ssml = buildSsml({\n text: options.text,\n voiceName: voice.includes(':')\n ? voice\n : `${voice}:${getMAIVoiceModel(this.modelId) ?? this.modelId}`,\n locale: /^([a-z]{2,3}-[a-z]{2,4})-/i.exec(voice)?.[1],\n speed: options.speed,\n style,\n styleDegree: style != null ? styleDegree : undefined,\n });\n\n const {\n value: audio,\n responseHeaders,\n rawValue,\n } = await postToApi({\n url: this.config.url(),\n headers: combineHeaders(\n this.config.headers(),\n {\n 'Content-Type': 'application/ssml+xml',\n 'X-Microsoft-OutputFormat': outputFormat,\n },\n options.headers,\n ),\n body: { content: ssml, values: ssml },\n failedResponseHandler,\n successfulResponseHandler: createBinaryResponseHandler(),\n abortSignal: options.abortSignal,\n fetch: this.config.fetch,\n });\n\n return {\n audio,\n warnings,\n request: { body: ssml },\n response: {\n timestamp: currentDate,\n modelId: this.modelId,\n headers: responseHeaders,\n body: rawValue,\n },\n };\n }\n}\n\nfunction buildSsml({\n text,\n voiceName,\n locale = 'en-US',\n speed,\n style,\n styleDegree,\n}: {\n text: string;\n voiceName: string;\n locale?: string;\n speed?: number;\n style?: string;\n styleDegree?: number;\n}) {\n let content = escapeXml(text);\n if (speed != null) {\n content = `<prosody rate=\"${speed}\">${content}</prosody>`;\n }\n if (style != null) {\n const degree = styleDegree != null ? ` styledegree=\"${styleDegree}\"` : '';\n content = `<mstts:express-as style=\"${escapeXml(style)}\"${degree}>${content}</mstts:express-as>`;\n }\n return (\n `<speak version=\"1.0\" xmlns=\"http://www.w3.org/2001/10/synthesis\" ` +\n `xmlns:mstts=\"http://www.w3.org/2001/mstts\" xml:lang=\"${escapeXml(locale)}\">` +\n `<voice name=\"${escapeXml(voiceName)}\">${content}</voice></speak>`\n );\n}\n\nconst XML_ESCAPES: Record<string, string> = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n};\n\nfunction escapeXml(value: string) {\n return value.replace(/[&<>\"']/g, char => XML_ESCAPES[char]);\n}\n\n// Uses the language's default voice when no voice is set. An explicit voice\n// wins, and its locale selects the language.\nfunction resolveVoice(\n voice: string | undefined,\n language: string | undefined,\n): { voice: string; languageWarning?: string } {\n const code = language ? language.split('-')[0].toLowerCase() : undefined;\n if (voice == null) {\n if (code == null) return { voice: DEFAULT_VOICE };\n if (code === 'auto') {\n return {\n voice: DEFAULT_VOICE,\n languageWarning: `Automatic language detection is not supported. ${DEFAULT_VOICE} was used.`,\n };\n }\n const defaultVoice = DEFAULT_VOICES.get(code);\n return defaultVoice != null\n ? { voice: defaultVoice }\n : {\n voice: DEFAULT_VOICE,\n languageWarning: `No default MAI voice for language \"${language}\". ${DEFAULT_VOICE} was used.`,\n };\n }\n const voiceLanguage = /^([a-z]{2,3})-[a-z]{2,4}-/i\n .exec(voice)?.[1]\n ?.toLowerCase();\n return code != null &&\n code !== 'auto' &&\n voiceLanguage != null &&\n code !== voiceLanguage\n ? {\n voice,\n languageWarning: `The voice ${voice} selects the language. Language \"${language}\" was ignored.`,\n }\n : { voice };\n}\n\nconst errorSchema = z.object({\n error: z.object({ message: z.string() }),\n});\n\n// Azure Speech answers invalid requests (unknown voice, style, or output\n// format) with an empty 400 body.\nconst failedResponseHandler: ResponseHandler<APICallError> = async ({\n response,\n url,\n requestBodyValues,\n}) => {\n const responseHeaders = extractResponseHeaders(response);\n const responseBody = await response.text();\n const parsed = await safeParseJSON({\n text: responseBody,\n schema: errorSchema,\n });\n\n const message = parsed.success\n ? parsed.value.error.message\n : response.status === 400\n ? 'Azure Speech request failed with status 400. Check the voice name, style, and output format.'\n : `Azure Speech request failed with status ${response.status}.`;\n\n return {\n responseHeaders,\n value: new APICallError({\n message,\n url,\n requestBodyValues,\n statusCode: response.status,\n responseHeaders,\n responseBody,\n }),\n };\n};\n","import {\n lazySchema,\n zodSchema,\n type InferSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\n// Strict objects reject unknown keys (e.g. `diarization.maxSpeakers`, which\n// MAI-Transcribe-2 does not support) instead of silently dropping them.\nexport const azureSpeechTranscriptionModelOptionsShape = () => ({\n /**\n * Timing granularity. Defaults to `segment` so that transcription results\n * include timed segments (Azure's own default is `none`).\n */\n timestamps: z.enum(['word', 'segment', 'none']).optional(),\n\n /**\n * `verbatim` keeps fillers and false starts, `clean` removes them.\n * Azure defaults to `verbatim`.\n */\n transcribeStyle: z.enum(['verbatim', 'clean']).optional(),\n\n /**\n * Forces a single language, e.g. `['en']`. Omit for automatic language\n * detection and code switching.\n */\n locales: z.array(z.string()).length(1).optional(),\n\n /**\n * Speaker diarization. Speaker IDs are available in provider metadata.\n */\n diarization: z.strictObject({ enabled: z.boolean() }).optional(),\n\n /**\n * Keyword biasing for names and domain terminology.\n */\n phraseList: z.strictObject({ phrases: z.array(z.string()) }).optional(),\n});\n\nexport const azureSpeechTranscriptionModelOptions = lazySchema(() =>\n zodSchema(z.strictObject(azureSpeechTranscriptionModelOptionsShape())),\n);\n\nexport type AzureTranscriptionModelSpeechOptions = InferSchema<\n typeof azureSpeechTranscriptionModelOptions\n>;\n","import {\n lazySchema,\n zodSchema,\n type InferSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { azureSpeechTranscriptionModelOptionsShape } from './azure-speech-transcription-model-options';\n\nexport const azureTranscriptionModelOptions = lazySchema(() =>\n zodSchema(\n z.strictObject({\n /**\n * API to use. Defaults to Speech for MAI-Transcribe models, OpenAI otherwise.\n */\n api: z.enum(['openai', 'speech']).optional(),\n ...azureSpeechTranscriptionModelOptionsShape(),\n }),\n ),\n);\n\nexport type AzureTranscriptionModelOptions = InferSchema<\n typeof azureTranscriptionModelOptions\n>;\n\n// Azure Speech model names by lowercase model ID. MAI-Transcribe-1.5 only\n// accepts Azure's default timestamps (`none`).\nconst maiTranscribeModels = new Map([\n ['mai-transcribe-2', { name: 'MAI-Transcribe-2', supportsTimestamps: true }],\n [\n 'mai-transcribe-1.5',\n { name: 'MAI-Transcribe-1.5', supportsTimestamps: false },\n ],\n]);\n\nexport function getMAITranscribeModel(modelId: string) {\n return maiTranscribeModels.get(modelId.toLowerCase());\n}\n","import type { TranscriptionModelV4 } from '@ai-sdk/provider';\nimport {\n combineHeaders,\n convertBase64ToUint8Array,\n createJsonErrorResponseHandler,\n createJsonResponseHandler,\n mediaTypeToExtension,\n postFormDataToApi,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport type { AzureTranscriptionProviderMetadata } from './azure-transcription-provider-metadata';\nimport type { AzureTranscriptionModelSpeechOptions } from './azure-speech-transcription-model-options';\nimport { getMAITranscribeModel } from './azure-transcription-model-options';\n\nexport class AzureSpeechTranscriptionModel implements TranscriptionModelV4 {\n readonly specificationVersion = 'v4';\n readonly provider = 'azure.transcription';\n\n constructor(\n readonly modelId: string,\n private readonly config: {\n url: () => string;\n headers: () => Record<string, string | undefined>;\n fetch?: FetchFunction;\n },\n ) {}\n\n async doGenerate(\n options: Parameters<TranscriptionModelV4['doGenerate']>[0],\n azureOptions: AzureTranscriptionModelSpeechOptions = {},\n ): Promise<Awaited<ReturnType<TranscriptionModelV4['doGenerate']>>> {\n const timestamp = new Date();\n const maiModel = getMAITranscribeModel(this.modelId);\n const formData = new FormData();\n formData.append(\n 'audio',\n new Blob(\n [\n typeof options.audio === 'string'\n ? convertBase64ToUint8Array(options.audio)\n : options.audio,\n ],\n { type: options.mediaType },\n ),\n `audio.${mediaTypeToExtension(options.mediaType)}`,\n );\n formData.append(\n 'definition',\n JSON.stringify({\n enhancedMode: {\n enabled: true,\n model: maiModel?.name ?? this.modelId,\n modelOptions: {\n timestamps:\n azureOptions.timestamps ??\n (maiModel?.supportsTimestamps === false ? undefined : 'segment'),\n transcribeStyle: azureOptions.transcribeStyle,\n },\n },\n locales: azureOptions.locales,\n diarization: azureOptions.diarization,\n phraseList: azureOptions.phraseList,\n }),\n );\n\n const { value, rawValue, responseHeaders } = await postFormDataToApi({\n url: this.config.url(),\n headers: combineHeaders(this.config.headers(), options.headers),\n formData,\n abortSignal: options.abortSignal,\n fetch: this.config.fetch,\n failedResponseHandler: createJsonErrorResponseHandler({\n errorSchema: z.union([\n z.object({ error: z.object({ message: z.string() }) }),\n z.object({ message: z.string() }),\n ]),\n errorToMessage: data =>\n 'error' in data ? data.error.message : data.message,\n }),\n successfulResponseHandler: createJsonResponseHandler(responseSchema),\n });\n\n const phrases = value.phrases ?? [];\n // Consider every reported locale so mixed results (e.g. en + fil) are not\n // collapsed to one language; only ISO-639-1 codes are reported.\n const languages = new Set(\n phrases.flatMap(phrase =>\n phrase.locale ? [phrase.locale.split('-')[0].toLowerCase()] : [],\n ),\n );\n const [language] = languages;\n const reportedLanguage =\n languages.size === 1 && /^[a-z]{2}$/.test(language)\n ? language\n : undefined;\n\n return {\n text: value.combinedPhrases.map(phrase => phrase.text).join(' '),\n segments: phrases.flatMap(phrase =>\n phrase.offsetMilliseconds != null && phrase.durationMilliseconds != null\n ? [\n {\n text: phrase.text,\n startSecond: phrase.offsetMilliseconds / 1000,\n endSecond:\n (phrase.offsetMilliseconds + phrase.durationMilliseconds) /\n 1000,\n },\n ]\n : [],\n ),\n language: reportedLanguage,\n durationInSeconds:\n value.durationMilliseconds != null\n ? value.durationMilliseconds / 1000\n : undefined,\n warnings: [],\n providerMetadata: {\n azure: { phrases },\n } satisfies AzureTranscriptionProviderMetadata,\n response: {\n timestamp,\n modelId: this.modelId,\n headers: responseHeaders,\n body: rawValue,\n },\n };\n }\n}\n\nconst responseSchema = z.object({\n combinedPhrases: z.array(z.object({ text: z.string() })),\n durationMilliseconds: z.number().nullish(),\n phrases: z\n .array(\n z.object({\n text: z.string(),\n offsetMilliseconds: z.number().nullish(),\n durationMilliseconds: z.number().nullish(),\n locale: z.string().nullish(),\n speaker: z.number().nullish(),\n confidence: z.number().nullish(),\n words: z\n .array(\n z.object({\n text: z.string(),\n offsetMilliseconds: z.number().nullish(),\n durationMilliseconds: z.number().nullish(),\n }),\n )\n .nullish(),\n }),\n )\n .nullish(),\n});\n","// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n","import {\n OpenAIChatLanguageModel,\n OpenAICompletionLanguageModel,\n OpenAIEmbeddingModel,\n OpenAIImageModel,\n OpenAIResponsesLanguageModel,\n OpenAISpeechModel,\n OpenAITranscriptionModel,\n} from '@ai-sdk/openai/internal';\nimport { DeepSeekChatLanguageModel } from '@ai-sdk/deepseek/internal';\nimport {\n InvalidArgumentError,\n UnsupportedFunctionalityError,\n type EmbeddingModelV4,\n type LanguageModelV4,\n type ProviderV4,\n type ImageModelV4,\n type SharedV4Warning,\n type SpeechModelV4,\n type TranscriptionModelV4,\n} from '@ai-sdk/provider';\nimport {\n isValidHostnamePart,\n loadApiKey,\n loadSetting,\n normalizeHeaders,\n parseProviderOptions,\n serializeModelOptions,\n WORKFLOW_DESERIALIZE,\n WORKFLOW_SERIALIZE,\n withoutTrailingSlash,\n withUserAgentSuffix,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { azureOpenaiTools } from './azure-openai-tools';\nimport {\n azureSpeechModelOptions,\n getMAIVoiceModel,\n} from './azure-speech-model-options';\nimport { AzureSpeechSpeechModel } from './azure-speech-speech-model';\nimport { AzureSpeechTranscriptionModel } from './azure-speech-transcription-model';\nimport {\n azureTranscriptionModelOptions,\n getMAITranscribeModel,\n} from './azure-transcription-model-options';\nimport { VERSION } from './version';\n\nexport interface AzureOpenAIProvider extends ProviderV4 {\n (deploymentId: string): LanguageModelV4;\n\n /**\n * Creates an Azure OpenAI responses API model for text generation.\n */\n languageModel(deploymentId: string): LanguageModelV4;\n\n /**\n * Creates an Azure OpenAI chat model for text generation.\n */\n chat(deploymentId: string): LanguageModelV4;\n\n /**\n * Creates an Azure-hosted DeepSeek chat model for text generation.\n */\n deepseek(deploymentId: string): LanguageModelV4;\n\n /**\n * Creates an Azure OpenAI responses API model for text generation.\n */\n responses(deploymentId: string): LanguageModelV4;\n\n /**\n * Creates an Azure OpenAI completion model for text generation.\n */\n completion(deploymentId: string): LanguageModelV4;\n\n /**\n * Creates an Azure OpenAI model for text embeddings.\n */\n embedding(deploymentId: string): EmbeddingModelV4;\n\n /**\n * Creates an Azure OpenAI model for text embeddings.\n */\n embeddingModel(deploymentId: string): EmbeddingModelV4;\n\n /**\n * @deprecated Use `embedding` instead.\n */\n textEmbedding(deploymentId: string): EmbeddingModelV4;\n\n /**\n * @deprecated Use `embeddingModel` instead.\n */\n textEmbeddingModel(deploymentId: string): EmbeddingModelV4;\n\n /**\n * Creates an Azure OpenAI DALL-E model for image generation.\n */\n image(deploymentId: string): ImageModelV4;\n\n /**\n * Creates an Azure OpenAI DALL-E model for image generation.\n */\n imageModel(deploymentId: string): ImageModelV4;\n\n /**\n * Creates an Azure transcription model. MAI-Transcribe models use the Speech\n * API by default; other IDs use OpenAI. Override with providerOptions.azure.api.\n */\n transcription(deploymentId: string): TranscriptionModelV4;\n\n /**\n * Creates an Azure transcription model. Alias of `transcription`.\n */\n transcriptionModel(deploymentId: string): TranscriptionModelV4;\n\n /**\n * Creates an Azure speech generation model. MAI-Voice models use the Speech\n * API by default; other IDs use OpenAI. Override with providerOptions.azure.api.\n */\n speech(deploymentId: string): SpeechModelV4;\n\n /**\n * Creates an Azure speech generation model. Alias of `speech`.\n */\n speechModel(deploymentId: string): SpeechModelV4;\n\n /**\n * AzureOpenAI-specific tools.\n */\n tools: typeof azureOpenaiTools;\n}\n\nexport interface AzureOpenAIProviderSettings {\n /**\n * Name of the Azure OpenAI resource. Either this or `baseURL` can be used.\n *\n * The resource name is used in the assembled URL: `https://{resourceName}.openai.azure.com/openai/v1{path}`.\n * It must be a single DNS label (letters, digits, and hyphens).\n */\n resourceName?: string;\n\n /**\n * Use a different URL prefix for API calls, e.g. to use proxy servers. Either this or `resourceName` can be used.\n * When a baseURL is provided, the resourceName is ignored.\n *\n * With an unversioned Azure OpenAI baseURL, the resolved URL is `{baseURL}/v1{path}`.\n * Azure OpenAI base URLs that already end in `/openai/v1` are used as-is.\n * With a non-Azure custom gateway baseURL, the resolved URL is `{baseURL}{path}`.\n */\n baseURL?: string;\n\n /**\n * API key for authenticating requests.\n */\n apiKey?: string;\n\n /**\n * A function that returns an access token for Microsoft Entra\n * (formerly known as Azure Active Directory), which will be invoked\n * on every request.\n */\n tokenProvider?: (() => Promise<string>) | undefined;\n\n /**\n * Custom headers to include in the requests.\n */\n headers?: Record<string, string>;\n\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept requests,\n * or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n\n /**\n * Custom api version to use. Defaults to `v1`.\n * Complete v1 base URLs are used as-is.\n */\n apiVersion?: string;\n\n /**\n * Use deployment-based URLs for specific model types. Set to true to use legacy deployment format:\n * `{baseURL}/deployments/{deploymentId}{path}?api-version={apiVersion}` instead of\n * `{baseURL}/v1{path}?api-version={apiVersion}`.\n */\n useDeploymentBasedUrls?: boolean;\n\n /**\n * URL prefix for Azure Speech (MAI-Transcribe transcription and MAI-Voice\n * speech), e.g. a regional endpoint like\n * `https://eastus.api.cognitive.microsoft.com`.\n * Defaults to `https://{resourceName}.cognitiveservices.azure.com`.\n * Speech requests do not use `baseURL` or `apiVersion`.\n */\n speechBaseURL?: string;\n}\n\nfunction getAzureOpenAIBaseURLInfo(baseURL: string | undefined) {\n if (baseURL == null) {\n return {\n isAzureOpenAI: true,\n isFoundryProject: false,\n isVersioned: false,\n };\n }\n\n const url = new URL(baseURL);\n const hostname = url.hostname;\n const isAzureOpenAI =\n hostname.endsWith('.openai.azure.com') ||\n hostname.endsWith('.services.ai.azure.com') ||\n hostname.endsWith('.cognitiveservices.azure.com');\n const pathname = url.pathname.replace(/\\/+$/, '');\n\n return {\n isAzureOpenAI,\n isFoundryProject:\n hostname.endsWith('.services.ai.azure.com') &&\n pathname.startsWith('/api/projects/'),\n isVersioned: isAzureOpenAI && pathname.toLowerCase().endsWith('/openai/v1'),\n };\n}\n\n/**\n * Create an Azure OpenAI provider instance.\n */\nexport function createAzure(\n options: AzureOpenAIProviderSettings = {},\n): AzureOpenAIProvider {\n const tokenProvider = options.tokenProvider;\n\n if (options.apiKey && tokenProvider) {\n throw new InvalidArgumentError({\n argument: 'apiKey/tokenProvider',\n message:\n 'Both apiKey and tokenProvider were provided. Please use only one authentication method.',\n });\n }\n\n const getHeaders = (api: 'openai' | 'speech' = 'openai') => {\n const authHeaders = tokenProvider\n ? {}\n : {\n [api === 'speech' ? 'Ocp-Apim-Subscription-Key' : 'api-key']:\n loadApiKey({\n apiKey: options.apiKey,\n environmentVariableName: 'AZURE_API_KEY',\n description: api === 'speech' ? 'Azure Speech' : 'Azure OpenAI',\n }),\n };\n\n return withUserAgentSuffix(\n {\n ...authHeaders,\n ...options.headers,\n },\n `ai-sdk-azure/${VERSION}`,\n );\n };\n\n const fetch: FetchFunction | undefined = tokenProvider\n ? async (input, init) => {\n const headers = normalizeHeaders(init?.headers);\n\n if (headers.authorization == null) {\n headers.authorization = `Bearer ${await tokenProvider()}`;\n }\n\n return (options.fetch ?? globalThis.fetch)(input, {\n ...init,\n headers,\n });\n }\n : options.fetch;\n\n const getResourceName = () => {\n const resourceName = loadSetting({\n settingValue: options.resourceName,\n settingName: 'resourceName',\n environmentVariableName: 'AZURE_RESOURCE_NAME',\n description: 'Azure OpenAI resource name',\n });\n\n // The resource name becomes part of the request host, so only a DNS label\n // is accepted (e.g. `user@internal:8080/#` would rewrite the host).\n if (!isValidHostnamePart(resourceName)) {\n throw new InvalidArgumentError({\n argument: 'resourceName',\n message:\n 'Invalid Azure resource name. Expected a single DNS label (letters, digits, and hyphens). Use `baseURL` for custom endpoints.',\n });\n }\n\n return resourceName;\n };\n\n const apiVersion = options.apiVersion ?? 'v1';\n const {\n isAzureOpenAI,\n isFoundryProject,\n isVersioned: isAzureOpenAIVersioned,\n } = getAzureOpenAIBaseURLInfo(options.baseURL);\n\n const url = ({ path, modelId }: { path: string; modelId: string }) => {\n const baseUrlPrefix = withoutTrailingSlash(\n options.baseURL ?? `https://${getResourceName()}.openai.azure.com/openai`,\n );\n\n let fullUrl: URL;\n if (options.useDeploymentBasedUrls) {\n // Use deployment-based format for compatibility with certain Azure OpenAI models\n fullUrl = new URL(`${baseUrlPrefix}/deployments/${modelId}${path}`);\n } else if (!isAzureOpenAI || isAzureOpenAIVersioned) {\n // Custom gateways can own Azure routing and versioning themselves.\n // Complete Azure OpenAI v1 URLs also own their versioning.\n fullUrl = new URL(`${baseUrlPrefix}${path}`);\n } else {\n // Use v1 API format - no deployment ID in URL\n fullUrl = new URL(`${baseUrlPrefix}/v1${path}`);\n }\n\n if (\n options.useDeploymentBasedUrls ||\n (isAzureOpenAI && !isAzureOpenAIVersioned && !isFoundryProject)\n ) {\n fullUrl.searchParams.set('api-version', apiVersion);\n }\n\n return fullUrl.toString();\n };\n\n const createChatModel = (deploymentName: string) =>\n new OpenAIChatLanguageModel(deploymentName, {\n provider: 'azure.chat',\n url,\n headers: getHeaders,\n fetch,\n });\n\n const createDeepSeekModel = (deploymentName: string) =>\n new DeepSeekChatLanguageModel(deploymentName, {\n provider: 'azure.deepseek',\n url,\n headers: getHeaders,\n fetch,\n supportsPenaltySampling: true,\n supportsThinking: false,\n // json_object with thinking enabled makes Azure return the JSON in reasoning_content with empty content\n supportsStructuredOutputs: true,\n });\n\n const createCompletionModel = (modelId: string) =>\n new OpenAICompletionLanguageModel(modelId, {\n provider: 'azure.completion',\n url,\n headers: getHeaders,\n fetch,\n });\n\n const createEmbeddingModel = (modelId: string) =>\n new OpenAIEmbeddingModel(modelId, {\n provider: 'azure.embeddings',\n headers: getHeaders,\n url,\n fetch,\n });\n\n const createResponsesModel = (modelId: string) =>\n new OpenAIResponsesLanguageModel(modelId, {\n provider: 'azure.responses',\n url,\n headers: getHeaders,\n fetch,\n explicitMessageItemType: isFoundryProject,\n // Soft-deprecated. TODO: remove in v8\n fileIdPrefixes: ['assistant-'],\n });\n\n const createImageModel = (modelId: string) =>\n new OpenAIImageModel(modelId, {\n provider: 'azure.image',\n url,\n headers: getHeaders,\n fetch,\n // Azure model IDs are user-defined deployment names, so OpenAI model\n // family capabilities cannot be inferred from them.\n imageInputCapabilities: {\n supportsFileInputs: undefined,\n supportsMaskInputs: undefined,\n },\n });\n\n const speechBaseURL = () =>\n withoutTrailingSlash(options.speechBaseURL) ??\n `https://${getResourceName()}.cognitiveservices.azure.com`;\n\n const createTranscriptionModel = (modelId: string) =>\n new AzureTranscriptionModel(\n modelId,\n options,\n new OpenAITranscriptionModel(modelId, {\n provider: 'azure.transcription',\n url,\n headers: getHeaders,\n fetch,\n }),\n new AzureSpeechTranscriptionModel(modelId, {\n url: () =>\n `${speechBaseURL()}/speechtotext/transcriptions:transcribe?api-version=2025-10-15`,\n headers: () => getHeaders('speech'),\n fetch,\n }),\n );\n\n const createSpeechModel = (modelId: string) =>\n new AzureSpeechModel(\n modelId,\n options,\n new OpenAISpeechModel(modelId, {\n provider: 'azure.speech',\n url,\n headers: getHeaders,\n fetch,\n }),\n new AzureSpeechSpeechModel(modelId, {\n url: () => `${speechBaseURL()}/tts/cognitiveservices/v1`,\n headers: () => getHeaders('speech'),\n fetch,\n }),\n );\n\n const provider = function (deploymentId: string) {\n if (new.target) {\n throw new Error(\n 'The Azure OpenAI model function cannot be called with the new keyword.',\n );\n }\n\n return createResponsesModel(deploymentId);\n };\n\n provider.specificationVersion = 'v4' as const;\n provider.languageModel = createResponsesModel;\n provider.chat = createChatModel;\n provider.deepseek = createDeepSeekModel;\n provider.completion = createCompletionModel;\n provider.embedding = createEmbeddingModel;\n provider.embeddingModel = createEmbeddingModel;\n provider.textEmbedding = createEmbeddingModel;\n provider.textEmbeddingModel = createEmbeddingModel;\n provider.image = createImageModel;\n provider.imageModel = createImageModel;\n provider.responses = createResponsesModel;\n provider.transcription = createTranscriptionModel;\n provider.transcriptionModel = createTranscriptionModel;\n provider.speech = createSpeechModel;\n provider.speechModel = createSpeechModel;\n provider.tools = azureOpenaiTools;\n return provider;\n}\n\n/**\n * Default Azure OpenAI provider instance.\n */\nexport const azure = createAzure();\n\n// Resolves the API per request: providerOptions also reach this model via Gateway.\nclass AzureTranscriptionModel implements TranscriptionModelV4 {\n readonly specificationVersion = 'v4';\n readonly provider = 'azure.transcription';\n\n constructor(\n readonly modelId: string,\n private readonly config: AzureOpenAIProviderSettings,\n private readonly openai: OpenAITranscriptionModel,\n private readonly speech: AzureSpeechTranscriptionModel,\n ) {}\n\n static [WORKFLOW_SERIALIZE](model: AzureTranscriptionModel) {\n return serializeModelOptions({\n modelId: model.modelId,\n config: model.config,\n });\n }\n\n static [WORKFLOW_DESERIALIZE](options: {\n modelId: string;\n config: AzureOpenAIProviderSettings;\n }) {\n return createAzure(options.config).transcription(options.modelId);\n }\n\n async doGenerate(options: Parameters<TranscriptionModelV4['doGenerate']>[0]) {\n const { api, ...speechOptions } = await this.getOptions(\n options.providerOptions,\n );\n if (api === 'speech') {\n return this.speech.doGenerate(options, speechOptions);\n }\n\n const result = await this.openai.doGenerate(options);\n return {\n ...result,\n warnings: [\n ...result.warnings,\n ...Object.keys(speechOptions).map(key => ({\n type: 'unsupported' as const,\n feature: `providerOptions.azure.${key}`,\n details: 'This option requires the Azure Speech API.',\n })),\n ],\n };\n }\n\n async doStream(\n options: Parameters<NonNullable<TranscriptionModelV4['doStream']>>[0],\n ) {\n const { api } = await this.getOptions(options.providerOptions);\n if (api === 'speech') {\n throw new UnsupportedFunctionalityError({\n functionality: 'streaming transcription with the Azure Speech API',\n });\n }\n return this.openai.doStream(options);\n }\n\n private async getOptions(\n providerOptions: Parameters<\n TranscriptionModelV4['doGenerate']\n >[0]['providerOptions'],\n ) {\n const options = await parseProviderOptions({\n provider: 'azure',\n providerOptions,\n schema: azureTranscriptionModelOptions,\n });\n return {\n ...options,\n api:\n options?.api ??\n (getMAITranscribeModel(this.modelId) ? 'speech' : 'openai'),\n };\n }\n}\n\n// Resolves the API per request: providerOptions also reach this model via Gateway.\nclass AzureSpeechModel implements SpeechModelV4 {\n readonly specificationVersion = 'v4';\n readonly provider = 'azure.speech';\n\n constructor(\n readonly modelId: string,\n private readonly config: AzureOpenAIProviderSettings,\n private readonly openai: OpenAISpeechModel,\n private readonly speech: AzureSpeechSpeechModel,\n ) {}\n\n static [WORKFLOW_SERIALIZE](model: AzureSpeechModel) {\n return serializeModelOptions({\n modelId: model.modelId,\n config: model.config,\n });\n }\n\n static [WORKFLOW_DESERIALIZE](options: {\n modelId: string;\n config: AzureOpenAIProviderSettings;\n }) {\n return createAzure(options.config).speech(options.modelId);\n }\n\n async doGenerate(options: Parameters<SpeechModelV4['doGenerate']>[0]) {\n const { api, ...speechOptions } =\n (await parseProviderOptions({\n provider: 'azure',\n providerOptions: options.providerOptions,\n schema: azureSpeechModelOptions,\n })) ?? {};\n if (\n (api ?? (getMAIVoiceModel(this.modelId) ? 'speech' : 'openai')) ===\n 'speech'\n ) {\n return this.speech.doGenerate(options, speechOptions);\n }\n\n const result = await this.openai.doGenerate(options);\n return {\n ...result,\n warnings: [\n ...result.warnings,\n ...Object.entries(speechOptions)\n .filter(([, value]) => value !== undefined)\n .map(\n ([key]): SharedV4Warning => ({\n type: 'unsupported',\n feature: `providerOptions.azure.${key}`,\n details: 'This option requires the Azure Speech API.',\n }),\n ),\n ],\n };\n }\n}\n"],"mappings":";;;;;;AAQA,MAAa,mBAMT;CACF;CACA;CACA;CACA;CACA;AACF;;;ACbA,MAAa,4CAA4C;;;;;CAKvD,OAAO,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;;;;CAKlC,aAAa,EAAE,OAAO,CAAC,CAAC,IAAI,GAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;AACpD;AAE6C,iBAC3C,UAAU,EAAE,aAAa,mCAAmC,CAAC,CAAC,CAChE;;;ACdA,MAAa,0BAA0B,iBACrC,UACE,EAAE,aAAa;;;;CAIb,KAAK,EAAE,KAAK,CAAC,UAAU,QAAQ,CAAC,CAAC,CAAC,SAAS;CAC3C,GAAG,mCAAmC;AACxC,CAAC,CACH,CACF;AAOA,MAAM,iCAAiB,IAAI,IAAI,CAC7B,CAAC,qBAAqB,mBAAmB,GACzC,CAAC,eAAe,aAAa,CAC/B,CAAC;AAED,SAAgB,iBAAiB,SAAiB;CAChD,OAAO,eAAe,IAAI,QAAQ,YAAY,CAAC;AACjD;;;ACdA,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EH,QAAQ,oBAAoB,OAAyB;EACnD,OAAO,sBAAsB;GAC3B,SAAS,MAAM;GACf,QAAQ,MAAM;EAChB,CAAC;CACH;CAEA,QAAQ,sBAAsB,SAG3B;EACD,OAAO,YAAY,QAAQ,MAAM,CAAC,CAAC,OAAO,QAAQ,OAAO;CAC3D;CAEA,MAAM,WAAW,SAAqD;EACpE,MAAM,EAAE,KAAK,GAAG,kBACb,MAAM,qBAAqB;GAC1B,UAAU;GACV,iBAAiB,QAAQ;GACzB,QAAQ;EACV,CAAC,KAAM,CAAC;EACV,KACG,QAAQ,iBAAiB,KAAK,OAAO,IAAI,WAAW,eACrD,UAEA,OAAO,KAAK,OAAO,WAAW,SAAS,aAAa;EAGtD,MAAM,SAAS,MAAM,KAAK,OAAO,WAAW,OAAO;EACnD,OAAO;GACL,GAAG;GACH,UAAU,CACR,GAAG,OAAO,UACV,GAAG,OAAO,QAAQ,aAAa,CAAC,CAC7B,QAAQ,GAAG,WAAW,UAAU,KAAA,CAAS,CAAC,CAC1C,KACE,CAAC,UAA2B;IAC3B,MAAM;IACN,SAAS,yBAAyB;IAClC,SAAS;GACX,EACF,CACJ;EACF;CACF;AACF"}
|
package/docs/04-azure.mdx
CHANGED
|
@@ -134,8 +134,8 @@ You can use the following optional settings to customize the OpenAI provider ins
|
|
|
134
134
|
|
|
135
135
|
- **speechBaseURL** _string_
|
|
136
136
|
|
|
137
|
-
URL prefix for Azure Speech
|
|
138
|
-
a regional endpoint such as `https://eastus.api.cognitive.microsoft.com`.
|
|
137
|
+
URL prefix for Azure Speech requests (MAI-Transcribe transcription and MAI-Voice
|
|
138
|
+
speech generation), for example a regional endpoint such as `https://eastus.api.cognitive.microsoft.com`.
|
|
139
139
|
Defaults to `https://{resourceName}.cognitiveservices.azure.com`.
|
|
140
140
|
Speech requests do not use `baseURL` or `apiVersion`.
|
|
141
141
|
|
|
@@ -1114,11 +1114,17 @@ The first argument is the model id e.g. `whisper-1`.
|
|
|
1114
1114
|
const model = azure.transcription('whisper-1');
|
|
1115
1115
|
```
|
|
1116
1116
|
|
|
1117
|
-
### MAI-Transcribe
|
|
1117
|
+
### MAI-Transcribe
|
|
1118
|
+
|
|
1119
|
+
MAI-Transcribe models are multilingual speech-to-text models from Microsoft AI, served through Azure.
|
|
1120
|
+
The following model IDs use the Azure Speech API. They are matched case-insensitively
|
|
1121
|
+
and sent to Azure under their Azure model names:
|
|
1122
|
+
|
|
1123
|
+
| Model ID | Azure model | Notes |
|
|
1124
|
+
| -------------------- | -------------------- | ------------------------------------ |
|
|
1125
|
+
| `mai-transcribe-2` | `MAI-Transcribe-2` | Supports every option below. |
|
|
1126
|
+
| `mai-transcribe-1.5` | `MAI-Transcribe-1.5` | Supports `locales` and `phraseList`. |
|
|
1118
1127
|
|
|
1119
|
-
MAI-Transcribe-2 is a multilingual speech-to-text model from Microsoft AI, served through Azure.
|
|
1120
|
-
`azure.transcription('mai-transcribe-2')` uses the Azure Speech API.
|
|
1121
|
-
The model ID is matched case-insensitively and sent to Azure as `MAI-Transcribe-2`.
|
|
1122
1128
|
All other IDs use the OpenAI API by default, including custom deployment names.
|
|
1123
1129
|
|
|
1124
1130
|
```ts
|
|
@@ -1139,7 +1145,7 @@ const result = await transcribe({
|
|
|
1139
1145
|
});
|
|
1140
1146
|
```
|
|
1141
1147
|
|
|
1142
|
-
MAI-Transcribe
|
|
1148
|
+
MAI-Transcribe models require a Microsoft Foundry (Speech) resource in a region where they are available:
|
|
1143
1149
|
`centralindia`, `eastus`, `northeurope`, `southeastasia`, `westus`, or `westus2`
|
|
1144
1150
|
(see [Speech service regions](https://learn.microsoft.com/en-us/azure/ai-services/speech-service/regions?tabs=llmspeech)).
|
|
1145
1151
|
Resources in other regions reject the request.
|
|
@@ -1167,17 +1173,19 @@ The following options are available through `providerOptions.azure`:
|
|
|
1167
1173
|
|
|
1168
1174
|
- **api** _'openai' | 'speech'_
|
|
1169
1175
|
Overrides model-based API selection for this request.
|
|
1170
|
-
Set `openai` for an OpenAI deployment named
|
|
1176
|
+
Set `openai` for an OpenAI deployment named after one of the model IDs above, or `speech` to
|
|
1171
1177
|
send another model ID to Speech. Other Speech model IDs are sent unchanged.
|
|
1172
1178
|
|
|
1173
1179
|
- **timestamps** _'word' | 'segment' | 'none'_
|
|
1174
|
-
Timing granularity.
|
|
1175
|
-
timed segments (Azure's own default is `none`). `segment` returns one segment
|
|
1180
|
+
Timing granularity. For MAI-Transcribe-2 the AI SDK defaults to `segment` so that results
|
|
1181
|
+
include timed segments (Azure's own default is `none`). `segment` returns one segment
|
|
1176
1182
|
per sentence or speaker turn, `word` additionally returns word timing in provider
|
|
1177
1183
|
metadata, and `none` returns a single segment that spans the whole audio.
|
|
1184
|
+
MAI-Transcribe-1.5 only supports `none`, so the AI SDK does not send a default for it.
|
|
1178
1185
|
|
|
1179
1186
|
- **transcribeStyle** _'verbatim' | 'clean'_
|
|
1180
1187
|
`verbatim` keeps fillers and false starts, `clean` removes them. Defaults to `verbatim`.
|
|
1188
|
+
`clean` requires MAI-Transcribe-2.
|
|
1181
1189
|
|
|
1182
1190
|
- **locales** _string[]_
|
|
1183
1191
|
Exactly one language code, such as `['en']`. This is a strong hint; omit it for
|
|
@@ -1185,15 +1193,18 @@ The following options are available through `providerOptions.azure`:
|
|
|
1185
1193
|
|
|
1186
1194
|
- **diarization** _object_
|
|
1187
1195
|
Set `enabled` to `true` to identify speakers. Speaker IDs are returned in
|
|
1188
|
-
provider metadata. `maxSpeakers` is not supported
|
|
1196
|
+
provider metadata. Requires MAI-Transcribe-2. `maxSpeakers` is not supported.
|
|
1189
1197
|
|
|
1190
1198
|
- **phraseList** _object_
|
|
1191
1199
|
Set `phrases` to a list of names and domain terms to bias recognition toward them.
|
|
1192
1200
|
|
|
1193
1201
|
Explicit `api` takes precedence over the model ID. Existing OpenAI transcription
|
|
1194
1202
|
options remain under `providerOptions.openai`. Speech-only Azure options produce
|
|
1195
|
-
warnings when used with the OpenAI API. Unknown
|
|
1196
|
-
|
|
1203
|
+
warnings when used with the OpenAI API. Unknown `providerOptions.azure` keys
|
|
1204
|
+
(for example `diarization.maxSpeakers`) are rejected before the request is sent.
|
|
1205
|
+
Options that a model does not support, such as `timestamps: 'word'` with
|
|
1206
|
+
MAI-Transcribe-1.5, are sent unchanged, and Azure rejects the request with an
|
|
1207
|
+
error that names the option.
|
|
1197
1208
|
|
|
1198
1209
|
Results include transcript text, timed segments, duration, and an ISO-639-1
|
|
1199
1210
|
language code when the reported phrase locales identify one language. Mixed-language
|
|
@@ -1203,9 +1214,9 @@ timing are preserved in `providerMetadata.azure.phrases`; use the exported
|
|
|
1203
1214
|
`AzureTranscriptionProviderMetadata` type to access them. Phrase timing is in
|
|
1204
1215
|
milliseconds in metadata and seconds in normalized `segments`.
|
|
1205
1216
|
|
|
1206
|
-
MAI-Transcribe
|
|
1207
|
-
shorter than 2 hours and smaller than 250 MB, and
|
|
1208
|
-
transcription. The
|
|
1217
|
+
MAI-Transcribe models are file transcription models: they accept WAV, MP3, or FLAC files
|
|
1218
|
+
shorter than 2 hours and smaller than 250 MB, and do not support streaming
|
|
1219
|
+
transcription. The models are in public preview. See
|
|
1209
1220
|
[Azure's MAI-Transcribe guide](https://learn.microsoft.com/en-us/azure/ai-services/speech-service/mai-transcribe)
|
|
1210
1221
|
for supported languages and diarization limits.
|
|
1211
1222
|
|
|
@@ -1279,12 +1290,14 @@ The following provider options are available:
|
|
|
1279
1290
|
| `gpt-4o-mini-transcribe` | <Check /> | <Cross /> | <Cross /> | <Cross /> |
|
|
1280
1291
|
| `gpt-4o-transcribe` | <Check /> | <Cross /> | <Cross /> | <Cross /> |
|
|
1281
1292
|
| `mai-transcribe-2` | <Check /> | <Check /> | <Check /> | <Check /> |
|
|
1293
|
+
| `mai-transcribe-1.5` | <Check /> | <Check /> | <Check /> | <Check /> |
|
|
1282
1294
|
|
|
1283
1295
|
## Speech Models
|
|
1284
1296
|
|
|
1285
|
-
You can create models that call the Azure OpenAI speech API using the `.speech()` factory method.
|
|
1297
|
+
You can create models that call the Azure OpenAI speech API or Azure Speech text to speech using the `.speech()` factory method.
|
|
1286
1298
|
|
|
1287
|
-
The first argument is your deployment name for the text-to-speech model (e.g., `tts-1`)
|
|
1299
|
+
The first argument is your deployment name for the text-to-speech model (e.g., `tts-1`),
|
|
1300
|
+
or a [MAI-Voice](#mai-voice) model ID.
|
|
1288
1301
|
|
|
1289
1302
|
```ts
|
|
1290
1303
|
const model = azure.speech('your-tts-deployment-name');
|
|
@@ -1343,3 +1356,75 @@ Azure OpenAI supports TTS models through deployments. The capabilities depend on
|
|
|
1343
1356
|
| `tts-1` | <Cross /> |
|
|
1344
1357
|
| `tts-1-hd` | <Cross /> |
|
|
1345
1358
|
| `gpt-4o-mini-tts` | <Check /> |
|
|
1359
|
+
|
|
1360
|
+
### MAI-Voice
|
|
1361
|
+
|
|
1362
|
+
MAI-Voice models are multilingual text-to-speech models from Microsoft AI, served through Azure.
|
|
1363
|
+
The following model IDs use the Azure Speech API:
|
|
1364
|
+
|
|
1365
|
+
| Model ID | Notes |
|
|
1366
|
+
| ------------------- | --------------------------------------------- |
|
|
1367
|
+
| `mai-voice-2-flash` | Low latency, for voice agents and assistants. |
|
|
1368
|
+
| `mai-voice-2` | Highest fidelity, for long-form narration. |
|
|
1369
|
+
|
|
1370
|
+
All other IDs use the OpenAI API by default, including custom deployment names.
|
|
1371
|
+
|
|
1372
|
+
```ts
|
|
1373
|
+
import { azure, type AzureSpeechModelOptions } from '@ai-sdk/azure';
|
|
1374
|
+
import { generateSpeech } from 'ai';
|
|
1375
|
+
|
|
1376
|
+
const result = await generateSpeech({
|
|
1377
|
+
model: azure.speech('mai-voice-2-flash'),
|
|
1378
|
+
text: 'Thanks for calling! Your order shipped this morning.',
|
|
1379
|
+
voice: 'en-US-Ethan',
|
|
1380
|
+
providerOptions: {
|
|
1381
|
+
azure: { style: 'excited' } satisfies AzureSpeechModelOptions,
|
|
1382
|
+
},
|
|
1383
|
+
});
|
|
1384
|
+
```
|
|
1385
|
+
|
|
1386
|
+
MAI-Voice models require a Microsoft Foundry (Speech) resource in a region where they are available
|
|
1387
|
+
(see [Speech service regions](https://learn.microsoft.com/en-us/azure/ai-services/speech-service/regions)).
|
|
1388
|
+
They use the same settings as [MAI-Transcribe](#mai-transcribe): `resourceName` (or `AZURE_RESOURCE_NAME`),
|
|
1389
|
+
`apiKey` (or `AZURE_API_KEY`), `tokenProvider`, and `speechBaseURL`.
|
|
1390
|
+
|
|
1391
|
+
- **voice** is a prebuilt voice ID that includes its locale, such as `en-US-Harper`
|
|
1392
|
+
(the default), `de-DE-Mia`, or `es-MX-Valeria`. The voice locale selects the language.
|
|
1393
|
+
Full Azure voice names such as `es-MX-Valeria:MAI-Voice-2` are also accepted. Available
|
|
1394
|
+
voices vary by model; see
|
|
1395
|
+
[Azure's MAI-Voice guide](https://learn.microsoft.com/en-us/azure/ai-services/speech-service/mai-voices).
|
|
1396
|
+
- **language** picks a default voice when `voice` is not set (see the table below). Other
|
|
1397
|
+
languages and `auto` use `en-US-Harper` with a warning. When `voice` is set, its locale
|
|
1398
|
+
selects the language, and a conflicting `language` produces a warning.
|
|
1399
|
+
- **outputFormat** accepts `mp3` (default, 24 kHz), `wav`, `pcm` (headerless 24 kHz, 16-bit, mono), `opus` (Ogg),
|
|
1400
|
+
or any Azure `X-Microsoft-OutputFormat` value such as `audio-48khz-192kbitrate-mono-mp3`.
|
|
1401
|
+
Other values fall back to `mp3` with a warning. Azure labels raw formats such as `pcm` as `audio/basic`.
|
|
1402
|
+
- **speed** is a rate multiplier, for example `0.5` for half speed or `2` for double speed.
|
|
1403
|
+
- `instructions` is not supported and produces a warning.
|
|
1404
|
+
|
|
1405
|
+
| Language | Default voice | Language | Default voice |
|
|
1406
|
+
| -------- | --------------- | -------- | ------------- |
|
|
1407
|
+
| `de` | `de-DE-Mia` | `nl` | `nl-NL-Fleur` |
|
|
1408
|
+
| `en` | `en-US-Harper` | `pt` | `pt-BR-Luana` |
|
|
1409
|
+
| `es` | `es-MX-Valeria` | `ro` | `ro-RO-Elena` |
|
|
1410
|
+
| `fr` | `fr-FR-Soleil` | `ru` | `ru-RU-Masha` |
|
|
1411
|
+
| `hi` | `hi-IN-Kavya` | `th` | `th-TH-Krit` |
|
|
1412
|
+
| `hu` | `hu-HU-Lilla` | `tr` | `tr-TR-Elif` |
|
|
1413
|
+
| `it` | `it-IT-Rosa` | `zh` | `zh-CN-Mei` |
|
|
1414
|
+
| `ko` | `ko-KR-Haena` | | |
|
|
1415
|
+
|
|
1416
|
+
The following options are available through `providerOptions.azure`:
|
|
1417
|
+
|
|
1418
|
+
- **api** _'openai' | 'speech'_
|
|
1419
|
+
Overrides model-based API selection for this request.
|
|
1420
|
+
Set `openai` for an OpenAI deployment named after one of the model IDs above, or `speech` to
|
|
1421
|
+
send another model ID to Speech.
|
|
1422
|
+
|
|
1423
|
+
- **style** _string_
|
|
1424
|
+
Speaking style, such as `excited` or `whispering`. Supported styles vary by voice and model.
|
|
1425
|
+
|
|
1426
|
+
- **styleDegree** _number_
|
|
1427
|
+
Style intensity from 0.01 to 2. Azure defaults to 1. Requires `style`.
|
|
1428
|
+
|
|
1429
|
+
Text is always spoken as plain text; SSML input is not supported.
|
|
1430
|
+
The models are in public preview. AI Gateway forwards these provider options, including `azure.api`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-sdk/azure",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.89",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -29,10 +29,10 @@
|
|
|
29
29
|
}
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@ai-sdk/deepseek": "3.0.
|
|
33
|
-
"@ai-sdk/openai": "4.0.
|
|
34
|
-
"@ai-sdk/provider": "4.0.
|
|
35
|
-
"@ai-sdk/provider-utils": "5.0.
|
|
32
|
+
"@ai-sdk/deepseek": "3.0.58",
|
|
33
|
+
"@ai-sdk/openai": "4.0.83",
|
|
34
|
+
"@ai-sdk/provider": "4.0.21",
|
|
35
|
+
"@ai-sdk/provider-utils": "5.0.53"
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|
|
38
38
|
"@ai-sdk/test-server": "2.0.3",
|
|
@@ -15,10 +15,12 @@ import {
|
|
|
15
15
|
type LanguageModelV4,
|
|
16
16
|
type ProviderV4,
|
|
17
17
|
type ImageModelV4,
|
|
18
|
+
type SharedV4Warning,
|
|
18
19
|
type SpeechModelV4,
|
|
19
20
|
type TranscriptionModelV4,
|
|
20
21
|
} from '@ai-sdk/provider';
|
|
21
22
|
import {
|
|
23
|
+
isValidHostnamePart,
|
|
22
24
|
loadApiKey,
|
|
23
25
|
loadSetting,
|
|
24
26
|
normalizeHeaders,
|
|
@@ -31,10 +33,15 @@ import {
|
|
|
31
33
|
type FetchFunction,
|
|
32
34
|
} from '@ai-sdk/provider-utils';
|
|
33
35
|
import { azureOpenaiTools } from './azure-openai-tools';
|
|
36
|
+
import {
|
|
37
|
+
azureSpeechModelOptions,
|
|
38
|
+
getMAIVoiceModel,
|
|
39
|
+
} from './azure-speech-model-options';
|
|
40
|
+
import { AzureSpeechSpeechModel } from './azure-speech-speech-model';
|
|
34
41
|
import { AzureSpeechTranscriptionModel } from './azure-speech-transcription-model';
|
|
35
42
|
import {
|
|
36
43
|
azureTranscriptionModelOptions,
|
|
37
|
-
|
|
44
|
+
getMAITranscribeModel,
|
|
38
45
|
} from './azure-transcription-model-options';
|
|
39
46
|
import { VERSION } from './version';
|
|
40
47
|
|
|
@@ -97,8 +104,8 @@ export interface AzureOpenAIProvider extends ProviderV4 {
|
|
|
97
104
|
imageModel(deploymentId: string): ImageModelV4;
|
|
98
105
|
|
|
99
106
|
/**
|
|
100
|
-
* Creates an Azure transcription model. MAI-Transcribe
|
|
101
|
-
* by default; other IDs use OpenAI. Override with providerOptions.azure.api.
|
|
107
|
+
* Creates an Azure transcription model. MAI-Transcribe models use the Speech
|
|
108
|
+
* API by default; other IDs use OpenAI. Override with providerOptions.azure.api.
|
|
102
109
|
*/
|
|
103
110
|
transcription(deploymentId: string): TranscriptionModelV4;
|
|
104
111
|
|
|
@@ -108,10 +115,16 @@ export interface AzureOpenAIProvider extends ProviderV4 {
|
|
|
108
115
|
transcriptionModel(deploymentId: string): TranscriptionModelV4;
|
|
109
116
|
|
|
110
117
|
/**
|
|
111
|
-
* Creates an Azure
|
|
118
|
+
* Creates an Azure speech generation model. MAI-Voice models use the Speech
|
|
119
|
+
* API by default; other IDs use OpenAI. Override with providerOptions.azure.api.
|
|
112
120
|
*/
|
|
113
121
|
speech(deploymentId: string): SpeechModelV4;
|
|
114
122
|
|
|
123
|
+
/**
|
|
124
|
+
* Creates an Azure speech generation model. Alias of `speech`.
|
|
125
|
+
*/
|
|
126
|
+
speechModel(deploymentId: string): SpeechModelV4;
|
|
127
|
+
|
|
115
128
|
/**
|
|
116
129
|
* AzureOpenAI-specific tools.
|
|
117
130
|
*/
|
|
@@ -174,8 +187,9 @@ export interface AzureOpenAIProviderSettings {
|
|
|
174
187
|
useDeploymentBasedUrls?: boolean;
|
|
175
188
|
|
|
176
189
|
/**
|
|
177
|
-
* URL prefix for Azure Speech
|
|
178
|
-
* regional endpoint like
|
|
190
|
+
* URL prefix for Azure Speech (MAI-Transcribe transcription and MAI-Voice
|
|
191
|
+
* speech), e.g. a regional endpoint like
|
|
192
|
+
* `https://eastus.api.cognitive.microsoft.com`.
|
|
179
193
|
* Defaults to `https://{resourceName}.cognitiveservices.azure.com`.
|
|
180
194
|
* Speech requests do not use `baseURL` or `apiVersion`.
|
|
181
195
|
*/
|
|
@@ -270,7 +284,7 @@ export function createAzure(
|
|
|
270
284
|
|
|
271
285
|
// The resource name becomes part of the request host, so only a DNS label
|
|
272
286
|
// is accepted (e.g. `user@internal:8080/#` would rewrite the host).
|
|
273
|
-
if (
|
|
287
|
+
if (!isValidHostnamePart(resourceName)) {
|
|
274
288
|
throw new InvalidArgumentError({
|
|
275
289
|
argument: 'resourceName',
|
|
276
290
|
message:
|
|
@@ -377,6 +391,10 @@ export function createAzure(
|
|
|
377
391
|
},
|
|
378
392
|
});
|
|
379
393
|
|
|
394
|
+
const speechBaseURL = () =>
|
|
395
|
+
withoutTrailingSlash(options.speechBaseURL) ??
|
|
396
|
+
`https://${getResourceName()}.cognitiveservices.azure.com`;
|
|
397
|
+
|
|
380
398
|
const createTranscriptionModel = (modelId: string) =>
|
|
381
399
|
new AzureTranscriptionModel(
|
|
382
400
|
modelId,
|
|
@@ -389,22 +407,28 @@ export function createAzure(
|
|
|
389
407
|
}),
|
|
390
408
|
new AzureSpeechTranscriptionModel(modelId, {
|
|
391
409
|
url: () =>
|
|
392
|
-
`${
|
|
393
|
-
withoutTrailingSlash(options.speechBaseURL) ??
|
|
394
|
-
`https://${getResourceName()}.cognitiveservices.azure.com`
|
|
395
|
-
}/speechtotext/transcriptions:transcribe?api-version=2025-10-15`,
|
|
410
|
+
`${speechBaseURL()}/speechtotext/transcriptions:transcribe?api-version=2025-10-15`,
|
|
396
411
|
headers: () => getHeaders('speech'),
|
|
397
412
|
fetch,
|
|
398
413
|
}),
|
|
399
414
|
);
|
|
400
415
|
|
|
401
416
|
const createSpeechModel = (modelId: string) =>
|
|
402
|
-
new
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
417
|
+
new AzureSpeechModel(
|
|
418
|
+
modelId,
|
|
419
|
+
options,
|
|
420
|
+
new OpenAISpeechModel(modelId, {
|
|
421
|
+
provider: 'azure.speech',
|
|
422
|
+
url,
|
|
423
|
+
headers: getHeaders,
|
|
424
|
+
fetch,
|
|
425
|
+
}),
|
|
426
|
+
new AzureSpeechSpeechModel(modelId, {
|
|
427
|
+
url: () => `${speechBaseURL()}/tts/cognitiveservices/v1`,
|
|
428
|
+
headers: () => getHeaders('speech'),
|
|
429
|
+
fetch,
|
|
430
|
+
}),
|
|
431
|
+
);
|
|
408
432
|
|
|
409
433
|
const provider = function (deploymentId: string) {
|
|
410
434
|
if (new.target) {
|
|
@@ -431,6 +455,7 @@ export function createAzure(
|
|
|
431
455
|
provider.transcription = createTranscriptionModel;
|
|
432
456
|
provider.transcriptionModel = createTranscriptionModel;
|
|
433
457
|
provider.speech = createSpeechModel;
|
|
458
|
+
provider.speechModel = createSpeechModel;
|
|
434
459
|
provider.tools = azureOpenaiTools;
|
|
435
460
|
return provider;
|
|
436
461
|
}
|
|
@@ -513,7 +538,67 @@ class AzureTranscriptionModel implements TranscriptionModelV4 {
|
|
|
513
538
|
return {
|
|
514
539
|
...options,
|
|
515
540
|
api:
|
|
516
|
-
options?.api ??
|
|
541
|
+
options?.api ??
|
|
542
|
+
(getMAITranscribeModel(this.modelId) ? 'speech' : 'openai'),
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// Resolves the API per request: providerOptions also reach this model via Gateway.
|
|
548
|
+
class AzureSpeechModel implements SpeechModelV4 {
|
|
549
|
+
readonly specificationVersion = 'v4';
|
|
550
|
+
readonly provider = 'azure.speech';
|
|
551
|
+
|
|
552
|
+
constructor(
|
|
553
|
+
readonly modelId: string,
|
|
554
|
+
private readonly config: AzureOpenAIProviderSettings,
|
|
555
|
+
private readonly openai: OpenAISpeechModel,
|
|
556
|
+
private readonly speech: AzureSpeechSpeechModel,
|
|
557
|
+
) {}
|
|
558
|
+
|
|
559
|
+
static [WORKFLOW_SERIALIZE](model: AzureSpeechModel) {
|
|
560
|
+
return serializeModelOptions({
|
|
561
|
+
modelId: model.modelId,
|
|
562
|
+
config: model.config,
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
static [WORKFLOW_DESERIALIZE](options: {
|
|
567
|
+
modelId: string;
|
|
568
|
+
config: AzureOpenAIProviderSettings;
|
|
569
|
+
}) {
|
|
570
|
+
return createAzure(options.config).speech(options.modelId);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
async doGenerate(options: Parameters<SpeechModelV4['doGenerate']>[0]) {
|
|
574
|
+
const { api, ...speechOptions } =
|
|
575
|
+
(await parseProviderOptions({
|
|
576
|
+
provider: 'azure',
|
|
577
|
+
providerOptions: options.providerOptions,
|
|
578
|
+
schema: azureSpeechModelOptions,
|
|
579
|
+
})) ?? {};
|
|
580
|
+
if (
|
|
581
|
+
(api ?? (getMAIVoiceModel(this.modelId) ? 'speech' : 'openai')) ===
|
|
582
|
+
'speech'
|
|
583
|
+
) {
|
|
584
|
+
return this.speech.doGenerate(options, speechOptions);
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
const result = await this.openai.doGenerate(options);
|
|
588
|
+
return {
|
|
589
|
+
...result,
|
|
590
|
+
warnings: [
|
|
591
|
+
...result.warnings,
|
|
592
|
+
...Object.entries(speechOptions)
|
|
593
|
+
.filter(([, value]) => value !== undefined)
|
|
594
|
+
.map(
|
|
595
|
+
([key]): SharedV4Warning => ({
|
|
596
|
+
type: 'unsupported',
|
|
597
|
+
feature: `providerOptions.azure.${key}`,
|
|
598
|
+
details: 'This option requires the Azure Speech API.',
|
|
599
|
+
}),
|
|
600
|
+
),
|
|
601
|
+
],
|
|
517
602
|
};
|
|
518
603
|
}
|
|
519
604
|
}
|