@ai-sdk/mistral 4.0.79 → 4.0.80

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,339 @@
1
+ import {
2
+ InvalidArgumentError,
3
+ type Experimental_TranscriptionModelV4StreamOptions as TranscriptionModelV4StreamOptions,
4
+ type Experimental_TranscriptionModelV4StreamPart as TranscriptionModelV4StreamPart,
5
+ type SharedV4Warning,
6
+ } from '@ai-sdk/provider';
7
+ import {
8
+ connectToWebSocket,
9
+ convertUint8ArrayToBase64,
10
+ convertBase64ToUint8Array,
11
+ lazySchema,
12
+ parseProviderOptions,
13
+ safeParseJSON,
14
+ safeValidateTypes,
15
+ toWebSocketUrl,
16
+ waitForWebSocketBufferDrain,
17
+ zodSchema,
18
+ type WebSocketConnection,
19
+ type WebSocketConstructor,
20
+ } from '@ai-sdk/provider-utils';
21
+ import { z } from 'zod/v4';
22
+ import { mistralTranscriptionModelOptions } from './mistral-transcription-model-options';
23
+
24
+ export async function streamMistralTranscription({
25
+ modelId,
26
+ baseURL,
27
+ headers,
28
+ webSocket,
29
+ currentDate,
30
+ ...options
31
+ }: TranscriptionModelV4StreamOptions & {
32
+ modelId: string;
33
+ baseURL: string;
34
+ webSocket?: WebSocketConstructor;
35
+ currentDate: Date;
36
+ }) {
37
+ const mistralOptions = await parseProviderOptions({
38
+ provider: 'mistral',
39
+ providerOptions: options.providerOptions,
40
+ schema: mistralTranscriptionModelOptions,
41
+ });
42
+ const { type, rate = 16000 } = options.inputAudioFormat;
43
+ if (type !== 'audio/pcm' || !Number.isInteger(rate) || rate <= 0) {
44
+ throw new InvalidArgumentError({
45
+ argument: 'inputAudioFormat',
46
+ message:
47
+ 'Mistral realtime transcription requires audio/pcm (mono, signed 16-bit little-endian) with a positive integer sample rate.',
48
+ });
49
+ }
50
+
51
+ const warnings: SharedV4Warning[] = [];
52
+ for (const option of [
53
+ 'returnLanguage',
54
+ 'temperature',
55
+ 'timestampGranularities',
56
+ ] as const) {
57
+ if (mistralOptions?.[option] != null) {
58
+ warnings.push({
59
+ type: 'unsupported',
60
+ feature: `providerOptions.mistral.${option}`,
61
+ details: 'This option is not supported for realtime transcription.',
62
+ });
63
+ }
64
+ }
65
+
66
+ const turnDetection = mistralOptions?.turnDetection;
67
+ const session = {
68
+ audio_format: { encoding: 'pcm_s16le', sample_rate: rate },
69
+ target_streaming_delay_ms: mistralOptions?.targetStreamingDelayMs,
70
+ language: mistralOptions?.language,
71
+ context_bias: mistralOptions?.contextBias,
72
+ diarize: mistralOptions?.diarize,
73
+ speaker_references: mistralOptions?.speakerReferences,
74
+ turn_detection:
75
+ turnDetection == null
76
+ ? undefined
77
+ : {
78
+ start_threshold: turnDetection.startThreshold,
79
+ eager_end_threshold: turnDetection.eagerEndThreshold,
80
+ end_threshold: turnDetection.endThreshold,
81
+ min_silence_ms: turnDetection.minSilenceMs,
82
+ end_timeout_ms: turnDetection.endTimeoutMs,
83
+ },
84
+ };
85
+ const url = toWebSocketUrl(`${baseURL}/audio/transcriptions/realtime`);
86
+ url.searchParams.set('model', modelId);
87
+ let finished = false;
88
+ let cleanup: () => void = () => {};
89
+
90
+ return {
91
+ request: { body: url.toString() },
92
+ response: { timestamp: currentDate, modelId },
93
+ stream: new ReadableStream<TranscriptionModelV4StreamPart>({
94
+ start(controller) {
95
+ let connection: WebSocketConnection | undefined;
96
+ let reader:
97
+ | ReadableStreamDefaultReader<Uint8Array | string>
98
+ | undefined;
99
+ let configured = false;
100
+ let sending = false;
101
+ const stop = new AbortController();
102
+
103
+ cleanup = () => {
104
+ stop.abort();
105
+ void (
106
+ reader != null ? reader.cancel() : options.audio.cancel()
107
+ ).catch(() => {});
108
+ connection?.close(1000);
109
+ };
110
+ const fail = (error: unknown) => {
111
+ if (finished) return;
112
+ finished = true;
113
+ cleanup();
114
+ controller.error(error);
115
+ };
116
+ const sendAudio = async () => {
117
+ const socket = connection!.socket!;
118
+ reader = options.audio.getReader();
119
+ try {
120
+ while (true) {
121
+ if (finished) break;
122
+ const { done, value } = await reader.read();
123
+ if (finished || done) break;
124
+ const bytes =
125
+ typeof value === 'string'
126
+ ? convertBase64ToUint8Array(value)
127
+ : value;
128
+ // Keep each message below Mistral's 256 KiB limit, including
129
+ // base64 expansion, even when the caller supplies a large chunk.
130
+ for (let offset = 0; offset < bytes.length; offset += 64 * 1024) {
131
+ if (finished) break;
132
+ socket.send(
133
+ JSON.stringify({
134
+ type: 'input_audio.append',
135
+ audio: convertUint8ArrayToBase64(
136
+ bytes.subarray(offset, offset + 64 * 1024),
137
+ ),
138
+ }),
139
+ );
140
+ await waitForWebSocketBufferDrain(socket, {
141
+ abortSignal: stop.signal,
142
+ });
143
+ }
144
+ }
145
+ if (!finished) {
146
+ socket.send(JSON.stringify({ type: 'input_audio.end' }));
147
+ }
148
+ } finally {
149
+ reader.releaseLock();
150
+ reader = undefined;
151
+ }
152
+ };
153
+
154
+ controller.enqueue({ type: 'stream-start', warnings });
155
+ connection = connectToWebSocket({
156
+ url,
157
+ headers,
158
+ webSocket,
159
+ abortSignal: options.abortSignal,
160
+ onAbort: fail,
161
+ onProcessingError: fail,
162
+ onMessageText: async text => {
163
+ if (finished) return;
164
+ const parsed = await safeParseJSON({
165
+ text,
166
+ schema: eventEnvelopeSchema,
167
+ });
168
+ if (finished) return;
169
+ if (!parsed.success) throw parsed.error;
170
+ const raw = parsed.value;
171
+ if (options.includeRawChunks) {
172
+ controller.enqueue({ type: 'raw', rawValue: raw });
173
+ }
174
+ // Unknown events (including turn events) remain available as raw
175
+ // chunks without making the adapter depend on their schema.
176
+ if (!handledEvents.has(raw.type)) return;
177
+ const validated = await safeValidateTypes({
178
+ value: raw,
179
+ schema: transcriptionEventSchema,
180
+ });
181
+ if (finished) return;
182
+ if (!validated.success) throw validated.error;
183
+ const event = validated.value;
184
+ switch (event.type) {
185
+ case 'session.created':
186
+ if (configured) break;
187
+ configured = true;
188
+ connection!.socket!.send(
189
+ JSON.stringify({ type: 'session.update', session }),
190
+ );
191
+ break;
192
+ case 'session.updated':
193
+ if (!configured || sending) break;
194
+ sending = true;
195
+ void sendAudio().catch(fail);
196
+ break;
197
+ case 'transcription.text.delta':
198
+ controller.enqueue({
199
+ type: 'transcript-delta',
200
+ delta: event.text,
201
+ });
202
+ break;
203
+ case 'transcription.segment':
204
+ controller.enqueue({
205
+ type: 'transcript-final',
206
+ text: event.text,
207
+ startSecond: event.start ?? undefined,
208
+ endSecond: event.end ?? undefined,
209
+ ...(event.speaker_id != null && {
210
+ providerMetadata: {
211
+ mistral: { speakerId: event.speaker_id },
212
+ },
213
+ }),
214
+ });
215
+ break;
216
+ case 'transcription.done': {
217
+ const segments = event.segments ?? [];
218
+ controller.enqueue({
219
+ type: 'response-metadata',
220
+ modelId: event.model ?? modelId,
221
+ body: raw,
222
+ });
223
+ controller.enqueue({
224
+ type: 'finish',
225
+ text: event.text,
226
+ segments: segments.flatMap(segment =>
227
+ segment.start == null || segment.end == null
228
+ ? []
229
+ : [
230
+ {
231
+ text: segment.text,
232
+ startSecond: segment.start,
233
+ endSecond: segment.end,
234
+ },
235
+ ],
236
+ ),
237
+ language: event.language ?? undefined,
238
+ durationInSeconds:
239
+ typeof event.usage?.prompt_audio_seconds === 'number'
240
+ ? event.usage.prompt_audio_seconds
241
+ : undefined,
242
+ usage: event.usage ?? undefined,
243
+ providerMetadata: {
244
+ mistral: {
245
+ ...(event.usage != null && { usage: event.usage }),
246
+ segments: segments.map(segment => ({
247
+ text: segment.text,
248
+ ...(segment.start != null && {
249
+ startSecond: segment.start,
250
+ }),
251
+ ...(segment.end != null && { endSecond: segment.end }),
252
+ ...(segment.speaker_id != null && {
253
+ speakerId: segment.speaker_id,
254
+ }),
255
+ })),
256
+ },
257
+ },
258
+ });
259
+ finished = true;
260
+ controller.close();
261
+ cleanup();
262
+ break;
263
+ }
264
+ case 'error':
265
+ fail(new Error(event.error.message));
266
+ break;
267
+ }
268
+ },
269
+ onSocketError: () =>
270
+ fail(
271
+ new Error(
272
+ 'Mistral realtime transcription WebSocket error.' +
273
+ (webSocket == null
274
+ ? ' Pass a header-capable WebSocket implementation (e.g. ws) to createMistral({ webSocket }) to send the Authorization header.'
275
+ : ''),
276
+ ),
277
+ ),
278
+ onClose: ({ code, reason }) =>
279
+ fail(
280
+ new Error(
281
+ `Mistral realtime transcription connection closed before transcription.done (code: ${code ?? 'unknown'}${reason ? `, reason: ${reason}` : ''}).`,
282
+ ),
283
+ ),
284
+ });
285
+ // A constructor failure or an already-aborted signal can finish
286
+ // synchronously, before the connection has been assigned.
287
+ if (finished) connection.close();
288
+ },
289
+ cancel() {
290
+ if (finished) return;
291
+ finished = true;
292
+ cleanup();
293
+ },
294
+ }),
295
+ };
296
+ }
297
+
298
+ const handledEvents = new Set([
299
+ 'session.created',
300
+ 'session.updated',
301
+ 'transcription.text.delta',
302
+ 'transcription.segment',
303
+ 'transcription.done',
304
+ 'error',
305
+ ]);
306
+ const eventEnvelopeSchema = lazySchema(() =>
307
+ zodSchema(z.looseObject({ type: z.string() })),
308
+ );
309
+ const transcriptionEventSchema = lazySchema(() => {
310
+ const segment = {
311
+ text: z.string(),
312
+ start: z.number().nullish(),
313
+ end: z.number().nullish(),
314
+ speaker_id: z.string().nullish(),
315
+ };
316
+ return zodSchema(
317
+ z.discriminatedUnion('type', [
318
+ z.object({ type: z.literal('session.created') }),
319
+ z.object({ type: z.literal('session.updated') }),
320
+ z.object({
321
+ type: z.literal('transcription.text.delta'),
322
+ text: z.string(),
323
+ }),
324
+ z.object({ type: z.literal('transcription.segment'), ...segment }),
325
+ z.object({
326
+ type: z.literal('transcription.done'),
327
+ text: z.string(),
328
+ model: z.string().nullish(),
329
+ language: z.string().nullish(),
330
+ segments: z.array(z.object(segment)).nullish(),
331
+ usage: z.record(z.string(), z.json()).nullish(),
332
+ }),
333
+ z.object({
334
+ type: z.literal('error'),
335
+ error: z.object({ message: z.string() }),
336
+ }),
337
+ ]),
338
+ );
339
+ });
@@ -0,0 +1,121 @@
1
+ import {
2
+ InvalidArgumentError,
3
+ type Experimental_RealtimeModelV4SessionConfig as RealtimeModelV4SessionConfig,
4
+ } from '@ai-sdk/provider';
5
+ import {
6
+ resolve,
7
+ type Resolvable,
8
+ createJsonResponseHandler,
9
+ deleteFromApi,
10
+ lazySchema,
11
+ postJsonToApi,
12
+ zodSchema,
13
+ type FetchFunction,
14
+ } from '@ai-sdk/provider-utils';
15
+ import { z } from 'zod/v4';
16
+ import type { MistralChatModelId } from '../mistral-chat-language-model-options';
17
+ import { mistralFailedResponseHandler } from '../mistral-error';
18
+ import { MistralRealtimeModel } from './mistral-realtime-model';
19
+ import { buildMistralRealtimeSessionConfig } from './mistral-realtime-model-options';
20
+
21
+ /** Credentials for one browser voice conversation. */
22
+ export type MistralRealtimeSession = {
23
+ id: string;
24
+ participantToken: string;
25
+ serverUrl: string;
26
+ };
27
+
28
+ export interface MistralRealtimeFactory {
29
+ (modelId: MistralChatModelId): MistralRealtimeModel;
30
+
31
+ /** Server-only: create a voice session using the Mistral API key. */
32
+ createSession(options: {
33
+ model: MistralChatModelId;
34
+ sessionConfig?: RealtimeModelV4SessionConfig;
35
+ abortSignal?: AbortSignal;
36
+ }): Promise<MistralRealtimeSession>;
37
+
38
+ /** Server-only: release a voice session after the browser disconnects. */
39
+ closeSession(options: {
40
+ sessionId: string;
41
+ abortSignal?: AbortSignal;
42
+ }): Promise<void>;
43
+ }
44
+
45
+ export function createMistralRealtimeFactory(config: {
46
+ baseURL: string;
47
+ headers: Resolvable<Record<string, string | undefined>>;
48
+ fetch?: FetchFunction;
49
+ }): MistralRealtimeFactory {
50
+ return Object.assign(
51
+ (modelId: MistralChatModelId) => new MistralRealtimeModel(modelId),
52
+ {
53
+ async createSession({
54
+ model,
55
+ sessionConfig = {},
56
+ abortSignal,
57
+ }: Parameters<MistralRealtimeFactory['createSession']>[0]) {
58
+ if (model.trim().length === 0) {
59
+ throw new InvalidArgumentError({
60
+ argument: 'model',
61
+ message: 'Mistral voice sessions require a model ID.',
62
+ });
63
+ }
64
+ const body = await buildMistralRealtimeSessionConfig(sessionConfig, {
65
+ modelId: model,
66
+ });
67
+ const { value } = await postJsonToApi({
68
+ url: `${config.baseURL}/audio/sessions`,
69
+ headers: await resolve(config.headers),
70
+ body,
71
+ failedResponseHandler: mistralFailedResponseHandler,
72
+ successfulResponseHandler: createJsonResponseHandler(sessionSchema),
73
+ abortSignal,
74
+ fetch: config.fetch,
75
+ });
76
+ return {
77
+ id: value.id,
78
+ participantToken: value.participant_token,
79
+ serverUrl: value.server_url,
80
+ };
81
+ },
82
+
83
+ async closeSession({
84
+ sessionId,
85
+ abortSignal,
86
+ }: Parameters<MistralRealtimeFactory['closeSession']>[0]) {
87
+ if (
88
+ sessionId.trim().length === 0 ||
89
+ sessionId === '.' ||
90
+ sessionId === '..'
91
+ ) {
92
+ throw new InvalidArgumentError({
93
+ argument: 'sessionId',
94
+ message: 'Mistral voice sessions require a valid session ID.',
95
+ });
96
+ }
97
+ await deleteFromApi({
98
+ url: `${config.baseURL}/audio/sessions/${encodeURIComponent(sessionId)}`,
99
+ headers: await resolve(config.headers),
100
+ failedResponseHandler: mistralFailedResponseHandler,
101
+ successfulResponseHandler: async ({ response }) => {
102
+ await response.body?.cancel();
103
+ return { value: undefined };
104
+ },
105
+ abortSignal,
106
+ fetch: config.fetch,
107
+ });
108
+ },
109
+ },
110
+ );
111
+ }
112
+
113
+ const sessionSchema = lazySchema(() =>
114
+ zodSchema(
115
+ z.object({
116
+ id: z.string().min(1),
117
+ participant_token: z.string().min(1),
118
+ server_url: z.string().min(1),
119
+ }),
120
+ ),
121
+ );
@@ -0,0 +1,199 @@
1
+ import {
2
+ InvalidArgumentError,
3
+ UnsupportedFunctionalityError,
4
+ type Experimental_RealtimeModelV4SessionConfig as RealtimeModelV4SessionConfig,
5
+ } from '@ai-sdk/provider';
6
+ import {
7
+ lazySchema,
8
+ parseProviderOptions,
9
+ zodSchema,
10
+ type InferSchema,
11
+ } from '@ai-sdk/provider-utils';
12
+ import { z } from 'zod/v4';
13
+
14
+ export const mistralRealtimeModelOptions = lazySchema(() =>
15
+ zodSchema(
16
+ z.strictObject({
17
+ /** Speech recognition settings for the managed voice agent. */
18
+ stt: z
19
+ .strictObject({
20
+ model: z.string().min(1).optional(),
21
+ language: z.string().min(1).optional(),
22
+ contextBias: z.array(z.string().min(1)).optional(),
23
+ targetStreamingDelayMs: z.number().int().min(80).max(1200).optional(),
24
+ turnDetection: z
25
+ .strictObject({
26
+ startThreshold: z.number().min(0).max(1).optional(),
27
+ eagerEndThreshold: z.number().min(0).max(1).optional(),
28
+ endThreshold: z.number().min(0).max(1).optional(),
29
+ minSilenceMs: z.number().int().nonnegative().optional(),
30
+ endTimeoutMs: z.number().int().nonnegative().optional(),
31
+ })
32
+ .optional(),
33
+ })
34
+ .optional(),
35
+ /** Speech synthesis settings. `sessionConfig.voice` overrides voiceId. */
36
+ tts: z
37
+ .strictObject({
38
+ model: z.string().min(1).optional(),
39
+ voiceId: z.string().min(1).optional(),
40
+ phonemeHints: z
41
+ .record(z.string(), z.array(z.string().min(1)).min(1))
42
+ .optional(),
43
+ })
44
+ .optional(),
45
+ /** Interruptions and reminders during periods of silence. */
46
+ turn: z
47
+ .strictObject({
48
+ allowInterruptions: z.boolean().optional(),
49
+ inactivity: z
50
+ .strictObject({
51
+ timeoutMs: z.number().int().nonnegative().optional(),
52
+ maxReminders: z.number().int().nonnegative().optional(),
53
+ messages: z.array(z.string()).optional(),
54
+ })
55
+ .optional(),
56
+ })
57
+ .optional(),
58
+ /** Text spoken when the session connects. */
59
+ welcomeMessage: z.string().optional(),
60
+ /** Saved agent whose configuration is overridden for this session. */
61
+ agentId: z.string().min(1).optional(),
62
+ /** Version of the saved agent. Omit to use its latest version. */
63
+ agentVersion: z.number().int().nonnegative().optional(),
64
+ }),
65
+ ),
66
+ );
67
+
68
+ export type MistralRealtimeModelOptions = InferSchema<
69
+ typeof mistralRealtimeModelOptions
70
+ >;
71
+
72
+ /** Builds the REST configuration or the subset accepted by session.update. */
73
+ export async function buildMistralRealtimeSessionConfig(
74
+ config: RealtimeModelV4SessionConfig,
75
+ { modelId, update = false }: { modelId?: string; update?: boolean } = {},
76
+ ): Promise<Record<string, unknown>> {
77
+ const allowed = new Set([
78
+ 'instructions',
79
+ 'tools',
80
+ 'providerOptions',
81
+ ...(!update
82
+ ? [
83
+ 'voice',
84
+ 'inputAudioTranscription',
85
+ 'outputAudioTranscription',
86
+ 'outputModalities',
87
+ ]
88
+ : []),
89
+ ]);
90
+ for (const [key, value] of Object.entries(config)) {
91
+ if (value !== undefined && !allowed.has(key)) unsupported(key, update);
92
+ }
93
+ if (config.inputAudioTranscription?.prompt != null) {
94
+ unsupported('inputAudioTranscription.prompt', update);
95
+ }
96
+ if (
97
+ config.outputAudioTranscription != null &&
98
+ Object.values(config.outputAudioTranscription).some(value => value != null)
99
+ ) {
100
+ unsupported('outputAudioTranscription settings', update);
101
+ }
102
+ if (
103
+ config.outputModalities != null &&
104
+ (!config.outputModalities.includes('audio') ||
105
+ config.outputModalities.some(
106
+ value => value !== 'audio' && value !== 'text',
107
+ ))
108
+ ) {
109
+ unsupported('outputModalities without audio', update);
110
+ }
111
+
112
+ const options = await parseProviderOptions({
113
+ provider: 'mistral',
114
+ providerOptions: config.providerOptions,
115
+ schema: mistralRealtimeModelOptions,
116
+ });
117
+ if (update && options != null) {
118
+ for (const [key, value] of Object.entries(options)) {
119
+ if (value !== undefined && key !== 'turn') {
120
+ unsupported(`providerOptions.mistral.${key}`, true);
121
+ }
122
+ }
123
+ }
124
+ if (options?.agentVersion != null && options.agentId == null) {
125
+ throw new InvalidArgumentError({
126
+ argument: 'providerOptions.mistral.agentVersion',
127
+ message: 'Mistral agentVersion requires agentId.',
128
+ });
129
+ }
130
+
131
+ const stt = options?.stt;
132
+ const turnDetection = stt?.turnDetection;
133
+ const tts = options?.tts;
134
+ const turn = options?.turn;
135
+ const inactivity = turn?.inactivity;
136
+ return {
137
+ ...(modelId != null && { llm: { model: modelId } }),
138
+ ...(config.instructions != null && { instructions: config.instructions }),
139
+ ...(config.tools != null && {
140
+ tools: config.tools.map(tool => ({
141
+ type: 'function',
142
+ function: {
143
+ name: tool.name,
144
+ ...(tool.description != null && { description: tool.description }),
145
+ parameters: tool.parameters,
146
+ },
147
+ })),
148
+ }),
149
+ ...((stt != null || config.inputAudioTranscription != null) && {
150
+ stt: {
151
+ model: config.inputAudioTranscription?.model ?? stt?.model,
152
+ language: config.inputAudioTranscription?.language ?? stt?.language,
153
+ context_bias: stt?.contextBias,
154
+ target_streaming_delay_ms: stt?.targetStreamingDelayMs,
155
+ ...(turnDetection != null && {
156
+ turn_detection: {
157
+ start_threshold: turnDetection.startThreshold,
158
+ eager_end_threshold: turnDetection.eagerEndThreshold,
159
+ end_threshold: turnDetection.endThreshold,
160
+ min_silence_ms: turnDetection.minSilenceMs,
161
+ end_timeout_ms: turnDetection.endTimeoutMs,
162
+ },
163
+ }),
164
+ },
165
+ }),
166
+ ...((tts != null || config.voice != null) && {
167
+ tts: {
168
+ model: tts?.model,
169
+ voice_id: config.voice ?? tts?.voiceId,
170
+ phoneme_hints: tts?.phonemeHints,
171
+ },
172
+ }),
173
+ ...(turn != null && {
174
+ turn: {
175
+ allow_interruptions: turn.allowInterruptions,
176
+ ...(inactivity != null && {
177
+ inactivity: {
178
+ timeout_ms: inactivity.timeoutMs,
179
+ max_reminders: inactivity.maxReminders,
180
+ messages: inactivity.messages,
181
+ },
182
+ }),
183
+ },
184
+ }),
185
+ ...(options?.welcomeMessage != null && {
186
+ welcome_message: options.welcomeMessage,
187
+ }),
188
+ ...(options?.agentId != null && { agent_id: options.agentId }),
189
+ ...(options?.agentVersion != null && {
190
+ agent_version: options.agentVersion,
191
+ }),
192
+ };
193
+ }
194
+
195
+ function unsupported(setting: string, update: boolean): never {
196
+ throw new UnsupportedFunctionalityError({
197
+ functionality: `Mistral voice agent ${update ? 'live update of' : 'setting'} ${setting}`,
198
+ });
199
+ }
@@ -0,0 +1,46 @@
1
+ import {
2
+ UnsupportedFunctionalityError,
3
+ type Experimental_RealtimeModelV4 as RealtimeModelV4,
4
+ type Experimental_RealtimeModelV4ClientEvent as RealtimeModelV4ClientEvent,
5
+ type Experimental_RealtimeModelV4SessionConfig as RealtimeModelV4SessionConfig,
6
+ type Experimental_RealtimeModelV4TransportOptions as RealtimeModelV4TransportOptions,
7
+ } from '@ai-sdk/provider';
8
+ import type { MistralChatModelId } from '../mistral-chat-language-model-options';
9
+ import { buildMistralRealtimeSessionConfig } from './mistral-realtime-model-options';
10
+ import {
11
+ MistralRealtimeTransport,
12
+ parseMistralRealtimeEvent,
13
+ } from './mistral-realtime-transport';
14
+
15
+ /** A managed Mistral voice agent with provider-owned LiveKit transport. */
16
+ export class MistralRealtimeModel implements RealtimeModelV4 {
17
+ readonly specificationVersion = 'v4';
18
+ readonly provider = 'mistral.realtime';
19
+ readonly capabilities = {
20
+ conversation: 'turn-based',
21
+ transports: ['webrtc'],
22
+ connections: ['provider'],
23
+ startup: 'session-update',
24
+ finalization: 'transport-close',
25
+ } as const;
26
+
27
+ constructor(readonly modelId: MistralChatModelId) {}
28
+
29
+ createTransport(options: RealtimeModelV4TransportOptions) {
30
+ return new MistralRealtimeTransport(options);
31
+ }
32
+
33
+ parseServerEvent(raw: unknown) {
34
+ return parseMistralRealtimeEvent(raw);
35
+ }
36
+
37
+ serializeClientEvent(event: RealtimeModelV4ClientEvent): never {
38
+ throw new UnsupportedFunctionalityError({
39
+ functionality: `Mistral voice agent ${event.type} outside its provider transport`,
40
+ });
41
+ }
42
+
43
+ buildSessionConfig(config: RealtimeModelV4SessionConfig) {
44
+ return buildMistralRealtimeSessionConfig(config, { modelId: this.modelId });
45
+ }
46
+ }