@ai-sdk/azure 4.0.87 → 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.
@@ -15,6 +15,7 @@ import {
15
15
  type LanguageModelV4,
16
16
  type ProviderV4,
17
17
  type ImageModelV4,
18
+ type SharedV4Warning,
18
19
  type SpeechModelV4,
19
20
  type TranscriptionModelV4,
20
21
  } from '@ai-sdk/provider';
@@ -30,12 +31,20 @@ import {
30
31
  withoutTrailingSlash,
31
32
  withUserAgentSuffix,
32
33
  type FetchFunction,
34
+ type WebSocketConstructor,
33
35
  } from '@ai-sdk/provider-utils';
36
+ import { AzureMaiTranscriptionModel } from './azure-mai-transcription-model';
34
37
  import { azureOpenaiTools } from './azure-openai-tools';
38
+ import {
39
+ azureSpeechModelOptions,
40
+ getMAIVoiceModel,
41
+ } from './azure-speech-model-options';
42
+ import { AzureSpeechSpeechModel } from './azure-speech-speech-model';
35
43
  import { AzureSpeechTranscriptionModel } from './azure-speech-transcription-model';
36
44
  import {
37
45
  azureTranscriptionModelOptions,
38
- isMAITranscribe2,
46
+ getMAITranscribeModel,
47
+ isMAITranscribeStreaming,
39
48
  } from './azure-transcription-model-options';
40
49
  import { VERSION } from './version';
41
50
 
@@ -98,8 +107,9 @@ export interface AzureOpenAIProvider extends ProviderV4 {
98
107
  imageModel(deploymentId: string): ImageModelV4;
99
108
 
100
109
  /**
101
- * Creates an Azure transcription model. MAI-Transcribe-2 uses the Speech API
102
- * by default; other IDs use OpenAI. Override with providerOptions.azure.api.
110
+ * Creates an Azure transcription model. MAI-Transcribe models use the Speech
111
+ * API and MAI-Transcribe-2-Streaming the MAI realtime API by default; other
112
+ * IDs use OpenAI. Override with providerOptions.azure.api.
103
113
  */
104
114
  transcription(deploymentId: string): TranscriptionModelV4;
105
115
 
@@ -109,10 +119,16 @@ export interface AzureOpenAIProvider extends ProviderV4 {
109
119
  transcriptionModel(deploymentId: string): TranscriptionModelV4;
110
120
 
111
121
  /**
112
- * Creates an Azure OpenAI model for speech generation.
122
+ * Creates an Azure speech generation model. MAI-Voice models use the Speech
123
+ * API by default; other IDs use OpenAI. Override with providerOptions.azure.api.
113
124
  */
114
125
  speech(deploymentId: string): SpeechModelV4;
115
126
 
127
+ /**
128
+ * Creates an Azure speech generation model. Alias of `speech`.
129
+ */
130
+ speechModel(deploymentId: string): SpeechModelV4;
131
+
116
132
  /**
117
133
  * AzureOpenAI-specific tools.
118
134
  */
@@ -175,12 +191,27 @@ export interface AzureOpenAIProviderSettings {
175
191
  useDeploymentBasedUrls?: boolean;
176
192
 
177
193
  /**
178
- * URL prefix for Azure Speech transcription (MAI-Transcribe-2), e.g. a
179
- * regional endpoint like `https://eastus.api.cognitive.microsoft.com`.
194
+ * URL prefix for Azure Speech (MAI-Transcribe transcription and MAI-Voice
195
+ * speech), e.g. a regional endpoint like
196
+ * `https://eastus.api.cognitive.microsoft.com`.
180
197
  * Defaults to `https://{resourceName}.cognitiveservices.azure.com`.
181
198
  * Speech requests do not use `baseURL` or `apiVersion`.
182
199
  */
183
200
  speechBaseURL?: string;
201
+
202
+ /**
203
+ * URL prefix for MAI realtime APIs (MAI-Transcribe-2-Streaming).
204
+ * Defaults to `https://{resourceName}.services.ai.azure.com/mai/v1`.
205
+ */
206
+ maiBaseURL?: string;
207
+
208
+ /**
209
+ * Custom WebSocket implementation for MAI streaming transcription, e.g.
210
+ * `ws` in Node.js. With a custom implementation the API key is sent as a
211
+ * header; otherwise it is sent as the `api-key` query parameter. Entra ID
212
+ * tokens require a custom implementation; streaming rejects them otherwise.
213
+ */
214
+ webSocket?: WebSocketConstructor;
184
215
  }
185
216
 
186
217
  function getAzureOpenAIBaseURLInfo(baseURL: string | undefined) {
@@ -225,7 +256,7 @@ export function createAzure(
225
256
  });
226
257
  }
227
258
 
228
- const getHeaders = (api: 'openai' | 'speech' = 'openai') => {
259
+ const getHeaders = (api: 'openai' | 'speech' | 'mai' = 'openai') => {
229
260
  const authHeaders = tokenProvider
230
261
  ? {}
231
262
  : {
@@ -233,7 +264,12 @@ export function createAzure(
233
264
  loadApiKey({
234
265
  apiKey: options.apiKey,
235
266
  environmentVariableName: 'AZURE_API_KEY',
236
- description: api === 'speech' ? 'Azure Speech' : 'Azure OpenAI',
267
+ description:
268
+ api === 'speech'
269
+ ? 'Azure Speech'
270
+ : api === 'mai'
271
+ ? 'Azure MAI'
272
+ : 'Azure OpenAI',
237
273
  }),
238
274
  };
239
275
 
@@ -378,6 +414,10 @@ export function createAzure(
378
414
  },
379
415
  });
380
416
 
417
+ const speechBaseURL = () =>
418
+ withoutTrailingSlash(options.speechBaseURL) ??
419
+ `https://${getResourceName()}.cognitiveservices.azure.com`;
420
+
381
421
  const createTranscriptionModel = (modelId: string) =>
382
422
  new AzureTranscriptionModel(
383
423
  modelId,
@@ -390,22 +430,43 @@ export function createAzure(
390
430
  }),
391
431
  new AzureSpeechTranscriptionModel(modelId, {
392
432
  url: () =>
393
- `${
394
- withoutTrailingSlash(options.speechBaseURL) ??
395
- `https://${getResourceName()}.cognitiveservices.azure.com`
396
- }/speechtotext/transcriptions:transcribe?api-version=2025-10-15`,
433
+ `${speechBaseURL()}/speechtotext/transcriptions:transcribe?api-version=2025-10-15`,
397
434
  headers: () => getHeaders('speech'),
398
435
  fetch,
399
436
  }),
437
+ new AzureMaiTranscriptionModel(modelId, {
438
+ url: () =>
439
+ `${
440
+ withoutTrailingSlash(options.maiBaseURL) ??
441
+ `https://${getResourceName()}.services.ai.azure.com/mai/v1`
442
+ }/realtime?intent=transcription`,
443
+ headers: async () =>
444
+ tokenProvider
445
+ ? {
446
+ authorization: `Bearer ${await tokenProvider()}`,
447
+ ...getHeaders('mai'),
448
+ }
449
+ : getHeaders('mai'),
450
+ webSocket: options.webSocket,
451
+ }),
400
452
  );
401
453
 
402
454
  const createSpeechModel = (modelId: string) =>
403
- new OpenAISpeechModel(modelId, {
404
- provider: 'azure.speech',
405
- url,
406
- headers: getHeaders,
407
- fetch,
408
- });
455
+ new AzureSpeechModel(
456
+ modelId,
457
+ options,
458
+ new OpenAISpeechModel(modelId, {
459
+ provider: 'azure.speech',
460
+ url,
461
+ headers: getHeaders,
462
+ fetch,
463
+ }),
464
+ new AzureSpeechSpeechModel(modelId, {
465
+ url: () => `${speechBaseURL()}/tts/cognitiveservices/v1`,
466
+ headers: () => getHeaders('speech'),
467
+ fetch,
468
+ }),
469
+ );
409
470
 
410
471
  const provider = function (deploymentId: string) {
411
472
  if (new.target) {
@@ -432,6 +493,7 @@ export function createAzure(
432
493
  provider.transcription = createTranscriptionModel;
433
494
  provider.transcriptionModel = createTranscriptionModel;
434
495
  provider.speech = createSpeechModel;
496
+ provider.speechModel = createSpeechModel;
435
497
  provider.tools = azureOpenaiTools;
436
498
  return provider;
437
499
  }
@@ -451,6 +513,7 @@ class AzureTranscriptionModel implements TranscriptionModelV4 {
451
513
  private readonly config: AzureOpenAIProviderSettings,
452
514
  private readonly openai: OpenAITranscriptionModel,
453
515
  private readonly speech: AzureSpeechTranscriptionModel,
516
+ private readonly mai: AzureMaiTranscriptionModel,
454
517
  ) {}
455
518
 
456
519
  static [WORKFLOW_SERIALIZE](model: AzureTranscriptionModel) {
@@ -468,11 +531,18 @@ class AzureTranscriptionModel implements TranscriptionModelV4 {
468
531
  }
469
532
 
470
533
  async doGenerate(options: Parameters<TranscriptionModelV4['doGenerate']>[0]) {
471
- const { api, ...speechOptions } = await this.getOptions(
534
+ const { api, speechOptions, maiOptions } = await this.getOptions(
472
535
  options.providerOptions,
473
536
  );
537
+ if (api === 'mai') {
538
+ return this.mai.doGenerate();
539
+ }
474
540
  if (api === 'speech') {
475
- return this.speech.doGenerate(options, speechOptions);
541
+ const result = await this.speech.doGenerate(options, speechOptions);
542
+ return {
543
+ ...result,
544
+ warnings: [...result.warnings, ...maiOnlyWarnings(maiOptions)],
545
+ };
476
546
  }
477
547
 
478
548
  const result = await this.openai.doGenerate(options);
@@ -480,11 +550,8 @@ class AzureTranscriptionModel implements TranscriptionModelV4 {
480
550
  ...result,
481
551
  warnings: [
482
552
  ...result.warnings,
483
- ...Object.keys(speechOptions).map(key => ({
484
- type: 'unsupported' as const,
485
- feature: `providerOptions.azure.${key}`,
486
- details: 'This option requires the Azure Speech API.',
487
- })),
553
+ ...speechOnlyWarnings(speechOptions),
554
+ ...maiOnlyWarnings(maiOptions),
488
555
  ],
489
556
  };
490
557
  }
@@ -492,12 +559,21 @@ class AzureTranscriptionModel implements TranscriptionModelV4 {
492
559
  async doStream(
493
560
  options: Parameters<NonNullable<TranscriptionModelV4['doStream']>>[0],
494
561
  ) {
495
- const { api } = await this.getOptions(options.providerOptions);
562
+ const { api, speechOptions, maiOptions } = await this.getOptions(
563
+ options.providerOptions,
564
+ );
496
565
  if (api === 'speech') {
497
566
  throw new UnsupportedFunctionalityError({
498
567
  functionality: 'streaming transcription with the Azure Speech API',
499
568
  });
500
569
  }
570
+ if (api === 'mai') {
571
+ return this.mai.doStream(
572
+ options,
573
+ maiOptions,
574
+ speechOnlyWarnings(speechOptions),
575
+ );
576
+ }
501
577
  return this.openai.doStream(options);
502
578
  }
503
579
 
@@ -506,15 +582,97 @@ class AzureTranscriptionModel implements TranscriptionModelV4 {
506
582
  TranscriptionModelV4['doGenerate']
507
583
  >[0]['providerOptions'],
508
584
  ) {
509
- const options = await parseProviderOptions({
510
- provider: 'azure',
511
- providerOptions,
512
- schema: azureTranscriptionModelOptions,
513
- });
585
+ const { api, language, ...speechOptions } =
586
+ (await parseProviderOptions({
587
+ provider: 'azure',
588
+ providerOptions,
589
+ schema: azureTranscriptionModelOptions,
590
+ })) ?? {};
514
591
  return {
515
- ...options,
516
592
  api:
517
- options?.api ?? (isMAITranscribe2(this.modelId) ? 'speech' : 'openai'),
593
+ api ??
594
+ (isMAITranscribeStreaming(this.modelId)
595
+ ? ('mai' as const)
596
+ : getMAITranscribeModel(this.modelId)
597
+ ? ('speech' as const)
598
+ : ('openai' as const)),
599
+ speechOptions,
600
+ maiOptions: language != null ? { language } : {},
601
+ };
602
+ }
603
+ }
604
+
605
+ // Resolves the API per request: providerOptions also reach this model via Gateway.
606
+ class AzureSpeechModel implements SpeechModelV4 {
607
+ readonly specificationVersion = 'v4';
608
+ readonly provider = 'azure.speech';
609
+
610
+ constructor(
611
+ readonly modelId: string,
612
+ private readonly config: AzureOpenAIProviderSettings,
613
+ private readonly openai: OpenAISpeechModel,
614
+ private readonly speech: AzureSpeechSpeechModel,
615
+ ) {}
616
+
617
+ static [WORKFLOW_SERIALIZE](model: AzureSpeechModel) {
618
+ return serializeModelOptions({
619
+ modelId: model.modelId,
620
+ config: model.config,
621
+ });
622
+ }
623
+
624
+ static [WORKFLOW_DESERIALIZE](options: {
625
+ modelId: string;
626
+ config: AzureOpenAIProviderSettings;
627
+ }) {
628
+ return createAzure(options.config).speech(options.modelId);
629
+ }
630
+
631
+ async doGenerate(options: Parameters<SpeechModelV4['doGenerate']>[0]) {
632
+ const { api, ...speechOptions } =
633
+ (await parseProviderOptions({
634
+ provider: 'azure',
635
+ providerOptions: options.providerOptions,
636
+ schema: azureSpeechModelOptions,
637
+ })) ?? {};
638
+ if (
639
+ (api ?? (getMAIVoiceModel(this.modelId) ? 'speech' : 'openai')) ===
640
+ 'speech'
641
+ ) {
642
+ return this.speech.doGenerate(options, speechOptions);
643
+ }
644
+
645
+ const result = await this.openai.doGenerate(options);
646
+ return {
647
+ ...result,
648
+ warnings: [...result.warnings, ...speechOnlyWarnings(speechOptions)],
518
649
  };
519
650
  }
520
651
  }
652
+
653
+ function speechOnlyWarnings(options: Record<string, unknown>) {
654
+ return unsupportedOptionWarnings(
655
+ options,
656
+ 'This option requires the Azure Speech API.',
657
+ );
658
+ }
659
+
660
+ function maiOnlyWarnings(options: Record<string, unknown>) {
661
+ return unsupportedOptionWarnings(
662
+ options,
663
+ 'This option requires MAI streaming transcription.',
664
+ );
665
+ }
666
+
667
+ function unsupportedOptionWarnings(
668
+ options: Record<string, unknown>,
669
+ details: string,
670
+ ): SharedV4Warning[] {
671
+ return Object.entries(options)
672
+ .filter(([, value]) => value !== undefined)
673
+ .map(([key]) => ({
674
+ type: 'unsupported',
675
+ feature: `providerOptions.azure.${key}`,
676
+ details,
677
+ }));
678
+ }
@@ -0,0 +1,35 @@
1
+ import {
2
+ lazySchema,
3
+ zodSchema,
4
+ type InferSchema,
5
+ } from '@ai-sdk/provider-utils';
6
+ import { z } from 'zod/v4';
7
+ import { azureSpeechSpeechModelOptionsShape } from './azure-speech-speech-model-options';
8
+
9
+ export const azureSpeechModelOptions = lazySchema(() =>
10
+ zodSchema(
11
+ z.strictObject({
12
+ /**
13
+ * API to use. Defaults to Speech for MAI-Voice models, OpenAI otherwise.
14
+ */
15
+ api: z.enum(['openai', 'speech']).optional(),
16
+ ...azureSpeechSpeechModelOptionsShape(),
17
+ }),
18
+ ),
19
+ );
20
+
21
+ export type AzureSpeechModelOptions = InferSchema<
22
+ typeof azureSpeechModelOptions
23
+ >;
24
+
25
+ // Azure voice-name suffixes by lowercase model ID.
26
+ const maiVoiceModels = new Map([
27
+ ['mai-voice-2.1-flash', 'MAI-Voice-2.1-Flash'],
28
+ ['mai-voice-2.1', 'MAI-Voice-2.1'],
29
+ ['mai-voice-2-flash', 'MAI-Voice-2-Flash'],
30
+ ['mai-voice-2', 'MAI-Voice-2'],
31
+ ]);
32
+
33
+ export function getMAIVoiceModel(modelId: string) {
34
+ return maiVoiceModels.get(modelId.toLowerCase());
35
+ }
@@ -0,0 +1,27 @@
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 azureSpeechSpeechModelOptionsShape = () => ({
9
+ /**
10
+ * Speaking style applied with `mstts:express-as`, e.g. `excited` or
11
+ * `whispering`. Supported styles vary by voice.
12
+ */
13
+ style: z.string().min(1).optional(),
14
+
15
+ /**
16
+ * Intensity of `style`, from 0.01 to 2. Azure defaults to 1.
17
+ */
18
+ styleDegree: z.number().min(0.01).max(2).optional(),
19
+ });
20
+
21
+ export const azureSpeechSpeechModelOptions = lazySchema(() =>
22
+ zodSchema(z.strictObject(azureSpeechSpeechModelOptionsShape())),
23
+ );
24
+
25
+ export type AzureSpeechModelSpeechOptions = InferSchema<
26
+ typeof azureSpeechSpeechModelOptions
27
+ >;
@@ -0,0 +1,289 @@
1
+ import {
2
+ APICallError,
3
+ type SharedV4Warning,
4
+ type SpeechModelV4,
5
+ } from '@ai-sdk/provider';
6
+ import {
7
+ combineHeaders,
8
+ createBinaryResponseHandler,
9
+ extractResponseHeaders,
10
+ postToApi,
11
+ safeParseJSON,
12
+ type FetchFunction,
13
+ type ResponseHandler,
14
+ } from '@ai-sdk/provider-utils';
15
+ import { z } from 'zod/v4';
16
+ import { getMAIVoiceModel } from './azure-speech-model-options';
17
+ import type { AzureSpeechModelSpeechOptions } from './azure-speech-speech-model-options';
18
+
19
+ const DEFAULT_VOICE = 'en-US-Harper';
20
+
21
+ // Default voice per ISO 639-1 language; available on MAI-Voice-2,
22
+ // MAI-Voice-2.1, and their Flash variants.
23
+ const DEFAULT_VOICES = new Map([
24
+ ['de', 'de-DE-Mia'],
25
+ ['en', DEFAULT_VOICE],
26
+ ['es', 'es-MX-Valeria'],
27
+ ['fr', 'fr-FR-Soleil'],
28
+ ['hi', 'hi-IN-Kavya'],
29
+ ['hu', 'hu-HU-Lilla'],
30
+ ['it', 'it-IT-Rosa'],
31
+ ['ko', 'ko-KR-Haena'],
32
+ ['nl', 'nl-NL-Fleur'],
33
+ ['pt', 'pt-BR-Luana'],
34
+ ['ro', 'ro-RO-Elena'],
35
+ ['ru', 'ru-RU-Masha'],
36
+ ['th', 'th-TH-Krit'],
37
+ ['tr', 'tr-TR-Elif'],
38
+ ['zh', 'zh-CN-Mei'],
39
+ ]);
40
+ const DEFAULT_OUTPUT_FORMAT = 'audio-24khz-160kbitrate-mono-mp3';
41
+
42
+ // Shorthand formats for `outputFormat`; other X-Microsoft-OutputFormat values
43
+ // (e.g. `audio-48khz-192kbitrate-mono-mp3`) are passed through unchanged.
44
+ const OUTPUT_FORMATS = new Map([
45
+ ['mp3', DEFAULT_OUTPUT_FORMAT],
46
+ ['opus', 'ogg-24khz-16bit-mono-opus'],
47
+ ['pcm', 'raw-24khz-16bit-mono-pcm'],
48
+ ['wav', 'riff-24khz-16bit-mono-pcm'],
49
+ ]);
50
+ const NATIVE_OUTPUT_FORMAT =
51
+ /^(?:amr|audio|g722|ogg|raw|riff|webm)-[a-z0-9-]+$/;
52
+
53
+ /**
54
+ * Azure Speech text to speech with SSML. The model is appended to the voice
55
+ * name, e.g. `en-US-Harper:MAI-Voice-2`.
56
+ */
57
+ export class AzureSpeechSpeechModel implements SpeechModelV4 {
58
+ readonly specificationVersion = 'v4';
59
+ readonly provider = 'azure.speech';
60
+
61
+ constructor(
62
+ readonly modelId: string,
63
+ private readonly config: {
64
+ url: () => string;
65
+ headers: () => Record<string, string | undefined>;
66
+ fetch?: FetchFunction;
67
+ _internal?: { currentDate?: () => Date };
68
+ },
69
+ ) {}
70
+
71
+ async doGenerate(
72
+ options: Parameters<SpeechModelV4['doGenerate']>[0],
73
+ azureOptions: AzureSpeechModelSpeechOptions = {},
74
+ ): Promise<Awaited<ReturnType<SpeechModelV4['doGenerate']>>> {
75
+ const currentDate = this.config._internal?.currentDate?.() ?? new Date();
76
+ const warnings: SharedV4Warning[] = [];
77
+ const { style, styleDegree } = azureOptions;
78
+
79
+ if (options.instructions != null) {
80
+ warnings.push({
81
+ type: 'unsupported',
82
+ feature: 'instructions',
83
+ details: 'Use providerOptions.azure.style to control speaking style.',
84
+ });
85
+ }
86
+ const { voice, languageWarning } = resolveVoice(
87
+ options.voice,
88
+ options.language,
89
+ );
90
+ if (languageWarning != null) {
91
+ warnings.push({
92
+ type: 'unsupported',
93
+ feature: 'language',
94
+ details: languageWarning,
95
+ });
96
+ }
97
+ if (styleDegree != null && style == null) {
98
+ warnings.push({
99
+ type: 'unsupported',
100
+ feature: 'providerOptions.azure.styleDegree',
101
+ details: 'styleDegree requires style.',
102
+ });
103
+ }
104
+
105
+ let outputFormat = DEFAULT_OUTPUT_FORMAT;
106
+ if (options.outputFormat != null) {
107
+ const format = options.outputFormat.toLowerCase();
108
+ const shorthand = OUTPUT_FORMATS.get(format);
109
+ if (shorthand != null) {
110
+ outputFormat = shorthand;
111
+ } else if (NATIVE_OUTPUT_FORMAT.test(format)) {
112
+ outputFormat = format;
113
+ } else {
114
+ warnings.push({
115
+ type: 'unsupported',
116
+ feature: 'outputFormat',
117
+ details: `Unsupported output format: ${options.outputFormat}. Using mp3 instead.`,
118
+ });
119
+ }
120
+ }
121
+
122
+ const ssml = buildSsml({
123
+ text: options.text,
124
+ voiceName: voice.includes(':')
125
+ ? voice
126
+ : `${voice}:${getMAIVoiceModel(this.modelId) ?? this.modelId}`,
127
+ locale: /^([a-z]{2,3}-[a-z]{2,4})-/i.exec(voice)?.[1],
128
+ speed: options.speed,
129
+ style,
130
+ styleDegree: style != null ? styleDegree : undefined,
131
+ });
132
+
133
+ const {
134
+ value: audio,
135
+ responseHeaders,
136
+ rawValue,
137
+ } = await postToApi({
138
+ url: this.config.url(),
139
+ headers: combineHeaders(
140
+ this.config.headers(),
141
+ {
142
+ 'Content-Type': 'application/ssml+xml',
143
+ 'X-Microsoft-OutputFormat': outputFormat,
144
+ },
145
+ options.headers,
146
+ ),
147
+ body: { content: ssml, values: ssml },
148
+ failedResponseHandler,
149
+ successfulResponseHandler: createBinaryResponseHandler(),
150
+ abortSignal: options.abortSignal,
151
+ fetch: this.config.fetch,
152
+ });
153
+
154
+ return {
155
+ audio,
156
+ warnings,
157
+ request: { body: ssml },
158
+ response: {
159
+ timestamp: currentDate,
160
+ modelId: this.modelId,
161
+ headers: responseHeaders,
162
+ body: rawValue,
163
+ },
164
+ };
165
+ }
166
+ }
167
+
168
+ function buildSsml({
169
+ text,
170
+ voiceName,
171
+ locale = 'en-US',
172
+ speed,
173
+ style,
174
+ styleDegree,
175
+ }: {
176
+ text: string;
177
+ voiceName: string;
178
+ locale?: string;
179
+ speed?: number;
180
+ style?: string;
181
+ styleDegree?: number;
182
+ }) {
183
+ let content = escapeXml(text);
184
+ if (speed != null) {
185
+ content = `<prosody rate="${speed}">${content}</prosody>`;
186
+ }
187
+ if (style != null) {
188
+ const degree = styleDegree != null ? ` styledegree="${styleDegree}"` : '';
189
+ content = `<mstts:express-as style="${escapeXml(style)}"${degree}>${content}</mstts:express-as>`;
190
+ }
191
+ return (
192
+ `<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" ` +
193
+ `xmlns:mstts="http://www.w3.org/2001/mstts" xml:lang="${escapeXml(locale)}">` +
194
+ `<voice name="${escapeXml(voiceName)}">${content}</voice></speak>`
195
+ );
196
+ }
197
+
198
+ const XML_ESCAPES: Record<string, string> = {
199
+ '&': '&amp;',
200
+ '<': '&lt;',
201
+ '>': '&gt;',
202
+ '"': '&quot;',
203
+ "'": '&apos;',
204
+ };
205
+
206
+ function escapeXml(value: string) {
207
+ return value.replace(/[&<>"']/g, char => XML_ESCAPES[char]);
208
+ }
209
+
210
+ // Uses the language's default voice when no voice is set. An explicit voice
211
+ // wins, and its locale selects the language.
212
+ function resolveVoice(
213
+ voice: string | undefined,
214
+ language: string | undefined,
215
+ ): { voice: string; languageWarning?: string } {
216
+ const code = language ? language.split('-')[0].toLowerCase() : undefined;
217
+ if (voice == null) {
218
+ if (code == null) return { voice: DEFAULT_VOICE };
219
+ if (code === 'auto') {
220
+ return {
221
+ voice: DEFAULT_VOICE,
222
+ languageWarning: `Automatic language detection is not supported. ${DEFAULT_VOICE} was used.`,
223
+ };
224
+ }
225
+ const defaultVoice = DEFAULT_VOICES.get(code);
226
+ return defaultVoice != null
227
+ ? { voice: defaultVoice }
228
+ : {
229
+ voice: DEFAULT_VOICE,
230
+ languageWarning: `No default MAI voice for language "${language}". ${DEFAULT_VOICE} was used.`,
231
+ };
232
+ }
233
+ const voiceLanguage = /^([a-z]{2,3})-[a-z]{2,4}-/i
234
+ .exec(voice)?.[1]
235
+ ?.toLowerCase();
236
+ return code != null &&
237
+ code !== 'auto' &&
238
+ voiceLanguage != null &&
239
+ code !== voiceLanguage
240
+ ? {
241
+ voice,
242
+ languageWarning: `The voice ${voice} selects the language. Language "${language}" was ignored.`,
243
+ }
244
+ : { voice };
245
+ }
246
+
247
+ const errorSchema = z.object({
248
+ error: z.object({ message: z.string() }),
249
+ });
250
+
251
+ // Azure Speech answers invalid requests (style or output format) with an empty
252
+ // 400 body. Unknown voices or styles reset the connection with an Envoy 502
253
+ // whose reason is `protocol error`; other 502s stay retryable.
254
+ const failedResponseHandler: ResponseHandler<APICallError> = async ({
255
+ response,
256
+ url,
257
+ requestBodyValues,
258
+ }) => {
259
+ const responseHeaders = extractResponseHeaders(response);
260
+ const responseBody = await response.text();
261
+ const parsed = await safeParseJSON({
262
+ text: responseBody,
263
+ schema: errorSchema,
264
+ });
265
+ const isVoiceReset =
266
+ response.status === 502 &&
267
+ responseBody.includes('reset reason: protocol error');
268
+
269
+ const message = parsed.success
270
+ ? parsed.value.error.message
271
+ : isVoiceReset
272
+ ? '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.'
273
+ : response.status === 400
274
+ ? 'Azure Speech request failed with status 400. Check the voice name, style, and output format.'
275
+ : `Azure Speech request failed with status ${response.status}.`;
276
+
277
+ return {
278
+ responseHeaders,
279
+ value: new APICallError({
280
+ message,
281
+ url,
282
+ requestBodyValues,
283
+ statusCode: response.status,
284
+ responseHeaders,
285
+ responseBody,
286
+ isRetryable: isVoiceReset ? false : undefined,
287
+ }),
288
+ };
289
+ };