@ai-sdk/azure 4.0.89 → 4.0.90
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 +6 -0
- package/dist/index.d.ts +17 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +308 -27
- package/dist/index.js.map +1 -1
- package/docs/04-azure.mdx +93 -13
- package/package.json +1 -1
- package/src/azure-mai-transcription-model-options.ts +22 -0
- package/src/azure-mai-transcription-model.ts +371 -0
- package/src/azure-openai-provider.ts +105 -31
- package/src/azure-speech-model-options.ts +2 -0
- package/src/azure-speech-speech-model.ts +14 -7
- package/src/azure-transcription-model-options.ts +9 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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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AG;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"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/azure-mai-transcription-model.ts","../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-mai-transcription-model-options.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 InvalidArgumentError,\n UnsupportedFunctionalityError,\n type Experimental_TranscriptionModelV4StreamPart as TranscriptionModelV4StreamPart,\n type SharedV4Warning,\n type TranscriptionModelV4,\n} from '@ai-sdk/provider';\nimport {\n connectToWebSocket,\n convertToBase64,\n safeParseJSON,\n toWebSocketUrl,\n waitForWebSocketBufferDrain,\n type WebSocketConnection,\n type WebSocketConstructor,\n type WebSocketLike,\n} from '@ai-sdk/provider-utils';\nimport type { AzureTranscriptionModelMaiOptions } from './azure-mai-transcription-model-options';\n\ntype StreamOptions = Parameters<\n NonNullable<TranscriptionModelV4['doStream']>\n>[0];\n\nconst SUPPORTED_SAMPLE_RATES = [16000, 24000];\nconst DEFAULT_SAMPLE_RATE = 24000;\n\n/**\n * MAI streaming transcription over the OpenAI Realtime-compatible\n * `/mai/v1/realtime` WebSocket. The model ID is the Foundry deployment name.\n */\nexport class AzureMaiTranscriptionModel 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: () =>\n | Record<string, string | undefined>\n | PromiseLike<Record<string, string | undefined>>;\n webSocket?: WebSocketConstructor;\n _internal?: { currentDate?: () => Date };\n },\n ) {}\n\n async doGenerate(): Promise<\n Awaited<ReturnType<TranscriptionModelV4['doGenerate']>>\n > {\n throw new UnsupportedFunctionalityError({\n functionality: `file transcription with ${this.modelId} (use streaming transcription)`,\n });\n }\n\n async doStream(\n options: StreamOptions,\n maiOptions: AzureTranscriptionModelMaiOptions = {},\n warnings: SharedV4Warning[] = [],\n ): Promise<\n Awaited<ReturnType<NonNullable<TranscriptionModelV4['doStream']>>>\n > {\n const currentDate = this.config._internal?.currentDate?.() ?? new Date();\n const { type, rate = DEFAULT_SAMPLE_RATE } = options.inputAudioFormat;\n if (type !== 'audio/pcm' || !SUPPORTED_SAMPLE_RATES.includes(rate)) {\n throw new InvalidArgumentError({\n argument: 'inputAudioFormat',\n message: `MAI streaming transcription requires 16-bit mono PCM (audio/pcm) at 16000 or 24000 Hz, got ${type}${options.inputAudioFormat.rate != null ? ` at ${rate} Hz` : ''}.`,\n });\n }\n\n const sessionUpdate = {\n type: 'session.update',\n session: {\n type: 'transcription',\n audio: {\n input: {\n format: { type: 'audio/pcm', rate },\n transcription: {\n model: this.modelId,\n ...(maiOptions.language != null\n ? { language: maiOptions.language }\n : {}),\n },\n // MAI supports neither server VAD nor noise reduction; the stream\n // commits once when the input audio ends.\n turn_detection: null,\n noise_reduction: null,\n },\n },\n },\n };\n\n const headers = {\n ...(await this.config.headers()),\n ...options.headers,\n };\n // Native WebSocket constructors drop headers, so bearer auth would be lost.\n if (\n this.config.webSocket == null &&\n Object.entries(headers).some(\n ([key, value]) =>\n key.toLowerCase() === 'authorization' && value != null,\n )\n ) {\n throw new InvalidArgumentError({\n argument: 'webSocket',\n message:\n 'MAI streaming transcription with Microsoft Entra ID (tokenProvider) or an Authorization header requires a custom webSocket implementation such as `ws`, because the native WebSocket cannot send headers.',\n });\n }\n\n return {\n request: { body: sessionUpdate },\n response: { timestamp: currentDate, modelId: this.modelId },\n stream: createMaiTranscriptionStream({\n ...getConnection({\n url: toWebSocketUrl(this.config.url()),\n headers,\n supportsHeaders: this.config.webSocket != null,\n }),\n webSocket: this.config.webSocket,\n sessionUpdate,\n bytesPerSecond: rate * 2,\n language: maiOptions.language,\n warnings,\n audio: options.audio,\n abortSignal: options.abortSignal,\n includeRawChunks: options.includeRawChunks,\n }),\n };\n }\n}\n\n// Native WebSocket constructors cannot send headers, so the key moves to the\n// `api-key` query parameter that MAI also accepts.\nfunction getConnection({\n url,\n headers,\n supportsHeaders,\n}: {\n url: URL;\n headers: Record<string, string | undefined>;\n supportsHeaders: boolean;\n}) {\n if (supportsHeaders) {\n return { url, headers };\n }\n const remaining: Record<string, string | undefined> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === 'api-key') {\n if (value != null) url.searchParams.set('api-key', value);\n } else {\n remaining[key] = value;\n }\n }\n return { url, headers: remaining };\n}\n\ntype MaiRealtimeEvent = {\n type?: string;\n item_id?: string;\n delta?: string;\n intermediate?: string;\n transcript?: string;\n error?: { message?: string; code?: string };\n};\n\nfunction createMaiTranscriptionStream({\n url,\n headers,\n webSocket,\n sessionUpdate,\n bytesPerSecond,\n language,\n warnings,\n audio,\n abortSignal,\n includeRawChunks,\n}: {\n url: URL;\n headers: Record<string, string | undefined>;\n webSocket: WebSocketConstructor | undefined;\n sessionUpdate: unknown;\n bytesPerSecond: number;\n language: string | undefined;\n warnings: SharedV4Warning[];\n audio: ReadableStream<Uint8Array | string>;\n abortSignal: AbortSignal | undefined;\n includeRawChunks: boolean | undefined;\n}) {\n let finished = false;\n let cleanup: (closeCode?: number) => void = () => {};\n\n return new ReadableStream<TranscriptionModelV4StreamPart>({\n start: controller => {\n let audioReader:\n | ReadableStreamDefaultReader<Uint8Array | string>\n | undefined;\n let connection: WebSocketConnection | undefined;\n let audioStarted = false;\n let committed = false;\n let audioBytes = 0;\n let deltas = '';\n\n cleanup = (closeCode?: number) => {\n if (audioReader != null) {\n void audioReader.cancel().catch(() => {});\n } else {\n void audio.cancel().catch(() => {});\n }\n connection?.close(closeCode);\n };\n\n const finishWithError = (error: unknown) => {\n if (finished) return;\n finished = true;\n cleanup();\n controller.error(error);\n };\n\n const finish = (text: string) => {\n if (finished) return;\n finished = true;\n controller.enqueue({\n type: 'finish',\n text,\n segments: [],\n language,\n ...(audioBytes > 0\n ? { durationInSeconds: audioBytes / bytesPerSecond }\n : {}),\n });\n controller.close();\n cleanup(1000);\n };\n\n const sendAudio = async (socket: WebSocketLike) => {\n audioReader = audio.getReader();\n try {\n while (true) {\n const { done, value } = await audioReader.read();\n if (done || finished) break;\n const base64 = convertToBase64(value);\n if (base64.length === 0) continue;\n audioBytes +=\n typeof value === 'string'\n ? base64ByteLength(base64)\n : value.byteLength;\n socket.send(\n JSON.stringify({\n type: 'input_audio_buffer.append',\n audio: base64,\n }),\n );\n await waitForWebSocketBufferDrain(socket);\n }\n } finally {\n audioReader.releaseLock();\n audioReader = undefined;\n }\n if (finished) return;\n if (audioBytes === 0) {\n finish('');\n return;\n }\n committed = true;\n socket.send(JSON.stringify({ type: 'input_audio_buffer.commit' }));\n };\n\n connection = connectToWebSocket({\n url,\n headers,\n webSocket,\n abortSignal,\n onAbort: finishWithError,\n onProcessingError: finishWithError,\n onOpen: () => {\n controller.enqueue({ type: 'stream-start', warnings });\n },\n onMessageText: async text => {\n const parsed = await safeParseJSON({ text });\n if (!parsed.success) return;\n const event = parsed.value as MaiRealtimeEvent;\n const socket = connection?.socket;\n\n if (includeRawChunks) {\n controller.enqueue({ type: 'raw', rawValue: event });\n }\n\n switch (event.type) {\n case 'session.created': {\n socket?.send(JSON.stringify(sessionUpdate));\n break;\n }\n\n // Settings are locked after the first append, so audio waits for\n // the server to acknowledge the session configuration.\n case 'session.updated': {\n if (audioStarted || socket == null) break;\n audioStarted = true;\n void sendAudio(socket).catch(finishWithError);\n break;\n }\n\n case 'conversation.item.input_audio_transcription.delta': {\n deltas += event.delta ?? '';\n controller.enqueue({\n type: 'transcript-delta',\n id: event.item_id,\n delta: event.delta ?? '',\n });\n break;\n }\n\n // MAI-specific: the provisional text after the latest delta.\n case 'conversation.item.input_audio_transcription.intermediate': {\n controller.enqueue({\n type: 'transcript-partial',\n id: event.item_id,\n text: event.intermediate ?? '',\n });\n break;\n }\n\n case 'conversation.item.input_audio_transcription.completed': {\n const transcript = event.transcript ?? deltas;\n controller.enqueue({\n type: 'transcript-final',\n id: event.item_id,\n text: transcript,\n });\n if (committed) finish(transcript);\n break;\n }\n\n case 'conversation.item.input_audio_transcription.failed':\n case 'error': {\n finishWithError(\n new Error(\n `Azure MAI transcription error${event.error?.code != null ? ` (${event.error.code})` : ''}: ${event.error?.message ?? 'unknown error'}`,\n ),\n );\n break;\n }\n }\n },\n onSocketError: () => {\n finishWithError(new Error('Azure MAI transcription WebSocket error'));\n },\n onClose: ({ code, reason }) => {\n finishWithError(\n new Error(\n `Azure MAI transcription connection closed before the transcript completed${code != null ? ` (code ${code}${reason ? `: ${reason}` : ''})` : ''}`,\n ),\n );\n },\n });\n },\n\n cancel: () => {\n if (finished) return;\n finished = true;\n cleanup();\n },\n });\n}\n\nfunction base64ByteLength(base64: string) {\n const padding = base64.endsWith('==') ? 2 : base64.endsWith('=') ? 1 : 0;\n return (base64.length * 3) / 4 - padding;\n}\n","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.1-flash', 'MAI-Voice-2.1-Flash'],\n ['mai-voice-2.1', 'MAI-Voice-2.1'],\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,\n// MAI-Voice-2.1, and their Flash variants.\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 (style or output format) with an empty\n// 400 body. Unknown voices or styles reset the connection with an Envoy 502\n// whose reason is `protocol error`; other 502s stay retryable.\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 const isVoiceReset =\n response.status === 502 &&\n responseBody.includes('reset reason: protocol error');\n\n const message = parsed.success\n ? parsed.value.error.message\n : isVoiceReset\n ? 'Azure Speech could not synthesize the request. Check that the voice is available for this model and that the style is supported by the voice.'\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 isRetryable: isVoiceReset ? false : undefined,\n }),\n };\n};\n","import {\n lazySchema,\n zodSchema,\n type InferSchema,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\n\nexport const azureMaiTranscriptionModelOptionsShape = () => ({\n /**\n * Language hint for streaming transcription, e.g. `en`. Omit for automatic\n * language detection.\n */\n language: z.string().min(1).optional(),\n});\n\nexport const azureMaiTranscriptionModelOptions = lazySchema(() =>\n zodSchema(z.strictObject(azureMaiTranscriptionModelOptionsShape())),\n);\n\nexport type AzureTranscriptionModelMaiOptions = InferSchema<\n typeof azureMaiTranscriptionModelOptions\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 { azureMaiTranscriptionModelOptionsShape } from './azure-mai-transcription-model-options';\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, MAI for\n * MAI-Transcribe-2-Streaming, and OpenAI otherwise.\n */\n api: z.enum(['openai', 'speech', 'mai']).optional(),\n ...azureSpeechTranscriptionModelOptionsShape(),\n ...azureMaiTranscriptionModelOptionsShape(),\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\nexport function isMAITranscribeStreaming(modelId: string): boolean {\n return modelId.toLowerCase() === 'mai-transcribe-2-streaming';\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 type WebSocketConstructor,\n} from '@ai-sdk/provider-utils';\nimport { AzureMaiTranscriptionModel } from './azure-mai-transcription-model';\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 isMAITranscribeStreaming,\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 and MAI-Transcribe-2-Streaming the MAI realtime API by default; other\n * 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 /**\n * URL prefix for MAI realtime APIs (MAI-Transcribe-2-Streaming).\n * Defaults to `https://{resourceName}.services.ai.azure.com/mai/v1`.\n */\n maiBaseURL?: string;\n\n /**\n * Custom WebSocket implementation for MAI streaming transcription, e.g.\n * `ws` in Node.js. With a custom implementation the API key is sent as a\n * header; otherwise it is sent as the `api-key` query parameter. Entra ID\n * tokens require a custom implementation; streaming rejects them otherwise.\n */\n webSocket?: WebSocketConstructor;\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' | 'mai' = '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:\n api === 'speech'\n ? 'Azure Speech'\n : api === 'mai'\n ? 'Azure MAI'\n : '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 new AzureMaiTranscriptionModel(modelId, {\n url: () =>\n `${\n withoutTrailingSlash(options.maiBaseURL) ??\n `https://${getResourceName()}.services.ai.azure.com/mai/v1`\n }/realtime?intent=transcription`,\n headers: async () =>\n tokenProvider\n ? {\n authorization: `Bearer ${await tokenProvider()}`,\n ...getHeaders('mai'),\n }\n : getHeaders('mai'),\n webSocket: options.webSocket,\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 private readonly mai: AzureMaiTranscriptionModel,\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, maiOptions } = await this.getOptions(\n options.providerOptions,\n );\n if (api === 'mai') {\n return this.mai.doGenerate();\n }\n if (api === 'speech') {\n const result = await this.speech.doGenerate(options, speechOptions);\n return {\n ...result,\n warnings: [...result.warnings, ...maiOnlyWarnings(maiOptions)],\n };\n }\n\n const result = await this.openai.doGenerate(options);\n return {\n ...result,\n warnings: [\n ...result.warnings,\n ...speechOnlyWarnings(speechOptions),\n ...maiOnlyWarnings(maiOptions),\n ],\n };\n }\n\n async doStream(\n options: Parameters<NonNullable<TranscriptionModelV4['doStream']>>[0],\n ) {\n const { api, speechOptions, maiOptions } = await this.getOptions(\n options.providerOptions,\n );\n if (api === 'speech') {\n throw new UnsupportedFunctionalityError({\n functionality: 'streaming transcription with the Azure Speech API',\n });\n }\n if (api === 'mai') {\n return this.mai.doStream(\n options,\n maiOptions,\n speechOnlyWarnings(speechOptions),\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 { api, language, ...speechOptions } =\n (await parseProviderOptions({\n provider: 'azure',\n providerOptions,\n schema: azureTranscriptionModelOptions,\n })) ?? {};\n return {\n api:\n api ??\n (isMAITranscribeStreaming(this.modelId)\n ? ('mai' as const)\n : getMAITranscribeModel(this.modelId)\n ? ('speech' as const)\n : ('openai' as const)),\n speechOptions,\n maiOptions: language != null ? { language } : {},\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: [...result.warnings, ...speechOnlyWarnings(speechOptions)],\n };\n }\n}\n\nfunction speechOnlyWarnings(options: Record<string, unknown>) {\n return unsupportedOptionWarnings(\n options,\n 'This option requires the Azure Speech API.',\n );\n}\n\nfunction maiOnlyWarnings(options: Record<string, unknown>) {\n return unsupportedOptionWarnings(\n options,\n 'This option requires MAI streaming transcription.',\n );\n}\n\nfunction unsupportedOptionWarnings(\n options: Record<string, unknown>,\n details: string,\n): SharedV4Warning[] {\n return Object.entries(options)\n .filter(([, value]) => value !== undefined)\n .map(([key]) => ({\n type: 'unsupported',\n feature: `providerOptions.azure.${key}`,\n details,\n }));\n}\n"],"mappings":";;;;;;AAuBA,MAAM,yBAAyB,CAAC,MAAO,IAAK;AAC5C,MAAM,sBAAsB;;;;;AAM5B,IAAa,6BAAb,MAAwE;CAItE,YACE,SACA,QAQA;EATS,KAAA,UAAA;EACQ,KAAA,SAAA;EALa,KAAA,uBAAA;EACZ,KAAA,WAAA;CAYjB;CAEH,MAAM,aAEJ;EACA,MAAM,IAAI,8BAA8B,EACtC,eAAe,2BAA2B,KAAK,QAAQ,gCACzD,CAAC;CACH;CAEA,MAAM,SACJ,SACA,aAAgD,CAAC,GACjD,WAA8B,CAAC,GAG/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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,CAAC,GAAG,OAAO,UAAU,GAAG,mBAAmB,aAAa,CAAC;EACrE;CACF;AACF;AAEA,SAAS,mBAAmB,SAAkC;CAC5D,OAAO,0BACL,SACA,4CACF;AACF;AAEA,SAAS,gBAAgB,SAAkC;CACzD,OAAO,0BACL,SACA,mDACF;AACF;AAEA,SAAS,0BACP,SACA,SACmB;CACnB,OAAO,OAAO,QAAQ,OAAO,CAAC,CAC3B,QAAQ,GAAG,WAAW,UAAU,KAAA,CAAS,CAAC,CAC1C,KAAK,CAAC,UAAU;EACf,MAAM;EACN,SAAS,yBAAyB;EAClC;CACF,EAAE;AACN"}
|
package/docs/04-azure.mdx
CHANGED
|
@@ -139,6 +139,20 @@ You can use the following optional settings to customize the OpenAI provider ins
|
|
|
139
139
|
Defaults to `https://{resourceName}.cognitiveservices.azure.com`.
|
|
140
140
|
Speech requests do not use `baseURL` or `apiVersion`.
|
|
141
141
|
|
|
142
|
+
- **maiBaseURL** _string_
|
|
143
|
+
|
|
144
|
+
URL prefix for MAI realtime requests (MAI-Transcribe-2-Streaming).
|
|
145
|
+
Defaults to `https://{resourceName}.services.ai.azure.com/mai/v1`.
|
|
146
|
+
|
|
147
|
+
- **webSocket** _WebSocketConstructor_
|
|
148
|
+
|
|
149
|
+
Custom WebSocket implementation for MAI streaming transcription, for example
|
|
150
|
+
the `WebSocket` export of the `ws` package in Node.js. With a custom
|
|
151
|
+
implementation the API key is sent in the `api-key` header; with the native
|
|
152
|
+
`WebSocket` it is sent as the `api-key` query parameter. Microsoft Entra ID
|
|
153
|
+
(`tokenProvider`) authentication requires a custom implementation; without one,
|
|
154
|
+
streaming fails with an `InvalidArgumentError` before connecting.
|
|
155
|
+
|
|
142
156
|
## Language Models
|
|
143
157
|
|
|
144
158
|
The Azure OpenAI provider instance is a function that you can invoke to create a language model:
|
|
@@ -1125,7 +1139,9 @@ and sent to Azure under their Azure model names:
|
|
|
1125
1139
|
| `mai-transcribe-2` | `MAI-Transcribe-2` | Supports every option below. |
|
|
1126
1140
|
| `mai-transcribe-1.5` | `MAI-Transcribe-1.5` | Supports `locales` and `phraseList`. |
|
|
1127
1141
|
|
|
1128
|
-
|
|
1142
|
+
`mai-transcribe-2-streaming` uses the MAI realtime API; see
|
|
1143
|
+
[MAI-Transcribe-2-Streaming](#mai-transcribe-2-streaming). All other IDs use the
|
|
1144
|
+
OpenAI API by default, including custom deployment names.
|
|
1129
1145
|
|
|
1130
1146
|
```ts
|
|
1131
1147
|
import { azure, type AzureTranscriptionModelOptions } from '@ai-sdk/azure';
|
|
@@ -1216,12 +1232,73 @@ milliseconds in metadata and seconds in normalized `segments`.
|
|
|
1216
1232
|
|
|
1217
1233
|
MAI-Transcribe models are file transcription models: they accept WAV, MP3, or FLAC files
|
|
1218
1234
|
shorter than 2 hours and smaller than 250 MB, and do not support streaming
|
|
1219
|
-
transcription
|
|
1235
|
+
transcription; use [MAI-Transcribe-2-Streaming](#mai-transcribe-2-streaming) to stream.
|
|
1236
|
+
The models are in public preview. See
|
|
1220
1237
|
[Azure's MAI-Transcribe guide](https://learn.microsoft.com/en-us/azure/ai-services/speech-service/mai-transcribe)
|
|
1221
1238
|
for supported languages and diarization limits.
|
|
1222
1239
|
|
|
1223
1240
|
AI Gateway forwards these provider options, including `azure.api`.
|
|
1224
1241
|
|
|
1242
|
+
### MAI-Transcribe-2-Streaming
|
|
1243
|
+
|
|
1244
|
+
MAI-Transcribe-2-Streaming is a low-latency streaming speech-to-text model from Microsoft AI.
|
|
1245
|
+
`azure.transcription('mai-transcribe-2-streaming')` streams audio to the MAI realtime API
|
|
1246
|
+
(`wss://{resourceName}.services.ai.azure.com/mai/v1/realtime`) with
|
|
1247
|
+
[`experimental_streamTranscribe`](/docs/ai-sdk-core/transcription#streaming-transcription).
|
|
1248
|
+
The model ID is sent to Azure as the Foundry deployment name, so deploy the model
|
|
1249
|
+
as `mai-transcribe-2-streaming`, or set `api: 'mai'` for other deployment names.
|
|
1250
|
+
|
|
1251
|
+
```ts
|
|
1252
|
+
import {
|
|
1253
|
+
createAzure,
|
|
1254
|
+
type AzureOpenAIProviderSettings,
|
|
1255
|
+
type AzureTranscriptionModelOptions,
|
|
1256
|
+
} from '@ai-sdk/azure';
|
|
1257
|
+
import { experimental_streamTranscribe as streamTranscribe } from 'ai';
|
|
1258
|
+
import { WebSocket } from 'ws';
|
|
1259
|
+
|
|
1260
|
+
const azure = createAzure({
|
|
1261
|
+
// `ws`'s WebSocket type differs from the DOM-style WebSocketConstructor.
|
|
1262
|
+
webSocket: WebSocket as unknown as AzureOpenAIProviderSettings['webSocket'],
|
|
1263
|
+
});
|
|
1264
|
+
|
|
1265
|
+
const result = streamTranscribe({
|
|
1266
|
+
model: azure.transcription('mai-transcribe-2-streaming'),
|
|
1267
|
+
audio, // ReadableStream of 16-bit mono PCM chunks
|
|
1268
|
+
inputAudioFormat: { type: 'audio/pcm', rate: 24000 },
|
|
1269
|
+
providerOptions: {
|
|
1270
|
+
azure: { language: 'en' } satisfies AzureTranscriptionModelOptions,
|
|
1271
|
+
},
|
|
1272
|
+
});
|
|
1273
|
+
|
|
1274
|
+
for await (const part of result.fullStream) {
|
|
1275
|
+
if (part.type === 'transcript-delta') {
|
|
1276
|
+
process.stdout.write(part.delta);
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
```
|
|
1280
|
+
|
|
1281
|
+
The model requires a Microsoft Foundry resource with a MAI-Transcribe-2-Streaming
|
|
1282
|
+
deployment in a supported region, such as `centralus`.
|
|
1283
|
+
Input audio must be 16-bit mono PCM (`audio/pcm`) at 16000 or 24000 Hz; the default is 24000 Hz.
|
|
1284
|
+
|
|
1285
|
+
The stream emits `transcript-delta` parts for finalized text and `transcript-partial`
|
|
1286
|
+
parts for the provisional text that follows the latest delta. MAI does not detect
|
|
1287
|
+
pauses on the server, so the stream commits once when the input audio ends and then
|
|
1288
|
+
emits a `transcript-final` part and the finished transcript. `durationInSeconds` is
|
|
1289
|
+
computed from the streamed audio.
|
|
1290
|
+
|
|
1291
|
+
The following options are available through `providerOptions.azure`:
|
|
1292
|
+
|
|
1293
|
+
- **api** _'openai' | 'speech' | 'mai'_
|
|
1294
|
+
Set `mai` to stream with a deployment that has a different name.
|
|
1295
|
+
|
|
1296
|
+
- **language** _string_
|
|
1297
|
+
Language hint such as `en`. Omit for automatic language detection.
|
|
1298
|
+
|
|
1299
|
+
File transcription options such as `timestamps` produce warnings when streaming.
|
|
1300
|
+
MAI-Transcribe-2-Streaming does not support file transcription.
|
|
1301
|
+
|
|
1225
1302
|
### OpenAI transcription
|
|
1226
1303
|
|
|
1227
1304
|
<Note>
|
|
@@ -1284,13 +1361,14 @@ The following provider options are available:
|
|
|
1284
1361
|
|
|
1285
1362
|
### Model Capabilities
|
|
1286
1363
|
|
|
1287
|
-
| Model
|
|
1288
|
-
|
|
|
1289
|
-
| `whisper-1`
|
|
1290
|
-
| `gpt-4o-mini-transcribe`
|
|
1291
|
-
| `gpt-4o-transcribe`
|
|
1292
|
-
| `mai-transcribe-2`
|
|
1293
|
-
| `mai-transcribe-1.5`
|
|
1364
|
+
| Model | Transcription | Duration | Segments | Language |
|
|
1365
|
+
| ---------------------------- | --------------------- | --------- | --------- | --------- |
|
|
1366
|
+
| `whisper-1` | <Check /> | <Check /> | <Check /> | <Check /> |
|
|
1367
|
+
| `gpt-4o-mini-transcribe` | <Check /> | <Cross /> | <Cross /> | <Cross /> |
|
|
1368
|
+
| `gpt-4o-transcribe` | <Check /> | <Cross /> | <Cross /> | <Cross /> |
|
|
1369
|
+
| `mai-transcribe-2` | <Check /> | <Check /> | <Check /> | <Check /> |
|
|
1370
|
+
| `mai-transcribe-1.5` | <Check /> | <Check /> | <Check /> | <Check /> |
|
|
1371
|
+
| `mai-transcribe-2-streaming` | <Check /> (streaming) | <Check /> | <Cross /> | <Cross /> |
|
|
1294
1372
|
|
|
1295
1373
|
## Speech Models
|
|
1296
1374
|
|
|
@@ -1362,10 +1440,12 @@ Azure OpenAI supports TTS models through deployments. The capabilities depend on
|
|
|
1362
1440
|
MAI-Voice models are multilingual text-to-speech models from Microsoft AI, served through Azure.
|
|
1363
1441
|
The following model IDs use the Azure Speech API:
|
|
1364
1442
|
|
|
1365
|
-
| Model ID
|
|
1366
|
-
|
|
|
1367
|
-
| `mai-voice-2-flash` | Low latency, for voice agents and assistants. |
|
|
1368
|
-
| `mai-voice-2` | Highest fidelity, for long-form narration. |
|
|
1443
|
+
| Model ID | Notes |
|
|
1444
|
+
| --------------------- | --------------------------------------------- |
|
|
1445
|
+
| `mai-voice-2.1-flash` | Low latency, for voice agents and assistants. |
|
|
1446
|
+
| `mai-voice-2.1` | Highest fidelity, for long-form narration. |
|
|
1447
|
+
| `mai-voice-2-flash` | Low latency, for voice agents and assistants. |
|
|
1448
|
+
| `mai-voice-2` | Highest fidelity, for long-form narration. |
|
|
1369
1449
|
|
|
1370
1450
|
All other IDs use the OpenAI API by default, including custom deployment names.
|
|
1371
1451
|
|
package/package.json
CHANGED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import {
|
|
2
|
+
lazySchema,
|
|
3
|
+
zodSchema,
|
|
4
|
+
type InferSchema,
|
|
5
|
+
} from '@ai-sdk/provider-utils';
|
|
6
|
+
import { z } from 'zod/v4';
|
|
7
|
+
|
|
8
|
+
export const azureMaiTranscriptionModelOptionsShape = () => ({
|
|
9
|
+
/**
|
|
10
|
+
* Language hint for streaming transcription, e.g. `en`. Omit for automatic
|
|
11
|
+
* language detection.
|
|
12
|
+
*/
|
|
13
|
+
language: z.string().min(1).optional(),
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
export const azureMaiTranscriptionModelOptions = lazySchema(() =>
|
|
17
|
+
zodSchema(z.strictObject(azureMaiTranscriptionModelOptionsShape())),
|
|
18
|
+
);
|
|
19
|
+
|
|
20
|
+
export type AzureTranscriptionModelMaiOptions = InferSchema<
|
|
21
|
+
typeof azureMaiTranscriptionModelOptions
|
|
22
|
+
>;
|