import { getErrorMessage, type Experimental_TranscriptionModelV4StreamOptions as TranscriptionModelV4StreamOptions, type Experimental_TranscriptionModelV4StreamPart as TranscriptionModelV4StreamPart, type Experimental_TranscriptionModelV4StreamResult as TranscriptionModelV4StreamResult, type SharedV4ProviderMetadata, type SharedV4Warning, type TranscriptionModelV4, } from '@ai-sdk/provider'; import { lazySchema, zodSchema, combineHeaders, convertBase64ToUint8Array, convertUint8ArrayToBase64, createJsonErrorResponseHandler, createJsonResponseHandler, connectToWebSocket, normalizeHeaders, experimental_parseTranscriptionStreamPart as parseTranscriptionStreamPart, postJsonToApi, resolve, EXPERIMENTAL_TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE as TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE, waitForWebSocketBufferDrain, EXPERIMENTAL_TRANSCRIPTION_STREAM_START_FRAME_TYPE as TRANSCRIPTION_STREAM_START_FRAME_TYPE, type Experimental_TranscriptionStreamStartFrame, type Resolvable, type WebSocketConnection, type WebSocketConstructor, type WebSocketLike, } from '@ai-sdk/provider-utils'; import { z } from './zod'; import { asGatewayError } from './errors'; import { parseAuthMethod } from './errors/parse-auth-method'; import type { GatewayConfig } from './gateway-config'; import { createErrorFromServerErrorPart, errorControllerWithGatewayError, } from './gateway-stream-errors'; import { VERCEL_AI_GATEWAY_TEAM_HEADER } from './gateway-headers'; import { GATEWAY_TRANSCRIPTION_SUBPROTOCOL, getGatewayTranscriptionProtocols, } from './gateway-realtime-auth'; import { withGatewayRequestTelemetryRedaction } from './redact-gateway-request-credentials'; export class GatewayTranscriptionModel implements TranscriptionModelV4 { readonly specificationVersion = 'v4' as const; constructor( readonly modelId: string, private readonly config: GatewayConfig & { provider: string; o11yHeaders: Resolvable>; _internal?: { currentDate?: () => Date; }; }, ) {} get provider(): string { return this.config.provider; } async doGenerate({ audio, mediaType, providerOptions, timestampGranularities, headers, abortSignal, }: Parameters[0]): Promise< Awaited> > { const resolvedHeaders = this.config.headers ? await resolve(this.config.headers) : undefined; try { const { responseHeaders, value: responseBody, rawValue, } = await postJsonToApi({ url: this.getUrl(), headers: combineHeaders( resolvedHeaders, headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders), ), body: withGatewayRequestTelemetryRedaction({ audio: audio instanceof Uint8Array ? convertUint8ArrayToBase64(audio) : audio, mediaType, ...(providerOptions && { providerOptions }), }), successfulResponseHandler: createJsonResponseHandler( gatewayTranscriptionResponseSchema, ), failedResponseHandler: createJsonErrorResponseHandler({ errorSchema: z.any(), errorToMessage: data => getErrorMessage(data) ?? 'unknown error', }), ...(abortSignal && { abortSignal }), fetch: this.config.fetch, }); const warnings = [ ...(responseBody.warnings ?? []), ] as Array; if (timestampGranularities?.length) { warnings.push({ type: 'unsupported', feature: 'timestampGranularities', details: 'The AI Gateway adapter does not forward the shared timestampGranularities option.', }); } if ( isXaiTranscriptionModel(this.modelId) && requestsXaiDiarization(providerOptions) && !containsSpeaker(rawValue) ) { warnings.push({ type: 'unsupported', feature: 'providerOptions.xai.diarize', details: 'AI Gateway does not currently expose xAI speaker diarization metadata.', }); } return { text: responseBody.text, segments: responseBody.segments ?? [], ...(responseBody.words != null && { words: responseBody.words }), language: responseBody.language ?? undefined, durationInSeconds: responseBody.durationInSeconds ?? undefined, warnings, ...(responseBody.usage != null && { usage: responseBody.usage }), providerMetadata: responseBody.providerMetadata as SharedV4ProviderMetadata, response: { timestamp: new Date(), modelId: this.modelId, headers: responseHeaders, body: rawValue, }, }; } catch (error) { throw await asGatewayError( error, await parseAuthMethod(resolvedHeaders ?? {}), ); } } async doStream( options: TranscriptionModelV4StreamOptions, ): Promise { const currentDate = this.config._internal?.currentDate?.() ?? new Date(); const headers = combineHeaders( await resolve(this.config.headers ?? {}), options.headers ?? {}, this.getModelConfigHeaders(), await resolve(this.config.o11yHeaders), ); const authMethod = await parseAuthMethod(headers); // First frame after the WebSocket opens, per the transcription-stream // envelope. Optional keys are omitted so the frame stays minimal. const startFrame: Experimental_TranscriptionStreamStartFrame = withGatewayRequestTelemetryRedaction({ type: TRANSCRIPTION_STREAM_START_FRAME_TYPE, inputAudioFormat: options.inputAudioFormat, ...(options.providerOptions != null && { providerOptions: options.providerOptions, }), ...(options.includeRawChunks != null && { includeRawChunks: options.includeRawChunks, }), }); return { stream: createGatewayTranscriptionStream({ webSocket: this.config.webSocket, url: toGatewayTranscriptionUrl(this.config.baseURL, this.modelId), protocols: getProtocolsFromHeaders(headers), headers, startFrame, audio: options.audio, abortSignal: options.abortSignal, authMethod, }), request: { body: startFrame }, response: { timestamp: currentDate, modelId: this.modelId }, }; } private getUrl() { return `${this.config.baseURL}/transcription-model`; } private getModelConfigHeaders() { return { 'ai-transcription-model-specification-version': '4', 'ai-model-id': this.modelId, }; } } function isXaiTranscriptionModel(modelId: string): boolean { return modelId.startsWith('spacexai/') || modelId.startsWith('xai/'); } function requestsXaiDiarization( providerOptions: | Parameters[0]['providerOptions'] | undefined, ): boolean { return ( providerOptions?.xai?.diarize === true || providerOptions?.spacexai?.diarize === true ); } function containsSpeaker(value: unknown): boolean { if (Array.isArray(value)) { return value.some(containsSpeaker); } if (value == null || typeof value !== 'object') { return false; } return Object.entries(value).some( ([key, nestedValue]) => (key === 'speaker' && nestedValue != null) || containsSpeaker(nestedValue), ); } /** * Gateway streaming transcription WebSocket URL: HTTP(S) base upgraded to * WS(S), model id in `?ai-model-id=` (browser `WebSocket` cannot set headers; * slash-safe for qualified ids like `openai/gpt-realtime-whisper`). */ export function toGatewayTranscriptionUrl( baseURL: string, modelId: string, ): string { const url = new URL(`${baseURL.replace(/^http/, 'ws')}/transcription-model`); url.searchParams.set('ai-model-id', modelId); return url.toString(); } /** * Auth-carrying subprotocols from the resolved request headers (bearer token * + optional team scope). Native `WebSocket` cannot send headers, so auth * rides the `Sec-WebSocket-Protocol` handshake. Header lookups are * case-insensitive because `combineHeaders` does not normalize casing and * callers can pass arbitrary casing via the `headers` option. */ export function getProtocolsFromHeaders( headers: Record, { marker = GATEWAY_TRANSCRIPTION_SUBPROTOCOL, getProtocols = getGatewayTranscriptionProtocols, }: { marker?: string; getProtocols?: ( token: string, options: { teamIdOrSlug?: string }, ) => string[]; } = {}, ): string[] { const normalizedHeaders = normalizeHeaders(headers); const authorization = normalizedHeaders.authorization; const token = authorization?.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : undefined; return token == null ? [marker] : getProtocols(token, { teamIdOrSlug: normalizedHeaders[VERCEL_AI_GATEWAY_TEAM_HEADER], }); } /** Audio frames stay under server frame-size limits (envelope rule 7). */ const MAX_AUDIO_FRAME_BYTES = 64 * 1024; function createGatewayTranscriptionStream({ webSocket, url, protocols, headers, startFrame, audio, abortSignal, authMethod, }: { webSocket: WebSocketConstructor | undefined; url: string; protocols: string[]; headers: Record; startFrame: Experimental_TranscriptionStreamStartFrame; audio: ReadableStream; abortSignal: AbortSignal | undefined; authMethod: 'api-key' | 'oidc' | undefined; }): ReadableStream { let finished = false; let cleanup: (closeCode?: number) => void = () => {}; return new ReadableStream({ start: controller => { let audioReader: | ReadableStreamDefaultReader | undefined; let hasServerErrorPart = false; let lastServerError: unknown; let audioStopped = false; let connection: WebSocketConnection | undefined; cleanup = (closeCode?: number) => { if (audioReader != null) { void audioReader.cancel().catch(() => {}); } else { // Pre-open failure or abort: `sendAudio` never took a reader, so // cancel the caller's audio stream directly — otherwise an upstream // producer piping into it hangs. void audio.cancel().catch(() => {}); } connection?.close(closeCode); }; const stopAudio = () => { audioStopped = true; if (audioReader != null) { void audioReader.cancel().catch(() => {}); audioReader = undefined; } else { void audio.cancel().catch(() => {}); } }; const finishWithError = (error: unknown) => { if (finished) return; finished = true; cleanup(); void errorControllerWithGatewayError(controller, error, authMethod); }; const sendAudio = async (socket: WebSocketLike) => { const reader = audio.getReader(); audioReader = reader; try { while (true) { const { done, value } = await reader.read(); if (done || finished) break; // Binary frames; base64 string chunks are decoded first. Caller // chunks are split to stay under server frame-size limits // (envelope rule 7), with backpressure between frames. const bytes = typeof value === 'string' ? convertBase64ToUint8Array(value) : value; for ( let offset = 0; offset < bytes.length; offset += MAX_AUDIO_FRAME_BYTES ) { if (finished) break; socket.send( bytes.subarray(offset, offset + MAX_AUDIO_FRAME_BYTES), ); await waitForWebSocketBufferDrain(socket); } } } finally { reader.releaseLock(); // unlocked again: cleanup must cancel `audio`, not the reader if (audioReader === reader) { audioReader = undefined; } } if (!finished && !audioStopped) { socket.send( JSON.stringify({ type: TRANSCRIPTION_STREAM_AUDIO_DONE_FRAME_TYPE, }), ); } }; connection = connectToWebSocket({ url, protocols, headers, webSocket, abortSignal, onAbort: reason => { if (finished) return; finished = true; cleanup(); controller.error(reason); }, onProcessingError: finishWithError, onOpen: socket => { socket.send(JSON.stringify(startFrame)); void sendAudio(socket).catch(finishWithError); }, // Server frames are envelope-serialized stream parts; the codec // handles parsing, unknown-part skipping, and timestamp revival. onMessageText: text => { if (finished) return; const part = parseTranscriptionStreamPart(text); if (part == null) return; if (part.type === 'finish') { finished = true; controller.enqueue(part); controller.close(); cleanup(1000); return; } if (part.type === 'error') { // Remembered so the terminal close error (the server closes // non-1000 after an error part) surfaces the server's message // to promise-based consumers. hasServerErrorPart = true; lastServerError = part.error; // envelope rule 5: error parts are terminal — stop sending audio // while the server holds the connection open (e.g. for its final // billing flush) stopAudio(); } controller.enqueue(part); }, onSocketError: () => { finishWithError( new Error('Connection error on AI Gateway transcription stream'), ); }, onClose: () => { if (hasServerErrorPart) { if (finished) return; void createErrorFromServerErrorPart( lastServerError, authMethod, ).then(finishWithError); return; } finishWithError( new Error( 'AI Gateway transcription stream closed before a finish part was received', ), ); }, }); }, cancel: () => { if (finished) return; finished = true; cleanup(); }, }); } const providerMetadataEntrySchema = () => z.catchall(z.object({}), z.unknown()); const gatewayTranscriptionWarningSchema = () => z.discriminatedUnion('type', [ z.object({ type: z.literal('unsupported'), feature: z.string(), details: z.optional(z.string()), }), z.object({ type: z.literal('compatibility'), feature: z.string(), details: z.optional(z.string()), }), z.object({ type: z.literal('deprecated'), setting: z.string(), message: z.string(), }), z.object({ type: z.literal('other'), message: z.string(), }), ]); const gatewayTranscriptionResponseSchema = lazySchema(() => zodSchema( z.object({ text: z.string(), segments: z.optional( z.array( z.object({ text: z.string(), startSecond: z.number(), endSecond: z.number(), }), ), ), words: z.nullish( z.array( z.object({ text: z.string(), startSecond: z.number(), endSecond: z.number(), }), ), ), language: z.nullish(z.string()), durationInSeconds: z.nullish(z.number()), warnings: z.optional(z.array(gatewayTranscriptionWarningSchema())), usage: z.optional(z.record(z.string(), z.json())), providerMetadata: z.optional( z.record(z.string(), providerMetadataEntrySchema()), ), }), ), );