@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.
- package/CHANGELOG.md +19 -0
- package/dist/index.d.ts +36 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +551 -26
- package/dist/index.js.map +1 -1
- package/docs/04-azure.mdx +190 -25
- 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 +191 -33
- package/src/azure-speech-model-options.ts +35 -0
- package/src/azure-speech-speech-model-options.ts +27 -0
- package/src/azure-speech-speech-model.ts +289 -0
- package/src/azure-speech-transcription-model.ts +6 -5
- package/src/azure-transcription-model-options.ts +21 -4
- package/src/index.ts +1 -0
package/dist/index.js
CHANGED
|
@@ -1,8 +1,238 @@
|
|
|
1
1
|
import { OpenAIChatLanguageModel, OpenAICompletionLanguageModel, OpenAIEmbeddingModel, OpenAIImageModel, OpenAIResponsesLanguageModel, OpenAISpeechModel, OpenAITranscriptionModel, codeInterpreter, fileSearch, imageGeneration, webSearch, webSearchPreview } from "@ai-sdk/openai/internal";
|
|
2
2
|
import { DeepSeekChatLanguageModel } from "@ai-sdk/deepseek/internal";
|
|
3
|
-
import { InvalidArgumentError, UnsupportedFunctionalityError } from "@ai-sdk/provider";
|
|
4
|
-
import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE, combineHeaders, convertBase64ToUint8Array, createJsonErrorResponseHandler, createJsonResponseHandler, isValidHostnamePart, lazySchema, loadApiKey, loadSetting, mediaTypeToExtension, normalizeHeaders, parseProviderOptions, postFormDataToApi, serializeModelOptions, withUserAgentSuffix, withoutTrailingSlash, zodSchema } from "@ai-sdk/provider-utils";
|
|
3
|
+
import { APICallError, InvalidArgumentError, UnsupportedFunctionalityError } from "@ai-sdk/provider";
|
|
4
|
+
import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE, combineHeaders, connectToWebSocket, convertBase64ToUint8Array, convertToBase64, createBinaryResponseHandler, createJsonErrorResponseHandler, createJsonResponseHandler, extractResponseHeaders, isValidHostnamePart, lazySchema, loadApiKey, loadSetting, mediaTypeToExtension, normalizeHeaders, parseProviderOptions, postFormDataToApi, postToApi, safeParseJSON, serializeModelOptions, toWebSocketUrl, waitForWebSocketBufferDrain, withUserAgentSuffix, withoutTrailingSlash, zodSchema } from "@ai-sdk/provider-utils";
|
|
5
5
|
import { z } from "zod/v4";
|
|
6
|
+
//#region src/azure-mai-transcription-model.ts
|
|
7
|
+
const SUPPORTED_SAMPLE_RATES = [16e3, 24e3];
|
|
8
|
+
const DEFAULT_SAMPLE_RATE = 24e3;
|
|
9
|
+
/**
|
|
10
|
+
* MAI streaming transcription over the OpenAI Realtime-compatible
|
|
11
|
+
* `/mai/v1/realtime` WebSocket. The model ID is the Foundry deployment name.
|
|
12
|
+
*/
|
|
13
|
+
var AzureMaiTranscriptionModel = class {
|
|
14
|
+
constructor(modelId, config) {
|
|
15
|
+
this.modelId = modelId;
|
|
16
|
+
this.config = config;
|
|
17
|
+
this.specificationVersion = "v4";
|
|
18
|
+
this.provider = "azure.transcription";
|
|
19
|
+
}
|
|
20
|
+
async doGenerate() {
|
|
21
|
+
throw new UnsupportedFunctionalityError({ functionality: `file transcription with ${this.modelId} (use streaming transcription)` });
|
|
22
|
+
}
|
|
23
|
+
async doStream(options, maiOptions = {}, warnings = []) {
|
|
24
|
+
const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
|
|
25
|
+
const { type, rate = DEFAULT_SAMPLE_RATE } = options.inputAudioFormat;
|
|
26
|
+
if (type !== "audio/pcm" || !SUPPORTED_SAMPLE_RATES.includes(rate)) throw new InvalidArgumentError({
|
|
27
|
+
argument: "inputAudioFormat",
|
|
28
|
+
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` : ""}.`
|
|
29
|
+
});
|
|
30
|
+
const sessionUpdate = {
|
|
31
|
+
type: "session.update",
|
|
32
|
+
session: {
|
|
33
|
+
type: "transcription",
|
|
34
|
+
audio: { input: {
|
|
35
|
+
format: {
|
|
36
|
+
type: "audio/pcm",
|
|
37
|
+
rate
|
|
38
|
+
},
|
|
39
|
+
transcription: {
|
|
40
|
+
model: this.modelId,
|
|
41
|
+
...maiOptions.language != null ? { language: maiOptions.language } : {}
|
|
42
|
+
},
|
|
43
|
+
turn_detection: null,
|
|
44
|
+
noise_reduction: null
|
|
45
|
+
} }
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
const headers = {
|
|
49
|
+
...await this.config.headers(),
|
|
50
|
+
...options.headers
|
|
51
|
+
};
|
|
52
|
+
if (this.config.webSocket == null && Object.entries(headers).some(([key, value]) => key.toLowerCase() === "authorization" && value != null)) throw new InvalidArgumentError({
|
|
53
|
+
argument: "webSocket",
|
|
54
|
+
message: "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."
|
|
55
|
+
});
|
|
56
|
+
return {
|
|
57
|
+
request: { body: sessionUpdate },
|
|
58
|
+
response: {
|
|
59
|
+
timestamp: currentDate,
|
|
60
|
+
modelId: this.modelId
|
|
61
|
+
},
|
|
62
|
+
stream: createMaiTranscriptionStream({
|
|
63
|
+
...getConnection({
|
|
64
|
+
url: toWebSocketUrl(this.config.url()),
|
|
65
|
+
headers,
|
|
66
|
+
supportsHeaders: this.config.webSocket != null
|
|
67
|
+
}),
|
|
68
|
+
webSocket: this.config.webSocket,
|
|
69
|
+
sessionUpdate,
|
|
70
|
+
bytesPerSecond: rate * 2,
|
|
71
|
+
language: maiOptions.language,
|
|
72
|
+
warnings,
|
|
73
|
+
audio: options.audio,
|
|
74
|
+
abortSignal: options.abortSignal,
|
|
75
|
+
includeRawChunks: options.includeRawChunks
|
|
76
|
+
})
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
function getConnection({ url, headers, supportsHeaders }) {
|
|
81
|
+
if (supportsHeaders) return {
|
|
82
|
+
url,
|
|
83
|
+
headers
|
|
84
|
+
};
|
|
85
|
+
const remaining = {};
|
|
86
|
+
for (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === "api-key") {
|
|
87
|
+
if (value != null) url.searchParams.set("api-key", value);
|
|
88
|
+
} else remaining[key] = value;
|
|
89
|
+
return {
|
|
90
|
+
url,
|
|
91
|
+
headers: remaining
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function createMaiTranscriptionStream({ url, headers, webSocket, sessionUpdate, bytesPerSecond, language, warnings, audio, abortSignal, includeRawChunks }) {
|
|
95
|
+
let finished = false;
|
|
96
|
+
let cleanup = () => {};
|
|
97
|
+
return new ReadableStream({
|
|
98
|
+
start: (controller) => {
|
|
99
|
+
let audioReader;
|
|
100
|
+
let connection;
|
|
101
|
+
let audioStarted = false;
|
|
102
|
+
let committed = false;
|
|
103
|
+
let audioBytes = 0;
|
|
104
|
+
let deltas = "";
|
|
105
|
+
cleanup = (closeCode) => {
|
|
106
|
+
if (audioReader != null) audioReader.cancel().catch(() => {});
|
|
107
|
+
else audio.cancel().catch(() => {});
|
|
108
|
+
connection?.close(closeCode);
|
|
109
|
+
};
|
|
110
|
+
const finishWithError = (error) => {
|
|
111
|
+
if (finished) return;
|
|
112
|
+
finished = true;
|
|
113
|
+
cleanup();
|
|
114
|
+
controller.error(error);
|
|
115
|
+
};
|
|
116
|
+
const finish = (text) => {
|
|
117
|
+
if (finished) return;
|
|
118
|
+
finished = true;
|
|
119
|
+
controller.enqueue({
|
|
120
|
+
type: "finish",
|
|
121
|
+
text,
|
|
122
|
+
segments: [],
|
|
123
|
+
language,
|
|
124
|
+
...audioBytes > 0 ? { durationInSeconds: audioBytes / bytesPerSecond } : {}
|
|
125
|
+
});
|
|
126
|
+
controller.close();
|
|
127
|
+
cleanup(1e3);
|
|
128
|
+
};
|
|
129
|
+
const sendAudio = async (socket) => {
|
|
130
|
+
audioReader = audio.getReader();
|
|
131
|
+
try {
|
|
132
|
+
while (true) {
|
|
133
|
+
const { done, value } = await audioReader.read();
|
|
134
|
+
if (done || finished) break;
|
|
135
|
+
const base64 = convertToBase64(value);
|
|
136
|
+
if (base64.length === 0) continue;
|
|
137
|
+
audioBytes += typeof value === "string" ? base64ByteLength(base64) : value.byteLength;
|
|
138
|
+
socket.send(JSON.stringify({
|
|
139
|
+
type: "input_audio_buffer.append",
|
|
140
|
+
audio: base64
|
|
141
|
+
}));
|
|
142
|
+
await waitForWebSocketBufferDrain(socket);
|
|
143
|
+
}
|
|
144
|
+
} finally {
|
|
145
|
+
audioReader.releaseLock();
|
|
146
|
+
audioReader = void 0;
|
|
147
|
+
}
|
|
148
|
+
if (finished) return;
|
|
149
|
+
if (audioBytes === 0) {
|
|
150
|
+
finish("");
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
committed = true;
|
|
154
|
+
socket.send(JSON.stringify({ type: "input_audio_buffer.commit" }));
|
|
155
|
+
};
|
|
156
|
+
connection = connectToWebSocket({
|
|
157
|
+
url,
|
|
158
|
+
headers,
|
|
159
|
+
webSocket,
|
|
160
|
+
abortSignal,
|
|
161
|
+
onAbort: finishWithError,
|
|
162
|
+
onProcessingError: finishWithError,
|
|
163
|
+
onOpen: () => {
|
|
164
|
+
controller.enqueue({
|
|
165
|
+
type: "stream-start",
|
|
166
|
+
warnings
|
|
167
|
+
});
|
|
168
|
+
},
|
|
169
|
+
onMessageText: async (text) => {
|
|
170
|
+
const parsed = await safeParseJSON({ text });
|
|
171
|
+
if (!parsed.success) return;
|
|
172
|
+
const event = parsed.value;
|
|
173
|
+
const socket = connection?.socket;
|
|
174
|
+
if (includeRawChunks) controller.enqueue({
|
|
175
|
+
type: "raw",
|
|
176
|
+
rawValue: event
|
|
177
|
+
});
|
|
178
|
+
switch (event.type) {
|
|
179
|
+
case "session.created":
|
|
180
|
+
socket?.send(JSON.stringify(sessionUpdate));
|
|
181
|
+
break;
|
|
182
|
+
case "session.updated":
|
|
183
|
+
if (audioStarted || socket == null) break;
|
|
184
|
+
audioStarted = true;
|
|
185
|
+
sendAudio(socket).catch(finishWithError);
|
|
186
|
+
break;
|
|
187
|
+
case "conversation.item.input_audio_transcription.delta":
|
|
188
|
+
deltas += event.delta ?? "";
|
|
189
|
+
controller.enqueue({
|
|
190
|
+
type: "transcript-delta",
|
|
191
|
+
id: event.item_id,
|
|
192
|
+
delta: event.delta ?? ""
|
|
193
|
+
});
|
|
194
|
+
break;
|
|
195
|
+
case "conversation.item.input_audio_transcription.intermediate":
|
|
196
|
+
controller.enqueue({
|
|
197
|
+
type: "transcript-partial",
|
|
198
|
+
id: event.item_id,
|
|
199
|
+
text: event.intermediate ?? ""
|
|
200
|
+
});
|
|
201
|
+
break;
|
|
202
|
+
case "conversation.item.input_audio_transcription.completed": {
|
|
203
|
+
const transcript = event.transcript ?? deltas;
|
|
204
|
+
controller.enqueue({
|
|
205
|
+
type: "transcript-final",
|
|
206
|
+
id: event.item_id,
|
|
207
|
+
text: transcript
|
|
208
|
+
});
|
|
209
|
+
if (committed) finish(transcript);
|
|
210
|
+
break;
|
|
211
|
+
}
|
|
212
|
+
case "conversation.item.input_audio_transcription.failed":
|
|
213
|
+
case "error": finishWithError(/* @__PURE__ */ new Error(`Azure MAI transcription error${event.error?.code != null ? ` (${event.error.code})` : ""}: ${event.error?.message ?? "unknown error"}`));
|
|
214
|
+
}
|
|
215
|
+
},
|
|
216
|
+
onSocketError: () => {
|
|
217
|
+
finishWithError(/* @__PURE__ */ new Error("Azure MAI transcription WebSocket error"));
|
|
218
|
+
},
|
|
219
|
+
onClose: ({ code, reason }) => {
|
|
220
|
+
finishWithError(/* @__PURE__ */ new Error(`Azure MAI transcription connection closed before the transcript completed${code != null ? ` (code ${code}${reason ? `: ${reason}` : ""})` : ""}`));
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
},
|
|
224
|
+
cancel: () => {
|
|
225
|
+
if (finished) return;
|
|
226
|
+
finished = true;
|
|
227
|
+
cleanup();
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
function base64ByteLength(base64) {
|
|
232
|
+
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
|
|
233
|
+
return base64.length * 3 / 4 - padding;
|
|
234
|
+
}
|
|
235
|
+
//#endregion
|
|
6
236
|
//#region src/azure-openai-tools.ts
|
|
7
237
|
const azureOpenaiTools = {
|
|
8
238
|
codeInterpreter,
|
|
@@ -12,6 +242,216 @@ const azureOpenaiTools = {
|
|
|
12
242
|
webSearchPreview
|
|
13
243
|
};
|
|
14
244
|
//#endregion
|
|
245
|
+
//#region src/azure-speech-speech-model-options.ts
|
|
246
|
+
const azureSpeechSpeechModelOptionsShape = () => ({
|
|
247
|
+
/**
|
|
248
|
+
* Speaking style applied with `mstts:express-as`, e.g. `excited` or
|
|
249
|
+
* `whispering`. Supported styles vary by voice.
|
|
250
|
+
*/
|
|
251
|
+
style: z.string().min(1).optional(),
|
|
252
|
+
/**
|
|
253
|
+
* Intensity of `style`, from 0.01 to 2. Azure defaults to 1.
|
|
254
|
+
*/
|
|
255
|
+
styleDegree: z.number().min(.01).max(2).optional()
|
|
256
|
+
});
|
|
257
|
+
lazySchema(() => zodSchema(z.strictObject(azureSpeechSpeechModelOptionsShape())));
|
|
258
|
+
//#endregion
|
|
259
|
+
//#region src/azure-speech-model-options.ts
|
|
260
|
+
const azureSpeechModelOptions = lazySchema(() => zodSchema(z.strictObject({
|
|
261
|
+
/**
|
|
262
|
+
* API to use. Defaults to Speech for MAI-Voice models, OpenAI otherwise.
|
|
263
|
+
*/
|
|
264
|
+
api: z.enum(["openai", "speech"]).optional(),
|
|
265
|
+
...azureSpeechSpeechModelOptionsShape()
|
|
266
|
+
})));
|
|
267
|
+
const maiVoiceModels = /* @__PURE__ */ new Map([
|
|
268
|
+
["mai-voice-2.1-flash", "MAI-Voice-2.1-Flash"],
|
|
269
|
+
["mai-voice-2.1", "MAI-Voice-2.1"],
|
|
270
|
+
["mai-voice-2-flash", "MAI-Voice-2-Flash"],
|
|
271
|
+
["mai-voice-2", "MAI-Voice-2"]
|
|
272
|
+
]);
|
|
273
|
+
function getMAIVoiceModel(modelId) {
|
|
274
|
+
return maiVoiceModels.get(modelId.toLowerCase());
|
|
275
|
+
}
|
|
276
|
+
//#endregion
|
|
277
|
+
//#region src/azure-speech-speech-model.ts
|
|
278
|
+
const DEFAULT_VOICE = "en-US-Harper";
|
|
279
|
+
const DEFAULT_VOICES = /* @__PURE__ */ new Map([
|
|
280
|
+
["de", "de-DE-Mia"],
|
|
281
|
+
["en", DEFAULT_VOICE],
|
|
282
|
+
["es", "es-MX-Valeria"],
|
|
283
|
+
["fr", "fr-FR-Soleil"],
|
|
284
|
+
["hi", "hi-IN-Kavya"],
|
|
285
|
+
["hu", "hu-HU-Lilla"],
|
|
286
|
+
["it", "it-IT-Rosa"],
|
|
287
|
+
["ko", "ko-KR-Haena"],
|
|
288
|
+
["nl", "nl-NL-Fleur"],
|
|
289
|
+
["pt", "pt-BR-Luana"],
|
|
290
|
+
["ro", "ro-RO-Elena"],
|
|
291
|
+
["ru", "ru-RU-Masha"],
|
|
292
|
+
["th", "th-TH-Krit"],
|
|
293
|
+
["tr", "tr-TR-Elif"],
|
|
294
|
+
["zh", "zh-CN-Mei"]
|
|
295
|
+
]);
|
|
296
|
+
const DEFAULT_OUTPUT_FORMAT = "audio-24khz-160kbitrate-mono-mp3";
|
|
297
|
+
const OUTPUT_FORMATS = /* @__PURE__ */ new Map([
|
|
298
|
+
["mp3", DEFAULT_OUTPUT_FORMAT],
|
|
299
|
+
["opus", "ogg-24khz-16bit-mono-opus"],
|
|
300
|
+
["pcm", "raw-24khz-16bit-mono-pcm"],
|
|
301
|
+
["wav", "riff-24khz-16bit-mono-pcm"]
|
|
302
|
+
]);
|
|
303
|
+
const NATIVE_OUTPUT_FORMAT = /^(?:amr|audio|g722|ogg|raw|riff|webm)-[a-z0-9-]+$/;
|
|
304
|
+
/**
|
|
305
|
+
* Azure Speech text to speech with SSML. The model is appended to the voice
|
|
306
|
+
* name, e.g. `en-US-Harper:MAI-Voice-2`.
|
|
307
|
+
*/
|
|
308
|
+
var AzureSpeechSpeechModel = class {
|
|
309
|
+
constructor(modelId, config) {
|
|
310
|
+
this.modelId = modelId;
|
|
311
|
+
this.config = config;
|
|
312
|
+
this.specificationVersion = "v4";
|
|
313
|
+
this.provider = "azure.speech";
|
|
314
|
+
}
|
|
315
|
+
async doGenerate(options, azureOptions = {}) {
|
|
316
|
+
const currentDate = this.config._internal?.currentDate?.() ?? /* @__PURE__ */ new Date();
|
|
317
|
+
const warnings = [];
|
|
318
|
+
const { style, styleDegree } = azureOptions;
|
|
319
|
+
if (options.instructions != null) warnings.push({
|
|
320
|
+
type: "unsupported",
|
|
321
|
+
feature: "instructions",
|
|
322
|
+
details: "Use providerOptions.azure.style to control speaking style."
|
|
323
|
+
});
|
|
324
|
+
const { voice, languageWarning } = resolveVoice(options.voice, options.language);
|
|
325
|
+
if (languageWarning != null) warnings.push({
|
|
326
|
+
type: "unsupported",
|
|
327
|
+
feature: "language",
|
|
328
|
+
details: languageWarning
|
|
329
|
+
});
|
|
330
|
+
if (styleDegree != null && style == null) warnings.push({
|
|
331
|
+
type: "unsupported",
|
|
332
|
+
feature: "providerOptions.azure.styleDegree",
|
|
333
|
+
details: "styleDegree requires style."
|
|
334
|
+
});
|
|
335
|
+
let outputFormat = DEFAULT_OUTPUT_FORMAT;
|
|
336
|
+
if (options.outputFormat != null) {
|
|
337
|
+
const format = options.outputFormat.toLowerCase();
|
|
338
|
+
const shorthand = OUTPUT_FORMATS.get(format);
|
|
339
|
+
if (shorthand != null) outputFormat = shorthand;
|
|
340
|
+
else if (NATIVE_OUTPUT_FORMAT.test(format)) outputFormat = format;
|
|
341
|
+
else warnings.push({
|
|
342
|
+
type: "unsupported",
|
|
343
|
+
feature: "outputFormat",
|
|
344
|
+
details: `Unsupported output format: ${options.outputFormat}. Using mp3 instead.`
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
const ssml = buildSsml({
|
|
348
|
+
text: options.text,
|
|
349
|
+
voiceName: voice.includes(":") ? voice : `${voice}:${getMAIVoiceModel(this.modelId) ?? this.modelId}`,
|
|
350
|
+
locale: /^([a-z]{2,3}-[a-z]{2,4})-/i.exec(voice)?.[1],
|
|
351
|
+
speed: options.speed,
|
|
352
|
+
style,
|
|
353
|
+
styleDegree: style != null ? styleDegree : void 0
|
|
354
|
+
});
|
|
355
|
+
const { value: audio, responseHeaders, rawValue } = await postToApi({
|
|
356
|
+
url: this.config.url(),
|
|
357
|
+
headers: combineHeaders(this.config.headers(), {
|
|
358
|
+
"Content-Type": "application/ssml+xml",
|
|
359
|
+
"X-Microsoft-OutputFormat": outputFormat
|
|
360
|
+
}, options.headers),
|
|
361
|
+
body: {
|
|
362
|
+
content: ssml,
|
|
363
|
+
values: ssml
|
|
364
|
+
},
|
|
365
|
+
failedResponseHandler,
|
|
366
|
+
successfulResponseHandler: createBinaryResponseHandler(),
|
|
367
|
+
abortSignal: options.abortSignal,
|
|
368
|
+
fetch: this.config.fetch
|
|
369
|
+
});
|
|
370
|
+
return {
|
|
371
|
+
audio,
|
|
372
|
+
warnings,
|
|
373
|
+
request: { body: ssml },
|
|
374
|
+
response: {
|
|
375
|
+
timestamp: currentDate,
|
|
376
|
+
modelId: this.modelId,
|
|
377
|
+
headers: responseHeaders,
|
|
378
|
+
body: rawValue
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
function buildSsml({ text, voiceName, locale = "en-US", speed, style, styleDegree }) {
|
|
384
|
+
let content = escapeXml(text);
|
|
385
|
+
if (speed != null) content = `<prosody rate="${speed}">${content}</prosody>`;
|
|
386
|
+
if (style != null) {
|
|
387
|
+
const degree = styleDegree != null ? ` styledegree="${styleDegree}"` : "";
|
|
388
|
+
content = `<mstts:express-as style="${escapeXml(style)}"${degree}>${content}</mstts:express-as>`;
|
|
389
|
+
}
|
|
390
|
+
return `<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="http://www.w3.org/2001/mstts" xml:lang="${escapeXml(locale)}"><voice name="${escapeXml(voiceName)}">${content}</voice></speak>`;
|
|
391
|
+
}
|
|
392
|
+
const XML_ESCAPES = {
|
|
393
|
+
"&": "&",
|
|
394
|
+
"<": "<",
|
|
395
|
+
">": ">",
|
|
396
|
+
"\"": """,
|
|
397
|
+
"'": "'"
|
|
398
|
+
};
|
|
399
|
+
function escapeXml(value) {
|
|
400
|
+
return value.replace(/[&<>"']/g, (char) => XML_ESCAPES[char]);
|
|
401
|
+
}
|
|
402
|
+
function resolveVoice(voice, language) {
|
|
403
|
+
const code = language ? language.split("-")[0].toLowerCase() : void 0;
|
|
404
|
+
if (voice == null) {
|
|
405
|
+
if (code == null) return { voice: DEFAULT_VOICE };
|
|
406
|
+
if (code === "auto") return {
|
|
407
|
+
voice: DEFAULT_VOICE,
|
|
408
|
+
languageWarning: `Automatic language detection is not supported. ${DEFAULT_VOICE} was used.`
|
|
409
|
+
};
|
|
410
|
+
const defaultVoice = DEFAULT_VOICES.get(code);
|
|
411
|
+
return defaultVoice != null ? { voice: defaultVoice } : {
|
|
412
|
+
voice: DEFAULT_VOICE,
|
|
413
|
+
languageWarning: `No default MAI voice for language "${language}". ${DEFAULT_VOICE} was used.`
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
const voiceLanguage = /^([a-z]{2,3})-[a-z]{2,4}-/i.exec(voice)?.[1]?.toLowerCase();
|
|
417
|
+
return code != null && code !== "auto" && voiceLanguage != null && code !== voiceLanguage ? {
|
|
418
|
+
voice,
|
|
419
|
+
languageWarning: `The voice ${voice} selects the language. Language "${language}" was ignored.`
|
|
420
|
+
} : { voice };
|
|
421
|
+
}
|
|
422
|
+
const errorSchema = z.object({ error: z.object({ message: z.string() }) });
|
|
423
|
+
const failedResponseHandler = async ({ response, url, requestBodyValues }) => {
|
|
424
|
+
const responseHeaders = extractResponseHeaders(response);
|
|
425
|
+
const responseBody = await response.text();
|
|
426
|
+
const parsed = await safeParseJSON({
|
|
427
|
+
text: responseBody,
|
|
428
|
+
schema: errorSchema
|
|
429
|
+
});
|
|
430
|
+
const isVoiceReset = response.status === 502 && responseBody.includes("reset reason: protocol error");
|
|
431
|
+
const message = parsed.success ? parsed.value.error.message : isVoiceReset ? "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." : response.status === 400 ? "Azure Speech request failed with status 400. Check the voice name, style, and output format." : `Azure Speech request failed with status ${response.status}.`;
|
|
432
|
+
return {
|
|
433
|
+
responseHeaders,
|
|
434
|
+
value: new APICallError({
|
|
435
|
+
message,
|
|
436
|
+
url,
|
|
437
|
+
requestBodyValues,
|
|
438
|
+
statusCode: response.status,
|
|
439
|
+
responseHeaders,
|
|
440
|
+
responseBody,
|
|
441
|
+
isRetryable: isVoiceReset ? false : void 0
|
|
442
|
+
})
|
|
443
|
+
};
|
|
444
|
+
};
|
|
445
|
+
//#endregion
|
|
446
|
+
//#region src/azure-mai-transcription-model-options.ts
|
|
447
|
+
const azureMaiTranscriptionModelOptionsShape = () => ({
|
|
448
|
+
/**
|
|
449
|
+
* Language hint for streaming transcription, e.g. `en`. Omit for automatic
|
|
450
|
+
* language detection.
|
|
451
|
+
*/
|
|
452
|
+
language: z.string().min(1).optional() });
|
|
453
|
+
lazySchema(() => zodSchema(z.strictObject(azureMaiTranscriptionModelOptionsShape())));
|
|
454
|
+
//#endregion
|
|
15
455
|
//#region src/azure-speech-transcription-model-options.ts
|
|
16
456
|
const azureSpeechTranscriptionModelOptionsShape = () => ({
|
|
17
457
|
/**
|
|
@@ -47,13 +487,29 @@ lazySchema(() => zodSchema(z.strictObject(azureSpeechTranscriptionModelOptionsSh
|
|
|
47
487
|
//#region src/azure-transcription-model-options.ts
|
|
48
488
|
const azureTranscriptionModelOptions = lazySchema(() => zodSchema(z.strictObject({
|
|
49
489
|
/**
|
|
50
|
-
* API to use. Defaults to Speech for MAI-Transcribe
|
|
490
|
+
* API to use. Defaults to Speech for MAI-Transcribe models, MAI for
|
|
491
|
+
* MAI-Transcribe-2-Streaming, and OpenAI otherwise.
|
|
51
492
|
*/
|
|
52
|
-
api: z.enum([
|
|
53
|
-
|
|
493
|
+
api: z.enum([
|
|
494
|
+
"openai",
|
|
495
|
+
"speech",
|
|
496
|
+
"mai"
|
|
497
|
+
]).optional(),
|
|
498
|
+
...azureSpeechTranscriptionModelOptionsShape(),
|
|
499
|
+
...azureMaiTranscriptionModelOptionsShape()
|
|
54
500
|
})));
|
|
55
|
-
|
|
56
|
-
|
|
501
|
+
const maiTranscribeModels = /* @__PURE__ */ new Map([["mai-transcribe-2", {
|
|
502
|
+
name: "MAI-Transcribe-2",
|
|
503
|
+
supportsTimestamps: true
|
|
504
|
+
}], ["mai-transcribe-1.5", {
|
|
505
|
+
name: "MAI-Transcribe-1.5",
|
|
506
|
+
supportsTimestamps: false
|
|
507
|
+
}]]);
|
|
508
|
+
function getMAITranscribeModel(modelId) {
|
|
509
|
+
return maiTranscribeModels.get(modelId.toLowerCase());
|
|
510
|
+
}
|
|
511
|
+
function isMAITranscribeStreaming(modelId) {
|
|
512
|
+
return modelId.toLowerCase() === "mai-transcribe-2-streaming";
|
|
57
513
|
}
|
|
58
514
|
//#endregion
|
|
59
515
|
//#region src/azure-speech-transcription-model.ts
|
|
@@ -66,14 +522,15 @@ var AzureSpeechTranscriptionModel = class {
|
|
|
66
522
|
}
|
|
67
523
|
async doGenerate(options, azureOptions = {}) {
|
|
68
524
|
const timestamp = /* @__PURE__ */ new Date();
|
|
525
|
+
const maiModel = getMAITranscribeModel(this.modelId);
|
|
69
526
|
const formData = new FormData();
|
|
70
527
|
formData.append("audio", new Blob([typeof options.audio === "string" ? convertBase64ToUint8Array(options.audio) : options.audio], { type: options.mediaType }), `audio.${mediaTypeToExtension(options.mediaType)}`);
|
|
71
528
|
formData.append("definition", JSON.stringify({
|
|
72
529
|
enhancedMode: {
|
|
73
530
|
enabled: true,
|
|
74
|
-
model:
|
|
531
|
+
model: maiModel?.name ?? this.modelId,
|
|
75
532
|
modelOptions: {
|
|
76
|
-
timestamps: azureOptions.timestamps ?? "segment",
|
|
533
|
+
timestamps: azureOptions.timestamps ?? (maiModel?.supportsTimestamps === false ? void 0 : "segment"),
|
|
77
534
|
transcribeStyle: azureOptions.transcribeStyle
|
|
78
535
|
}
|
|
79
536
|
},
|
|
@@ -136,7 +593,7 @@ const responseSchema = z.object({
|
|
|
136
593
|
});
|
|
137
594
|
//#endregion
|
|
138
595
|
//#region src/version.ts
|
|
139
|
-
const VERSION = "4.0.
|
|
596
|
+
const VERSION = "4.0.90";
|
|
140
597
|
//#endregion
|
|
141
598
|
//#region src/azure-openai-provider.ts
|
|
142
599
|
function getAzureOpenAIBaseURLInfo(baseURL) {
|
|
@@ -168,7 +625,7 @@ function createAzure(options = {}) {
|
|
|
168
625
|
const authHeaders = tokenProvider ? {} : { [api === "speech" ? "Ocp-Apim-Subscription-Key" : "api-key"]: loadApiKey({
|
|
169
626
|
apiKey: options.apiKey,
|
|
170
627
|
environmentVariableName: "AZURE_API_KEY",
|
|
171
|
-
description: api === "speech" ? "Azure Speech" : "Azure OpenAI"
|
|
628
|
+
description: api === "speech" ? "Azure Speech" : api === "mai" ? "Azure MAI" : "Azure OpenAI"
|
|
172
629
|
}) };
|
|
173
630
|
return withUserAgentSuffix({
|
|
174
631
|
...authHeaders,
|
|
@@ -252,22 +709,34 @@ function createAzure(options = {}) {
|
|
|
252
709
|
supportsMaskInputs: void 0
|
|
253
710
|
}
|
|
254
711
|
});
|
|
712
|
+
const speechBaseURL = () => withoutTrailingSlash(options.speechBaseURL) ?? `https://${getResourceName()}.cognitiveservices.azure.com`;
|
|
255
713
|
const createTranscriptionModel = (modelId) => new AzureTranscriptionModel(modelId, options, new OpenAITranscriptionModel(modelId, {
|
|
256
714
|
provider: "azure.transcription",
|
|
257
715
|
url,
|
|
258
716
|
headers: getHeaders,
|
|
259
717
|
fetch
|
|
260
718
|
}), new AzureSpeechTranscriptionModel(modelId, {
|
|
261
|
-
url: () => `${
|
|
719
|
+
url: () => `${speechBaseURL()}/speechtotext/transcriptions:transcribe?api-version=2025-10-15`,
|
|
262
720
|
headers: () => getHeaders("speech"),
|
|
263
721
|
fetch
|
|
722
|
+
}), new AzureMaiTranscriptionModel(modelId, {
|
|
723
|
+
url: () => `${withoutTrailingSlash(options.maiBaseURL) ?? `https://${getResourceName()}.services.ai.azure.com/mai/v1`}/realtime?intent=transcription`,
|
|
724
|
+
headers: async () => tokenProvider ? {
|
|
725
|
+
authorization: `Bearer ${await tokenProvider()}`,
|
|
726
|
+
...getHeaders("mai")
|
|
727
|
+
} : getHeaders("mai"),
|
|
728
|
+
webSocket: options.webSocket
|
|
264
729
|
}));
|
|
265
|
-
const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, {
|
|
730
|
+
const createSpeechModel = (modelId) => new AzureSpeechModel(modelId, options, new OpenAISpeechModel(modelId, {
|
|
266
731
|
provider: "azure.speech",
|
|
267
732
|
url,
|
|
268
733
|
headers: getHeaders,
|
|
269
734
|
fetch
|
|
270
|
-
})
|
|
735
|
+
}), new AzureSpeechSpeechModel(modelId, {
|
|
736
|
+
url: () => `${speechBaseURL()}/tts/cognitiveservices/v1`,
|
|
737
|
+
headers: () => getHeaders("speech"),
|
|
738
|
+
fetch
|
|
739
|
+
}));
|
|
271
740
|
const provider = function(deploymentId) {
|
|
272
741
|
if (new.target) throw new Error("The Azure OpenAI model function cannot be called with the new keyword.");
|
|
273
742
|
return createResponsesModel(deploymentId);
|
|
@@ -287,6 +756,7 @@ function createAzure(options = {}) {
|
|
|
287
756
|
provider.transcription = createTranscriptionModel;
|
|
288
757
|
provider.transcriptionModel = createTranscriptionModel;
|
|
289
758
|
provider.speech = createSpeechModel;
|
|
759
|
+
provider.speechModel = createSpeechModel;
|
|
290
760
|
provider.tools = azureOpenaiTools;
|
|
291
761
|
return provider;
|
|
292
762
|
}
|
|
@@ -295,11 +765,12 @@ function createAzure(options = {}) {
|
|
|
295
765
|
*/
|
|
296
766
|
const azure = createAzure();
|
|
297
767
|
var AzureTranscriptionModel = class {
|
|
298
|
-
constructor(modelId, config, openai, speech) {
|
|
768
|
+
constructor(modelId, config, openai, speech, mai) {
|
|
299
769
|
this.modelId = modelId;
|
|
300
770
|
this.config = config;
|
|
301
771
|
this.openai = openai;
|
|
302
772
|
this.speech = speech;
|
|
773
|
+
this.mai = mai;
|
|
303
774
|
this.specificationVersion = "v4";
|
|
304
775
|
this.provider = "azure.transcription";
|
|
305
776
|
}
|
|
@@ -313,35 +784,89 @@ var AzureTranscriptionModel = class {
|
|
|
313
784
|
return createAzure(options.config).transcription(options.modelId);
|
|
314
785
|
}
|
|
315
786
|
async doGenerate(options) {
|
|
316
|
-
const { api,
|
|
317
|
-
if (api === "
|
|
787
|
+
const { api, speechOptions, maiOptions } = await this.getOptions(options.providerOptions);
|
|
788
|
+
if (api === "mai") return this.mai.doGenerate();
|
|
789
|
+
if (api === "speech") {
|
|
790
|
+
const result = await this.speech.doGenerate(options, speechOptions);
|
|
791
|
+
return {
|
|
792
|
+
...result,
|
|
793
|
+
warnings: [...result.warnings, ...maiOnlyWarnings(maiOptions)]
|
|
794
|
+
};
|
|
795
|
+
}
|
|
318
796
|
const result = await this.openai.doGenerate(options);
|
|
319
797
|
return {
|
|
320
798
|
...result,
|
|
321
|
-
warnings: [
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
799
|
+
warnings: [
|
|
800
|
+
...result.warnings,
|
|
801
|
+
...speechOnlyWarnings(speechOptions),
|
|
802
|
+
...maiOnlyWarnings(maiOptions)
|
|
803
|
+
]
|
|
326
804
|
};
|
|
327
805
|
}
|
|
328
806
|
async doStream(options) {
|
|
329
|
-
const { api } = await this.getOptions(options.providerOptions);
|
|
807
|
+
const { api, speechOptions, maiOptions } = await this.getOptions(options.providerOptions);
|
|
330
808
|
if (api === "speech") throw new UnsupportedFunctionalityError({ functionality: "streaming transcription with the Azure Speech API" });
|
|
809
|
+
if (api === "mai") return this.mai.doStream(options, maiOptions, speechOnlyWarnings(speechOptions));
|
|
331
810
|
return this.openai.doStream(options);
|
|
332
811
|
}
|
|
333
812
|
async getOptions(providerOptions) {
|
|
334
|
-
const
|
|
813
|
+
const { api, language, ...speechOptions } = await parseProviderOptions({
|
|
335
814
|
provider: "azure",
|
|
336
815
|
providerOptions,
|
|
337
816
|
schema: azureTranscriptionModelOptions
|
|
817
|
+
}) ?? {};
|
|
818
|
+
return {
|
|
819
|
+
api: api ?? (isMAITranscribeStreaming(this.modelId) ? "mai" : getMAITranscribeModel(this.modelId) ? "speech" : "openai"),
|
|
820
|
+
speechOptions,
|
|
821
|
+
maiOptions: language != null ? { language } : {}
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
};
|
|
825
|
+
var AzureSpeechModel = class {
|
|
826
|
+
constructor(modelId, config, openai, speech) {
|
|
827
|
+
this.modelId = modelId;
|
|
828
|
+
this.config = config;
|
|
829
|
+
this.openai = openai;
|
|
830
|
+
this.speech = speech;
|
|
831
|
+
this.specificationVersion = "v4";
|
|
832
|
+
this.provider = "azure.speech";
|
|
833
|
+
}
|
|
834
|
+
static [WORKFLOW_SERIALIZE](model) {
|
|
835
|
+
return serializeModelOptions({
|
|
836
|
+
modelId: model.modelId,
|
|
837
|
+
config: model.config
|
|
338
838
|
});
|
|
839
|
+
}
|
|
840
|
+
static [WORKFLOW_DESERIALIZE](options) {
|
|
841
|
+
return createAzure(options.config).speech(options.modelId);
|
|
842
|
+
}
|
|
843
|
+
async doGenerate(options) {
|
|
844
|
+
const { api, ...speechOptions } = await parseProviderOptions({
|
|
845
|
+
provider: "azure",
|
|
846
|
+
providerOptions: options.providerOptions,
|
|
847
|
+
schema: azureSpeechModelOptions
|
|
848
|
+
}) ?? {};
|
|
849
|
+
if ((api ?? (getMAIVoiceModel(this.modelId) ? "speech" : "openai")) === "speech") return this.speech.doGenerate(options, speechOptions);
|
|
850
|
+
const result = await this.openai.doGenerate(options);
|
|
339
851
|
return {
|
|
340
|
-
...
|
|
341
|
-
|
|
852
|
+
...result,
|
|
853
|
+
warnings: [...result.warnings, ...speechOnlyWarnings(speechOptions)]
|
|
342
854
|
};
|
|
343
855
|
}
|
|
344
856
|
};
|
|
857
|
+
function speechOnlyWarnings(options) {
|
|
858
|
+
return unsupportedOptionWarnings(options, "This option requires the Azure Speech API.");
|
|
859
|
+
}
|
|
860
|
+
function maiOnlyWarnings(options) {
|
|
861
|
+
return unsupportedOptionWarnings(options, "This option requires MAI streaming transcription.");
|
|
862
|
+
}
|
|
863
|
+
function unsupportedOptionWarnings(options, details) {
|
|
864
|
+
return Object.entries(options).filter(([, value]) => value !== void 0).map(([key]) => ({
|
|
865
|
+
type: "unsupported",
|
|
866
|
+
feature: `providerOptions.azure.${key}`,
|
|
867
|
+
details
|
|
868
|
+
}));
|
|
869
|
+
}
|
|
345
870
|
//#endregion
|
|
346
871
|
export { VERSION, azure, createAzure };
|
|
347
872
|
|