@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
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
import {
|
|
2
|
+
InvalidArgumentError,
|
|
3
|
+
UnsupportedFunctionalityError,
|
|
4
|
+
type Experimental_TranscriptionModelV4StreamPart as TranscriptionModelV4StreamPart,
|
|
5
|
+
type SharedV4Warning,
|
|
6
|
+
type TranscriptionModelV4,
|
|
7
|
+
} from '@ai-sdk/provider';
|
|
8
|
+
import {
|
|
9
|
+
connectToWebSocket,
|
|
10
|
+
convertToBase64,
|
|
11
|
+
safeParseJSON,
|
|
12
|
+
toWebSocketUrl,
|
|
13
|
+
waitForWebSocketBufferDrain,
|
|
14
|
+
type WebSocketConnection,
|
|
15
|
+
type WebSocketConstructor,
|
|
16
|
+
type WebSocketLike,
|
|
17
|
+
} from '@ai-sdk/provider-utils';
|
|
18
|
+
import type { AzureTranscriptionModelMaiOptions } from './azure-mai-transcription-model-options';
|
|
19
|
+
|
|
20
|
+
type StreamOptions = Parameters<
|
|
21
|
+
NonNullable<TranscriptionModelV4['doStream']>
|
|
22
|
+
>[0];
|
|
23
|
+
|
|
24
|
+
const SUPPORTED_SAMPLE_RATES = [16000, 24000];
|
|
25
|
+
const DEFAULT_SAMPLE_RATE = 24000;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* MAI streaming transcription over the OpenAI Realtime-compatible
|
|
29
|
+
* `/mai/v1/realtime` WebSocket. The model ID is the Foundry deployment name.
|
|
30
|
+
*/
|
|
31
|
+
export class AzureMaiTranscriptionModel implements TranscriptionModelV4 {
|
|
32
|
+
readonly specificationVersion = 'v4';
|
|
33
|
+
readonly provider = 'azure.transcription';
|
|
34
|
+
|
|
35
|
+
constructor(
|
|
36
|
+
readonly modelId: string,
|
|
37
|
+
private readonly config: {
|
|
38
|
+
url: () => string;
|
|
39
|
+
headers: () =>
|
|
40
|
+
| Record<string, string | undefined>
|
|
41
|
+
| PromiseLike<Record<string, string | undefined>>;
|
|
42
|
+
webSocket?: WebSocketConstructor;
|
|
43
|
+
_internal?: { currentDate?: () => Date };
|
|
44
|
+
},
|
|
45
|
+
) {}
|
|
46
|
+
|
|
47
|
+
async doGenerate(): Promise<
|
|
48
|
+
Awaited<ReturnType<TranscriptionModelV4['doGenerate']>>
|
|
49
|
+
> {
|
|
50
|
+
throw new UnsupportedFunctionalityError({
|
|
51
|
+
functionality: `file transcription with ${this.modelId} (use streaming transcription)`,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async doStream(
|
|
56
|
+
options: StreamOptions,
|
|
57
|
+
maiOptions: AzureTranscriptionModelMaiOptions = {},
|
|
58
|
+
warnings: SharedV4Warning[] = [],
|
|
59
|
+
): Promise<
|
|
60
|
+
Awaited<ReturnType<NonNullable<TranscriptionModelV4['doStream']>>>
|
|
61
|
+
> {
|
|
62
|
+
const currentDate = this.config._internal?.currentDate?.() ?? new Date();
|
|
63
|
+
const { type, rate = DEFAULT_SAMPLE_RATE } = options.inputAudioFormat;
|
|
64
|
+
if (type !== 'audio/pcm' || !SUPPORTED_SAMPLE_RATES.includes(rate)) {
|
|
65
|
+
throw new InvalidArgumentError({
|
|
66
|
+
argument: 'inputAudioFormat',
|
|
67
|
+
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` : ''}.`,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const sessionUpdate = {
|
|
72
|
+
type: 'session.update',
|
|
73
|
+
session: {
|
|
74
|
+
type: 'transcription',
|
|
75
|
+
audio: {
|
|
76
|
+
input: {
|
|
77
|
+
format: { type: 'audio/pcm', rate },
|
|
78
|
+
transcription: {
|
|
79
|
+
model: this.modelId,
|
|
80
|
+
...(maiOptions.language != null
|
|
81
|
+
? { language: maiOptions.language }
|
|
82
|
+
: {}),
|
|
83
|
+
},
|
|
84
|
+
// MAI supports neither server VAD nor noise reduction; the stream
|
|
85
|
+
// commits once when the input audio ends.
|
|
86
|
+
turn_detection: null,
|
|
87
|
+
noise_reduction: null,
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const headers = {
|
|
94
|
+
...(await this.config.headers()),
|
|
95
|
+
...options.headers,
|
|
96
|
+
};
|
|
97
|
+
// Native WebSocket constructors drop headers, so bearer auth would be lost.
|
|
98
|
+
if (
|
|
99
|
+
this.config.webSocket == null &&
|
|
100
|
+
Object.entries(headers).some(
|
|
101
|
+
([key, value]) =>
|
|
102
|
+
key.toLowerCase() === 'authorization' && value != null,
|
|
103
|
+
)
|
|
104
|
+
) {
|
|
105
|
+
throw new InvalidArgumentError({
|
|
106
|
+
argument: 'webSocket',
|
|
107
|
+
message:
|
|
108
|
+
'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.',
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return {
|
|
113
|
+
request: { body: sessionUpdate },
|
|
114
|
+
response: { timestamp: currentDate, modelId: this.modelId },
|
|
115
|
+
stream: createMaiTranscriptionStream({
|
|
116
|
+
...getConnection({
|
|
117
|
+
url: toWebSocketUrl(this.config.url()),
|
|
118
|
+
headers,
|
|
119
|
+
supportsHeaders: this.config.webSocket != null,
|
|
120
|
+
}),
|
|
121
|
+
webSocket: this.config.webSocket,
|
|
122
|
+
sessionUpdate,
|
|
123
|
+
bytesPerSecond: rate * 2,
|
|
124
|
+
language: maiOptions.language,
|
|
125
|
+
warnings,
|
|
126
|
+
audio: options.audio,
|
|
127
|
+
abortSignal: options.abortSignal,
|
|
128
|
+
includeRawChunks: options.includeRawChunks,
|
|
129
|
+
}),
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Native WebSocket constructors cannot send headers, so the key moves to the
|
|
135
|
+
// `api-key` query parameter that MAI also accepts.
|
|
136
|
+
function getConnection({
|
|
137
|
+
url,
|
|
138
|
+
headers,
|
|
139
|
+
supportsHeaders,
|
|
140
|
+
}: {
|
|
141
|
+
url: URL;
|
|
142
|
+
headers: Record<string, string | undefined>;
|
|
143
|
+
supportsHeaders: boolean;
|
|
144
|
+
}) {
|
|
145
|
+
if (supportsHeaders) {
|
|
146
|
+
return { url, headers };
|
|
147
|
+
}
|
|
148
|
+
const remaining: Record<string, string | undefined> = {};
|
|
149
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
150
|
+
if (key.toLowerCase() === 'api-key') {
|
|
151
|
+
if (value != null) url.searchParams.set('api-key', value);
|
|
152
|
+
} else {
|
|
153
|
+
remaining[key] = value;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return { url, headers: remaining };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
type MaiRealtimeEvent = {
|
|
160
|
+
type?: string;
|
|
161
|
+
item_id?: string;
|
|
162
|
+
delta?: string;
|
|
163
|
+
intermediate?: string;
|
|
164
|
+
transcript?: string;
|
|
165
|
+
error?: { message?: string; code?: string };
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
function createMaiTranscriptionStream({
|
|
169
|
+
url,
|
|
170
|
+
headers,
|
|
171
|
+
webSocket,
|
|
172
|
+
sessionUpdate,
|
|
173
|
+
bytesPerSecond,
|
|
174
|
+
language,
|
|
175
|
+
warnings,
|
|
176
|
+
audio,
|
|
177
|
+
abortSignal,
|
|
178
|
+
includeRawChunks,
|
|
179
|
+
}: {
|
|
180
|
+
url: URL;
|
|
181
|
+
headers: Record<string, string | undefined>;
|
|
182
|
+
webSocket: WebSocketConstructor | undefined;
|
|
183
|
+
sessionUpdate: unknown;
|
|
184
|
+
bytesPerSecond: number;
|
|
185
|
+
language: string | undefined;
|
|
186
|
+
warnings: SharedV4Warning[];
|
|
187
|
+
audio: ReadableStream<Uint8Array | string>;
|
|
188
|
+
abortSignal: AbortSignal | undefined;
|
|
189
|
+
includeRawChunks: boolean | undefined;
|
|
190
|
+
}) {
|
|
191
|
+
let finished = false;
|
|
192
|
+
let cleanup: (closeCode?: number) => void = () => {};
|
|
193
|
+
|
|
194
|
+
return new ReadableStream<TranscriptionModelV4StreamPart>({
|
|
195
|
+
start: controller => {
|
|
196
|
+
let audioReader:
|
|
197
|
+
| ReadableStreamDefaultReader<Uint8Array | string>
|
|
198
|
+
| undefined;
|
|
199
|
+
let connection: WebSocketConnection | undefined;
|
|
200
|
+
let audioStarted = false;
|
|
201
|
+
let committed = false;
|
|
202
|
+
let audioBytes = 0;
|
|
203
|
+
let deltas = '';
|
|
204
|
+
|
|
205
|
+
cleanup = (closeCode?: number) => {
|
|
206
|
+
if (audioReader != null) {
|
|
207
|
+
void audioReader.cancel().catch(() => {});
|
|
208
|
+
} else {
|
|
209
|
+
void audio.cancel().catch(() => {});
|
|
210
|
+
}
|
|
211
|
+
connection?.close(closeCode);
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
const finishWithError = (error: unknown) => {
|
|
215
|
+
if (finished) return;
|
|
216
|
+
finished = true;
|
|
217
|
+
cleanup();
|
|
218
|
+
controller.error(error);
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
const finish = (text: string) => {
|
|
222
|
+
if (finished) return;
|
|
223
|
+
finished = true;
|
|
224
|
+
controller.enqueue({
|
|
225
|
+
type: 'finish',
|
|
226
|
+
text,
|
|
227
|
+
segments: [],
|
|
228
|
+
language,
|
|
229
|
+
...(audioBytes > 0
|
|
230
|
+
? { durationInSeconds: audioBytes / bytesPerSecond }
|
|
231
|
+
: {}),
|
|
232
|
+
});
|
|
233
|
+
controller.close();
|
|
234
|
+
cleanup(1000);
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
const sendAudio = async (socket: WebSocketLike) => {
|
|
238
|
+
audioReader = audio.getReader();
|
|
239
|
+
try {
|
|
240
|
+
while (true) {
|
|
241
|
+
const { done, value } = await audioReader.read();
|
|
242
|
+
if (done || finished) break;
|
|
243
|
+
const base64 = convertToBase64(value);
|
|
244
|
+
if (base64.length === 0) continue;
|
|
245
|
+
audioBytes +=
|
|
246
|
+
typeof value === 'string'
|
|
247
|
+
? base64ByteLength(base64)
|
|
248
|
+
: value.byteLength;
|
|
249
|
+
socket.send(
|
|
250
|
+
JSON.stringify({
|
|
251
|
+
type: 'input_audio_buffer.append',
|
|
252
|
+
audio: base64,
|
|
253
|
+
}),
|
|
254
|
+
);
|
|
255
|
+
await waitForWebSocketBufferDrain(socket);
|
|
256
|
+
}
|
|
257
|
+
} finally {
|
|
258
|
+
audioReader.releaseLock();
|
|
259
|
+
audioReader = undefined;
|
|
260
|
+
}
|
|
261
|
+
if (finished) return;
|
|
262
|
+
if (audioBytes === 0) {
|
|
263
|
+
finish('');
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
committed = true;
|
|
267
|
+
socket.send(JSON.stringify({ type: 'input_audio_buffer.commit' }));
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
connection = connectToWebSocket({
|
|
271
|
+
url,
|
|
272
|
+
headers,
|
|
273
|
+
webSocket,
|
|
274
|
+
abortSignal,
|
|
275
|
+
onAbort: finishWithError,
|
|
276
|
+
onProcessingError: finishWithError,
|
|
277
|
+
onOpen: () => {
|
|
278
|
+
controller.enqueue({ type: 'stream-start', warnings });
|
|
279
|
+
},
|
|
280
|
+
onMessageText: async text => {
|
|
281
|
+
const parsed = await safeParseJSON({ text });
|
|
282
|
+
if (!parsed.success) return;
|
|
283
|
+
const event = parsed.value as MaiRealtimeEvent;
|
|
284
|
+
const socket = connection?.socket;
|
|
285
|
+
|
|
286
|
+
if (includeRawChunks) {
|
|
287
|
+
controller.enqueue({ type: 'raw', rawValue: event });
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
switch (event.type) {
|
|
291
|
+
case 'session.created': {
|
|
292
|
+
socket?.send(JSON.stringify(sessionUpdate));
|
|
293
|
+
break;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// Settings are locked after the first append, so audio waits for
|
|
297
|
+
// the server to acknowledge the session configuration.
|
|
298
|
+
case 'session.updated': {
|
|
299
|
+
if (audioStarted || socket == null) break;
|
|
300
|
+
audioStarted = true;
|
|
301
|
+
void sendAudio(socket).catch(finishWithError);
|
|
302
|
+
break;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
case 'conversation.item.input_audio_transcription.delta': {
|
|
306
|
+
deltas += event.delta ?? '';
|
|
307
|
+
controller.enqueue({
|
|
308
|
+
type: 'transcript-delta',
|
|
309
|
+
id: event.item_id,
|
|
310
|
+
delta: event.delta ?? '',
|
|
311
|
+
});
|
|
312
|
+
break;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// MAI-specific: the provisional text after the latest delta.
|
|
316
|
+
case 'conversation.item.input_audio_transcription.intermediate': {
|
|
317
|
+
controller.enqueue({
|
|
318
|
+
type: 'transcript-partial',
|
|
319
|
+
id: event.item_id,
|
|
320
|
+
text: event.intermediate ?? '',
|
|
321
|
+
});
|
|
322
|
+
break;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
case 'conversation.item.input_audio_transcription.completed': {
|
|
326
|
+
const transcript = event.transcript ?? deltas;
|
|
327
|
+
controller.enqueue({
|
|
328
|
+
type: 'transcript-final',
|
|
329
|
+
id: event.item_id,
|
|
330
|
+
text: transcript,
|
|
331
|
+
});
|
|
332
|
+
if (committed) finish(transcript);
|
|
333
|
+
break;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
case 'conversation.item.input_audio_transcription.failed':
|
|
337
|
+
case 'error': {
|
|
338
|
+
finishWithError(
|
|
339
|
+
new Error(
|
|
340
|
+
`Azure MAI transcription error${event.error?.code != null ? ` (${event.error.code})` : ''}: ${event.error?.message ?? 'unknown error'}`,
|
|
341
|
+
),
|
|
342
|
+
);
|
|
343
|
+
break;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
},
|
|
347
|
+
onSocketError: () => {
|
|
348
|
+
finishWithError(new Error('Azure MAI transcription WebSocket error'));
|
|
349
|
+
},
|
|
350
|
+
onClose: ({ code, reason }) => {
|
|
351
|
+
finishWithError(
|
|
352
|
+
new Error(
|
|
353
|
+
`Azure MAI transcription connection closed before the transcript completed${code != null ? ` (code ${code}${reason ? `: ${reason}` : ''})` : ''}`,
|
|
354
|
+
),
|
|
355
|
+
);
|
|
356
|
+
},
|
|
357
|
+
});
|
|
358
|
+
},
|
|
359
|
+
|
|
360
|
+
cancel: () => {
|
|
361
|
+
if (finished) return;
|
|
362
|
+
finished = true;
|
|
363
|
+
cleanup();
|
|
364
|
+
},
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function base64ByteLength(base64: string) {
|
|
369
|
+
const padding = base64.endsWith('==') ? 2 : base64.endsWith('=') ? 1 : 0;
|
|
370
|
+
return (base64.length * 3) / 4 - padding;
|
|
371
|
+
}
|
|
@@ -31,7 +31,9 @@ import {
|
|
|
31
31
|
withoutTrailingSlash,
|
|
32
32
|
withUserAgentSuffix,
|
|
33
33
|
type FetchFunction,
|
|
34
|
+
type WebSocketConstructor,
|
|
34
35
|
} from '@ai-sdk/provider-utils';
|
|
36
|
+
import { AzureMaiTranscriptionModel } from './azure-mai-transcription-model';
|
|
35
37
|
import { azureOpenaiTools } from './azure-openai-tools';
|
|
36
38
|
import {
|
|
37
39
|
azureSpeechModelOptions,
|
|
@@ -42,6 +44,7 @@ import { AzureSpeechTranscriptionModel } from './azure-speech-transcription-mode
|
|
|
42
44
|
import {
|
|
43
45
|
azureTranscriptionModelOptions,
|
|
44
46
|
getMAITranscribeModel,
|
|
47
|
+
isMAITranscribeStreaming,
|
|
45
48
|
} from './azure-transcription-model-options';
|
|
46
49
|
import { VERSION } from './version';
|
|
47
50
|
|
|
@@ -105,7 +108,8 @@ export interface AzureOpenAIProvider extends ProviderV4 {
|
|
|
105
108
|
|
|
106
109
|
/**
|
|
107
110
|
* Creates an Azure transcription model. MAI-Transcribe models use the Speech
|
|
108
|
-
* API
|
|
111
|
+
* API and MAI-Transcribe-2-Streaming the MAI realtime API by default; other
|
|
112
|
+
* IDs use OpenAI. Override with providerOptions.azure.api.
|
|
109
113
|
*/
|
|
110
114
|
transcription(deploymentId: string): TranscriptionModelV4;
|
|
111
115
|
|
|
@@ -194,6 +198,20 @@ export interface AzureOpenAIProviderSettings {
|
|
|
194
198
|
* Speech requests do not use `baseURL` or `apiVersion`.
|
|
195
199
|
*/
|
|
196
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;
|
|
197
215
|
}
|
|
198
216
|
|
|
199
217
|
function getAzureOpenAIBaseURLInfo(baseURL: string | undefined) {
|
|
@@ -238,7 +256,7 @@ export function createAzure(
|
|
|
238
256
|
});
|
|
239
257
|
}
|
|
240
258
|
|
|
241
|
-
const getHeaders = (api: 'openai' | 'speech' = 'openai') => {
|
|
259
|
+
const getHeaders = (api: 'openai' | 'speech' | 'mai' = 'openai') => {
|
|
242
260
|
const authHeaders = tokenProvider
|
|
243
261
|
? {}
|
|
244
262
|
: {
|
|
@@ -246,7 +264,12 @@ export function createAzure(
|
|
|
246
264
|
loadApiKey({
|
|
247
265
|
apiKey: options.apiKey,
|
|
248
266
|
environmentVariableName: 'AZURE_API_KEY',
|
|
249
|
-
description:
|
|
267
|
+
description:
|
|
268
|
+
api === 'speech'
|
|
269
|
+
? 'Azure Speech'
|
|
270
|
+
: api === 'mai'
|
|
271
|
+
? 'Azure MAI'
|
|
272
|
+
: 'Azure OpenAI',
|
|
250
273
|
}),
|
|
251
274
|
};
|
|
252
275
|
|
|
@@ -411,6 +434,21 @@ export function createAzure(
|
|
|
411
434
|
headers: () => getHeaders('speech'),
|
|
412
435
|
fetch,
|
|
413
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
|
+
}),
|
|
414
452
|
);
|
|
415
453
|
|
|
416
454
|
const createSpeechModel = (modelId: string) =>
|
|
@@ -475,6 +513,7 @@ class AzureTranscriptionModel implements TranscriptionModelV4 {
|
|
|
475
513
|
private readonly config: AzureOpenAIProviderSettings,
|
|
476
514
|
private readonly openai: OpenAITranscriptionModel,
|
|
477
515
|
private readonly speech: AzureSpeechTranscriptionModel,
|
|
516
|
+
private readonly mai: AzureMaiTranscriptionModel,
|
|
478
517
|
) {}
|
|
479
518
|
|
|
480
519
|
static [WORKFLOW_SERIALIZE](model: AzureTranscriptionModel) {
|
|
@@ -492,11 +531,18 @@ class AzureTranscriptionModel implements TranscriptionModelV4 {
|
|
|
492
531
|
}
|
|
493
532
|
|
|
494
533
|
async doGenerate(options: Parameters<TranscriptionModelV4['doGenerate']>[0]) {
|
|
495
|
-
const { api,
|
|
534
|
+
const { api, speechOptions, maiOptions } = await this.getOptions(
|
|
496
535
|
options.providerOptions,
|
|
497
536
|
);
|
|
537
|
+
if (api === 'mai') {
|
|
538
|
+
return this.mai.doGenerate();
|
|
539
|
+
}
|
|
498
540
|
if (api === 'speech') {
|
|
499
|
-
|
|
541
|
+
const result = await this.speech.doGenerate(options, speechOptions);
|
|
542
|
+
return {
|
|
543
|
+
...result,
|
|
544
|
+
warnings: [...result.warnings, ...maiOnlyWarnings(maiOptions)],
|
|
545
|
+
};
|
|
500
546
|
}
|
|
501
547
|
|
|
502
548
|
const result = await this.openai.doGenerate(options);
|
|
@@ -504,11 +550,8 @@ class AzureTranscriptionModel implements TranscriptionModelV4 {
|
|
|
504
550
|
...result,
|
|
505
551
|
warnings: [
|
|
506
552
|
...result.warnings,
|
|
507
|
-
...
|
|
508
|
-
|
|
509
|
-
feature: `providerOptions.azure.${key}`,
|
|
510
|
-
details: 'This option requires the Azure Speech API.',
|
|
511
|
-
})),
|
|
553
|
+
...speechOnlyWarnings(speechOptions),
|
|
554
|
+
...maiOnlyWarnings(maiOptions),
|
|
512
555
|
],
|
|
513
556
|
};
|
|
514
557
|
}
|
|
@@ -516,12 +559,21 @@ class AzureTranscriptionModel implements TranscriptionModelV4 {
|
|
|
516
559
|
async doStream(
|
|
517
560
|
options: Parameters<NonNullable<TranscriptionModelV4['doStream']>>[0],
|
|
518
561
|
) {
|
|
519
|
-
const { api } = await this.getOptions(
|
|
562
|
+
const { api, speechOptions, maiOptions } = await this.getOptions(
|
|
563
|
+
options.providerOptions,
|
|
564
|
+
);
|
|
520
565
|
if (api === 'speech') {
|
|
521
566
|
throw new UnsupportedFunctionalityError({
|
|
522
567
|
functionality: 'streaming transcription with the Azure Speech API',
|
|
523
568
|
});
|
|
524
569
|
}
|
|
570
|
+
if (api === 'mai') {
|
|
571
|
+
return this.mai.doStream(
|
|
572
|
+
options,
|
|
573
|
+
maiOptions,
|
|
574
|
+
speechOnlyWarnings(speechOptions),
|
|
575
|
+
);
|
|
576
|
+
}
|
|
525
577
|
return this.openai.doStream(options);
|
|
526
578
|
}
|
|
527
579
|
|
|
@@ -530,16 +582,22 @@ class AzureTranscriptionModel implements TranscriptionModelV4 {
|
|
|
530
582
|
TranscriptionModelV4['doGenerate']
|
|
531
583
|
>[0]['providerOptions'],
|
|
532
584
|
) {
|
|
533
|
-
const
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
585
|
+
const { api, language, ...speechOptions } =
|
|
586
|
+
(await parseProviderOptions({
|
|
587
|
+
provider: 'azure',
|
|
588
|
+
providerOptions,
|
|
589
|
+
schema: azureTranscriptionModelOptions,
|
|
590
|
+
})) ?? {};
|
|
538
591
|
return {
|
|
539
|
-
...options,
|
|
540
592
|
api:
|
|
541
|
-
|
|
542
|
-
(
|
|
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 } : {},
|
|
543
601
|
};
|
|
544
602
|
}
|
|
545
603
|
}
|
|
@@ -587,18 +645,34 @@ class AzureSpeechModel implements SpeechModelV4 {
|
|
|
587
645
|
const result = await this.openai.doGenerate(options);
|
|
588
646
|
return {
|
|
589
647
|
...result,
|
|
590
|
-
warnings: [
|
|
591
|
-
...result.warnings,
|
|
592
|
-
...Object.entries(speechOptions)
|
|
593
|
-
.filter(([, value]) => value !== undefined)
|
|
594
|
-
.map(
|
|
595
|
-
([key]): SharedV4Warning => ({
|
|
596
|
-
type: 'unsupported',
|
|
597
|
-
feature: `providerOptions.azure.${key}`,
|
|
598
|
-
details: 'This option requires the Azure Speech API.',
|
|
599
|
-
}),
|
|
600
|
-
),
|
|
601
|
-
],
|
|
648
|
+
warnings: [...result.warnings, ...speechOnlyWarnings(speechOptions)],
|
|
602
649
|
};
|
|
603
650
|
}
|
|
604
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
|
+
}
|
|
@@ -24,6 +24,8 @@ export type AzureSpeechModelOptions = InferSchema<
|
|
|
24
24
|
|
|
25
25
|
// Azure voice-name suffixes by lowercase model ID.
|
|
26
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'],
|
|
27
29
|
['mai-voice-2-flash', 'MAI-Voice-2-Flash'],
|
|
28
30
|
['mai-voice-2', 'MAI-Voice-2'],
|
|
29
31
|
]);
|
|
@@ -18,8 +18,8 @@ import type { AzureSpeechModelSpeechOptions } from './azure-speech-speech-model-
|
|
|
18
18
|
|
|
19
19
|
const DEFAULT_VOICE = 'en-US-Harper';
|
|
20
20
|
|
|
21
|
-
// Default voice per ISO 639-1 language; available on MAI-Voice-2
|
|
22
|
-
// MAI-Voice-2
|
|
21
|
+
// Default voice per ISO 639-1 language; available on MAI-Voice-2,
|
|
22
|
+
// MAI-Voice-2.1, and their Flash variants.
|
|
23
23
|
const DEFAULT_VOICES = new Map([
|
|
24
24
|
['de', 'de-DE-Mia'],
|
|
25
25
|
['en', DEFAULT_VOICE],
|
|
@@ -248,8 +248,9 @@ const errorSchema = z.object({
|
|
|
248
248
|
error: z.object({ message: z.string() }),
|
|
249
249
|
});
|
|
250
250
|
|
|
251
|
-
// Azure Speech answers invalid requests (
|
|
252
|
-
//
|
|
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.
|
|
253
254
|
const failedResponseHandler: ResponseHandler<APICallError> = async ({
|
|
254
255
|
response,
|
|
255
256
|
url,
|
|
@@ -261,12 +262,17 @@ const failedResponseHandler: ResponseHandler<APICallError> = async ({
|
|
|
261
262
|
text: responseBody,
|
|
262
263
|
schema: errorSchema,
|
|
263
264
|
});
|
|
265
|
+
const isVoiceReset =
|
|
266
|
+
response.status === 502 &&
|
|
267
|
+
responseBody.includes('reset reason: protocol error');
|
|
264
268
|
|
|
265
269
|
const message = parsed.success
|
|
266
270
|
? parsed.value.error.message
|
|
267
|
-
:
|
|
268
|
-
? 'Azure Speech
|
|
269
|
-
:
|
|
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}.`;
|
|
270
276
|
|
|
271
277
|
return {
|
|
272
278
|
responseHeaders,
|
|
@@ -277,6 +283,7 @@ const failedResponseHandler: ResponseHandler<APICallError> = async ({
|
|
|
277
283
|
statusCode: response.status,
|
|
278
284
|
responseHeaders,
|
|
279
285
|
responseBody,
|
|
286
|
+
isRetryable: isVoiceReset ? false : undefined,
|
|
280
287
|
}),
|
|
281
288
|
};
|
|
282
289
|
};
|
|
@@ -4,16 +4,19 @@ import {
|
|
|
4
4
|
type InferSchema,
|
|
5
5
|
} from '@ai-sdk/provider-utils';
|
|
6
6
|
import { z } from 'zod/v4';
|
|
7
|
+
import { azureMaiTranscriptionModelOptionsShape } from './azure-mai-transcription-model-options';
|
|
7
8
|
import { azureSpeechTranscriptionModelOptionsShape } from './azure-speech-transcription-model-options';
|
|
8
9
|
|
|
9
10
|
export const azureTranscriptionModelOptions = lazySchema(() =>
|
|
10
11
|
zodSchema(
|
|
11
12
|
z.strictObject({
|
|
12
13
|
/**
|
|
13
|
-
* API to use. Defaults to Speech for MAI-Transcribe models,
|
|
14
|
+
* API to use. Defaults to Speech for MAI-Transcribe models, MAI for
|
|
15
|
+
* MAI-Transcribe-2-Streaming, and OpenAI otherwise.
|
|
14
16
|
*/
|
|
15
|
-
api: z.enum(['openai', 'speech']).optional(),
|
|
17
|
+
api: z.enum(['openai', 'speech', 'mai']).optional(),
|
|
16
18
|
...azureSpeechTranscriptionModelOptionsShape(),
|
|
19
|
+
...azureMaiTranscriptionModelOptionsShape(),
|
|
17
20
|
}),
|
|
18
21
|
),
|
|
19
22
|
);
|
|
@@ -35,3 +38,7 @@ const maiTranscribeModels = new Map([
|
|
|
35
38
|
export function getMAITranscribeModel(modelId: string) {
|
|
36
39
|
return maiTranscribeModels.get(modelId.toLowerCase());
|
|
37
40
|
}
|
|
41
|
+
|
|
42
|
+
export function isMAITranscribeStreaming(modelId: string): boolean {
|
|
43
|
+
return modelId.toLowerCase() === 'mai-transcribe-2-streaming';
|
|
44
|
+
}
|