@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.
@@ -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
+ }