@ai-sdk/gateway 4.0.151 → 4.0.152

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.
@@ -661,6 +661,72 @@ the short-lived setup response from `getToken()`.
661
661
  should stay compact (under an 8 KiB safe header budget).
662
662
  </Note>
663
663
 
664
+ ### Live Models
665
+
666
+ Live models such as `openai/gpt-live-1.1` hold one continuous conversation: a
667
+ `session-start` event opens the session, PCM16 audio streams in both directions,
668
+ and `session-close` ends it with final usage. `gateway.experimental_realtime()`
669
+ returns a Live model for known Live model IDs. It connects to the Gateway Live
670
+ route and speaks the normalized Live protocol. Pass `{ api: 'live' }` for a Live
671
+ model ID the SDK does not know yet, or `{ api: 'realtime' }` to force the
672
+ realtime route.
673
+
674
+ ```ts
675
+ import { gateway } from '@ai-sdk/gateway';
676
+
677
+ const live = gateway.experimental_realtime('openai/gpt-live-1.1');
678
+ const newerLive = gateway.experimental_realtime('openai/gpt-live-2', {
679
+ api: 'live',
680
+ });
681
+ ```
682
+
683
+ `getToken()` mints a client secret bound to the Live route for Live models, so
684
+ the browser can connect straight to the Gateway:
685
+
686
+ ```ts filename='app/api/live/setup/route.ts'
687
+ import { gateway } from '@ai-sdk/gateway';
688
+
689
+ export async function POST() {
690
+ const token = await gateway.experimental_realtime.getToken({
691
+ model: 'openai/gpt-live-1.1',
692
+ });
693
+
694
+ return Response.json(token);
695
+ }
696
+ ```
697
+
698
+ ```tsx filename='app/live/page.tsx'
699
+ 'use client';
700
+
701
+ import { gateway } from '@ai-sdk/gateway';
702
+ import { experimental_useRealtime } from '@ai-sdk/react';
703
+
704
+ const model = gateway.experimental_realtime('openai/gpt-live-1.1');
705
+
706
+ export default function LivePage() {
707
+ const live = experimental_useRealtime({
708
+ model,
709
+ api: { token: '/api/live/setup' },
710
+ sessionConfig: { instructions: 'Keep replies brief.' },
711
+ });
712
+
713
+ // live.connect(), live.close(), live.session?.usage, ...
714
+ }
715
+ ```
716
+
717
+ Live sessions accept `instructions`, `voice`, `inputAudioFormat`,
718
+ `outputAudioFormat` and `providerOptions` (`gateway`, and `openai` with
719
+ `delegation`, `input`, `store` and `voice`). Audio is `audio/pcm` at 16000 or
720
+ 24000 Hz, with the same format in both directions. Live uses client delegation:
721
+ your application submits context with `context-append` instead of the
722
+ turn-based tool loop, and `sendTextMessage()` and `addToolOutput()` are not
723
+ available. Live model IDs must be fully qualified (`creator/model-name`).
724
+
725
+ <Note>
726
+ Live through the Gateway provider uses WebSocket only. For WebRTC, use
727
+ `@ai-sdk/openai` directly. Responses delegation is not supported.
728
+ </Note>
729
+
664
730
  ### Provider Options
665
731
 
666
732
  Gateway [provider options](#gateway-provider-options) — `tags`, `user`, `byok`, compliance flags, and so on — are set under `providerOptions.gateway` in the **session configuration**, mirroring how they ride the request body on the non-realtime routes. Include them in the session configuration you send to the Gateway, and the Gateway applies them server-side:
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ai-sdk/gateway",
3
3
  "private": false,
4
- "version": "4.0.151",
4
+ "version": "4.0.152",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
7
7
  "sideEffects": false,
@@ -288,7 +288,6 @@ export const gatewayModelIds = {
288
288
  'spacexai/grok-4.5',
289
289
  'spacexai/grok-4.6',
290
290
  'spacexai/grok-4.7',
291
- 'spacexai/grok-build-0.1',
292
291
  'stealth/glyph-cluster',
293
292
  'stepfun/step-3.7-flash',
294
293
  'stepfun/step-5-preview',
@@ -368,6 +367,7 @@ export const gatewayModelIds = {
368
367
  'liquid/d1.2-ultra',
369
368
  'microsoft/decision-1.1',
370
369
  'microsoft/microsoft-decision-1',
370
+ 'modaic/mo',
371
371
  'nace-ai/drex-max-finance',
372
372
  'nace-ai/drex-max-v1.1',
373
373
  'nace-ai/drex-v2.0',
@@ -382,7 +382,7 @@ export const gatewayModelIds = {
382
382
  'typesafe-ai/jev-1.13.0',
383
383
  'typesafe-ai/jev-1.14.0',
384
384
  ],
385
- extraction: [],
385
+ extraction: ['scaledown/extract-1'],
386
386
  image: [
387
387
  'bfl/flux-2-flex',
388
388
  'bfl/flux-2-klein-4b',
@@ -415,7 +415,6 @@ export const gatewayModelIds = {
415
415
  'openai/gpt-image-2.5-sunburst',
416
416
  'openai/gpt-image-2.6-flare',
417
417
  'openai/gpt-image-2.6-sunburst',
418
- 'prodia/flux-fast-schnell',
419
418
  'recraft/recraft-v2',
420
419
  'recraft/recraft-v3',
421
420
  'recraft/recraft-v4',
@@ -474,6 +473,7 @@ export const gatewayModelIds = {
474
473
  'google/gemini-3.8-live',
475
474
  'google/gemini-3.8-live-extended-thinking',
476
475
  'openai/gpt-live-1',
476
+ 'openai/gpt-live-1.1',
477
477
  'openai/gpt-realtime-1.5',
478
478
  'openai/gpt-realtime-2',
479
479
  'openai/gpt-realtime-2.1',
@@ -48,6 +48,7 @@ import {
48
48
  GatewayTranscriptionModel,
49
49
  toGatewayTranscriptionUrl,
50
50
  } from './gateway-transcription-model';
51
+ import { GatewayRealtimeModelLive } from './gateway-realtime-model-live';
51
52
  import { GatewayRealtimeModel } from './gateway-realtime-model';
52
53
  import type { GatewayEmbeddingModelId } from './gateway-embedding-model-settings';
53
54
  import type { GatewayDecisionModelId } from './gateway-decision-model-settings';
@@ -56,12 +57,18 @@ import type { GatewayImageModelId } from './gateway-image-model-settings';
56
57
  import type { GatewayRerankingModelId } from './gateway-reranking-model-settings';
57
58
  import type { GatewaySpeechModelId } from './gateway-speech-model-settings';
58
59
  import type { GatewayTranscriptionModelId } from './gateway-transcription-model-settings';
59
- import type { GatewayRealtimeModelId } from './gateway-realtime-model-settings';
60
+ import {
61
+ gatewayLiveModelIds,
62
+ type GatewayKnownLiveModelId,
63
+ type GatewayRealtimeModelId,
64
+ type GatewayRealtimeOptions,
65
+ } from './gateway-realtime-model-settings';
60
66
  import type { GatewayVideoModelId } from './gateway-video-model-settings';
61
67
  import { gatewayTools } from './gateway-tools';
62
68
  import { getVercelOidcToken, getVercelRequestId } from './vercel-environment';
63
69
  import type { GatewayModelId } from './gateway-language-model-settings';
64
70
  import {
71
+ InvalidArgumentError,
65
72
  LoadAPIKeyError,
66
73
  type EmbeddingModelV4,
67
74
  type Experimental_BatchV4 as BatchV4,
@@ -75,6 +82,8 @@ import {
75
82
  type Experimental_StreamingSpeechModelV4,
76
83
  type Experimental_RealtimeFactoryV4 as RealtimeFactoryV4,
77
84
  type Experimental_RealtimeFactoryV4GetTokenOptions as RealtimeFactoryV4GetTokenOptions,
85
+ type Experimental_RealtimeFactoryV4GetTokenResult as RealtimeFactoryV4GetTokenResult,
86
+ type Experimental_RealtimeModelV4 as RealtimeModelV4,
78
87
  type ProviderV4,
79
88
  type LanguageModelV4,
80
89
  } from '@ai-sdk/provider';
@@ -223,9 +232,10 @@ export interface GatewayProvider extends ProviderV4 {
223
232
 
224
233
  /**
225
234
  * Creates an experimental realtime model for bidirectional audio/text
226
- * communication over WebSocket, normalized through the AI Gateway.
235
+ * communication over WebSocket, normalized through the AI Gateway. Known
236
+ * Live model IDs return a continuous Live model; `{ api }` overrides routing.
227
237
  */
228
- experimental_realtime: RealtimeFactoryV4;
238
+ experimental_realtime: GatewayRealtimeFactory;
229
239
 
230
240
  /**
231
241
  * Experimental streaming-transcription entry point. Callable like
@@ -249,6 +259,28 @@ export interface GatewayProvider extends ProviderV4 {
249
259
  tools: typeof gatewayTools;
250
260
  }
251
261
 
262
+ /**
263
+ * Realtime factory: returns a turn-based realtime model or, for Live model IDs
264
+ * or `{ api: 'live' }`, a continuous Live model. `getToken` mints a client
265
+ * secret bound to the matching Gateway WebSocket route.
266
+ */
267
+ export interface GatewayRealtimeFactory extends RealtimeFactoryV4 {
268
+ (modelId: string, options: { api: 'live' }): GatewayRealtimeModelLive;
269
+ (modelId: string, options: { api: 'realtime' }): GatewayRealtimeModel;
270
+ (
271
+ modelId: GatewayKnownLiveModelId,
272
+ options?: { api?: undefined },
273
+ ): GatewayRealtimeModelLive;
274
+ (
275
+ modelId: GatewayRealtimeModelId,
276
+ options?: GatewayRealtimeOptions,
277
+ ): RealtimeModelV4;
278
+
279
+ getToken(
280
+ options: RealtimeFactoryV4GetTokenOptions & GatewayRealtimeOptions,
281
+ ): Promise<RealtimeFactoryV4GetTokenResult>;
282
+ }
283
+
252
284
  export type GatewayTranscriptionFactoryGetTokenOptions = {
253
285
  model: GatewayTranscriptionModelId;
254
286
  /** Token lifetime in seconds. Gateway default is 60s (max 300s). */
@@ -461,7 +493,7 @@ export function createGateway(
461
493
  const mintClientSecret = async (params: {
462
494
  modelId: string;
463
495
  expiresAfterSeconds?: number;
464
- routeKind?: 'speech' | 'transcription';
496
+ routeKind?: 'live' | 'speech' | 'transcription';
465
497
  }): Promise<{ token: string; expiresAt?: number }> => {
466
498
  assertGatewayClientSecretServerEnvironment();
467
499
  const auth = await getRealtimeAuthToken();
@@ -792,20 +824,36 @@ export function createGateway(
792
824
  // needs to drive the transport with a server-minted client secret. The
793
825
  // server-only boundary is enforced on minting itself (`mintClientSecret`),
794
826
  // which requires the Gateway credential.
795
- const createRealtimeModel = (modelId: GatewayRealtimeModelId) =>
796
- new GatewayRealtimeModel(modelId, {
797
- provider: 'gateway.realtime',
798
- baseURL,
799
- teamIdOrSlug: options.teamIdOrSlug,
800
- createClientSecret: mintClientSecret,
801
- getHeaders,
802
- });
827
+ const createRealtimeModel = (
828
+ modelId: GatewayRealtimeModelId,
829
+ realtimeOptions?: GatewayRealtimeOptions,
830
+ ) =>
831
+ resolveGatewayRealtimeApi(modelId, realtimeOptions) === 'live'
832
+ ? new GatewayRealtimeModelLive(modelId, {
833
+ provider: 'gateway.live',
834
+ baseURL,
835
+ teamIdOrSlug: options.teamIdOrSlug,
836
+ createClientSecret: mintClientSecret,
837
+ getHeaders,
838
+ })
839
+ : new GatewayRealtimeModel(modelId, {
840
+ provider: 'gateway.realtime',
841
+ baseURL,
842
+ teamIdOrSlug: options.teamIdOrSlug,
843
+ createClientSecret: mintClientSecret,
844
+ getHeaders,
845
+ });
803
846
  provider.experimental_realtime = Object.assign(
804
- (modelId: GatewayRealtimeModelId) => createRealtimeModel(modelId),
847
+ (
848
+ modelId: GatewayRealtimeModelId,
849
+ realtimeOptions?: GatewayRealtimeOptions,
850
+ ) => createRealtimeModel(modelId, realtimeOptions),
805
851
  {
806
- getToken: async (tokenOptions: RealtimeFactoryV4GetTokenOptions) => {
807
- const { model: modelId, ...secretOptions } = tokenOptions;
808
- const model = createRealtimeModel(modelId);
852
+ getToken: async (
853
+ tokenOptions: RealtimeFactoryV4GetTokenOptions & GatewayRealtimeOptions,
854
+ ) => {
855
+ const { model: modelId, api, ...secretOptions } = tokenOptions;
856
+ const model = createRealtimeModel(modelId, { api });
809
857
  const secret = await model.doCreateClientSecret(secretOptions);
810
858
  return {
811
859
  token: secret.token,
@@ -814,7 +862,7 @@ export function createGateway(
814
862
  };
815
863
  },
816
864
  },
817
- ) as RealtimeFactoryV4;
865
+ ) as GatewayRealtimeFactory;
818
866
 
819
867
  provider.chat = provider.languageModel;
820
868
  provider.embedding = provider.embeddingModel;
@@ -876,6 +924,25 @@ export async function getGatewayAuthToken(
876
924
  };
877
925
  }
878
926
 
927
+ function resolveGatewayRealtimeApi(
928
+ modelId: string,
929
+ options?: GatewayRealtimeOptions,
930
+ ): 'live' | 'realtime' {
931
+ const api = options?.api;
932
+ if (api !== undefined) {
933
+ if (api !== 'live' && api !== 'realtime') {
934
+ throw new InvalidArgumentError({
935
+ argument: 'api',
936
+ message: 'AI Gateway realtime api must be "live" or "realtime".',
937
+ });
938
+ }
939
+ return api;
940
+ }
941
+ return (gatewayLiveModelIds as readonly string[]).includes(modelId)
942
+ ? 'live'
943
+ : 'realtime';
944
+ }
945
+
879
946
  function assertGatewayClientSecretServerEnvironment(): void {
880
947
  if (typeof globalThis.window !== 'undefined') {
881
948
  throw new Error(
@@ -0,0 +1,385 @@
1
+ import {
2
+ InvalidArgumentError,
3
+ UnsupportedFunctionalityError,
4
+ type Experimental_RealtimeModelV4 as RealtimeModelV4,
5
+ type Experimental_RealtimeModelV4ClientEvent as RealtimeModelV4ClientEvent,
6
+ type Experimental_RealtimeModelV4ClientSecretOptions as RealtimeModelV4ClientSecretOptions,
7
+ type Experimental_RealtimeModelV4ClientSecretResult as RealtimeModelV4ClientSecretResult,
8
+ type Experimental_RealtimeModelV4ServerConnection as RealtimeModelV4ServerConnection,
9
+ type Experimental_RealtimeModelV4ServerEvent as RealtimeModelV4ServerEvent,
10
+ type Experimental_RealtimeModelV4SessionConfig as RealtimeModelV4SessionConfig,
11
+ type Experimental_RealtimeModelV4SessionIntent as RealtimeModelV4SessionIntent,
12
+ } from '@ai-sdk/provider';
13
+ import { removeUndefinedEntries } from '@ai-sdk/provider-utils';
14
+ import { getGatewayRealtimeProtocols } from './gateway-realtime-auth';
15
+
16
+ export type GatewayRealtimeModelLiveConfig = {
17
+ provider: string;
18
+ baseURL: string;
19
+ teamIdOrSlug?: string;
20
+ getHeaders: () => Promise<Record<string, string | undefined>>;
21
+ /** Mints a Live-bound client secret (`vcst_`) server-side. */
22
+ createClientSecret: (params: {
23
+ modelId: string;
24
+ expiresAfterSeconds?: number;
25
+ routeKind: 'live';
26
+ }) => PromiseLike<{ token: string; expiresAt?: number }>;
27
+ };
28
+
29
+ const supportedOpenAILiveOptions = new Set([
30
+ 'delegation',
31
+ 'input',
32
+ 'store',
33
+ 'voice',
34
+ ]);
35
+ const contextChannels = new Set(['commentary', 'instructions', 'thinking']);
36
+
37
+ const supportedSessionSettings = new Set([
38
+ 'instructions',
39
+ 'voice',
40
+ 'inputAudioFormat',
41
+ 'outputAudioFormat',
42
+ 'providerOptions',
43
+ ]);
44
+
45
+ /**
46
+ * Live model backed by the AI Gateway.
47
+ *
48
+ * Live is a continuous conversation API: one `session-start` opens the
49
+ * session, PCM audio streams in both directions, and `session-close` ends it
50
+ * with final usage. The client speaks the Gateway's normalized Live protocol
51
+ * on `/v4/ai/live-model`, and the Gateway runs the provider mapping
52
+ * server-side, so server events arrive already normalized.
53
+ */
54
+ export class GatewayRealtimeModelLive implements RealtimeModelV4 {
55
+ readonly specificationVersion = 'v4' as const;
56
+ readonly capabilities = {
57
+ conversation: 'continuous',
58
+ transports: ['websocket'],
59
+ connections: ['client-secret-websocket', 'server-websocket'],
60
+ startup: 'session-start',
61
+ finalization: 'session-close',
62
+ } as const;
63
+ readonly provider: string;
64
+ readonly modelId: string;
65
+
66
+ private readonly config: GatewayRealtimeModelLiveConfig;
67
+
68
+ constructor(modelId: string, config: GatewayRealtimeModelLiveConfig) {
69
+ this.modelId = modelId;
70
+ this.provider = config.provider;
71
+ this.config = config;
72
+ }
73
+
74
+ /**
75
+ * Mints a short-lived client secret bound to this Live model. The browser
76
+ * opens the Live WebSocket with it through the `ai-gateway-auth.<token>`
77
+ * subprotocol; the session configuration is sent later in `session-start`.
78
+ */
79
+ async doCreateClientSecret(
80
+ options?: RealtimeModelV4ClientSecretOptions,
81
+ ): Promise<RealtimeModelV4ClientSecretResult> {
82
+ const secret = await this.config.createClientSecret({
83
+ modelId: this.modelId,
84
+ routeKind: 'live',
85
+ ...(options?.expiresAfterSeconds != null && {
86
+ expiresAfterSeconds: options.expiresAfterSeconds,
87
+ }),
88
+ });
89
+ return {
90
+ token: secret.token,
91
+ url: toGatewayLiveUrl(this.config.baseURL, this.modelId),
92
+ ...(secret.expiresAt != null && { expiresAt: secret.expiresAt }),
93
+ };
94
+ }
95
+
96
+ getWebSocketConfig(options: { token: string; url: string }): {
97
+ url: string;
98
+ protocols?: string[];
99
+ } {
100
+ return {
101
+ url: options.url,
102
+ protocols: getGatewayRealtimeProtocols(options.token, {
103
+ teamIdOrSlug: this.config.teamIdOrSlug,
104
+ }),
105
+ };
106
+ }
107
+
108
+ async getServerWebSocketConfig(options?: {
109
+ intent?: RealtimeModelV4SessionIntent;
110
+ }): Promise<RealtimeModelV4ServerConnection> {
111
+ this.assertConversationIntent(options);
112
+
113
+ return {
114
+ url: toGatewayLiveUrl(this.config.baseURL, this.modelId),
115
+ headers: removeUndefinedEntries(await this.config.getHeaders()),
116
+ };
117
+ }
118
+
119
+ parseServerEvent(raw: unknown): RealtimeModelV4ServerEvent {
120
+ if (
121
+ raw == null ||
122
+ typeof raw !== 'object' ||
123
+ Array.isArray(raw) ||
124
+ typeof (raw as { type?: unknown }).type !== 'string'
125
+ ) {
126
+ return {
127
+ type: 'error',
128
+ code: 'invalid_server_event',
129
+ message: 'Invalid AI Gateway Live server event.',
130
+ raw,
131
+ };
132
+ }
133
+ // Gateway-originated errors carry no provider payload; keep the frame as `raw`.
134
+ if ((raw as { type: string }).type === 'error' && !('raw' in raw)) {
135
+ return { ...(raw as object), raw } as RealtimeModelV4ServerEvent;
136
+ }
137
+ return raw as RealtimeModelV4ServerEvent;
138
+ }
139
+
140
+ serializeClientEvent(
141
+ event: RealtimeModelV4ClientEvent,
142
+ options?: { intent?: RealtimeModelV4SessionIntent },
143
+ ): unknown {
144
+ this.assertConversationIntent(options);
145
+ const eventId =
146
+ 'eventId' in event && event.eventId != null
147
+ ? { eventId: event.eventId }
148
+ : {};
149
+
150
+ switch (event.type) {
151
+ case 'session-start':
152
+ return {
153
+ type: 'session-start',
154
+ modelId: this.modelId,
155
+ config: this.buildSessionConfig(event.config),
156
+ ...eventId,
157
+ };
158
+ case 'session-close':
159
+ case 'input-audio-mute':
160
+ case 'input-audio-unmute':
161
+ return { type: event.type, ...eventId };
162
+ case 'input-audio-append':
163
+ return { type: 'input-audio-append', audio: event.audio, ...eventId };
164
+ case 'context-append':
165
+ validateContextOptions(event.providerOptions);
166
+ return {
167
+ type: 'context-append',
168
+ content: event.content,
169
+ delegationId: event.delegationId,
170
+ ...(event.providerOptions != null && {
171
+ providerOptions: event.providerOptions,
172
+ }),
173
+ ...eventId,
174
+ };
175
+ default:
176
+ throw new UnsupportedFunctionalityError({
177
+ functionality: `AI Gateway Live client event: ${event.type}`,
178
+ });
179
+ }
180
+ }
181
+
182
+ buildSessionConfig(
183
+ config: RealtimeModelV4SessionConfig,
184
+ options?: { intent?: RealtimeModelV4SessionIntent },
185
+ ): RealtimeModelV4SessionConfig {
186
+ this.assertConversationIntent(options);
187
+ for (const [key, value] of Object.entries(config)) {
188
+ if (value != null && !supportedSessionSettings.has(key)) {
189
+ throw new UnsupportedFunctionalityError({
190
+ functionality: `AI Gateway Live session setting: ${key}`,
191
+ });
192
+ }
193
+ }
194
+
195
+ validateSessionProviderOptions(config.providerOptions);
196
+
197
+ const input = config.inputAudioFormat;
198
+ const output = config.outputAudioFormat;
199
+ for (const [argument, format] of [
200
+ ['inputAudioFormat', input],
201
+ ['outputAudioFormat', output],
202
+ ] as const) {
203
+ if (format != null && !isSupportedAudioFormat(format)) {
204
+ throw new UnsupportedFunctionalityError({
205
+ functionality: `AI Gateway Live ${argument} ${format.type} at ${format.rate ?? 'an unspecified'} Hz; use audio/pcm at 16000 or 24000 Hz, or audio/pcma or audio/pcmu at 8000 Hz`,
206
+ });
207
+ }
208
+ }
209
+ if (
210
+ input != null &&
211
+ output != null &&
212
+ (input.type !== output.type || input.rate !== output.rate)
213
+ ) {
214
+ throw new InvalidArgumentError({
215
+ argument: 'outputAudioFormat',
216
+ message:
217
+ 'AI Gateway Live requires the same input and output audio format.',
218
+ });
219
+ }
220
+
221
+ return removeUndefinedEntries(
222
+ config as Record<string, unknown>,
223
+ ) as RealtimeModelV4SessionConfig;
224
+ }
225
+
226
+ private assertConversationIntent(options?: {
227
+ intent?: RealtimeModelV4SessionIntent;
228
+ }): void {
229
+ if (options?.intent != null && options.intent !== 'conversation') {
230
+ throw new Error(
231
+ `AI Gateway Live does not support the '${options.intent}' session intent.`,
232
+ );
233
+ }
234
+ }
235
+ }
236
+
237
+ function isRecord(value: unknown): value is Record<string, unknown> {
238
+ return value != null && typeof value === 'object' && !Array.isArray(value);
239
+ }
240
+
241
+ /** Gateway options stay service-owned; OpenAI Live options are WebSocket-only. */
242
+ function validateSessionProviderOptions(providerOptions: unknown): void {
243
+ if (providerOptions == null) return;
244
+ if (!isRecord(providerOptions))
245
+ throw new InvalidArgumentError({
246
+ argument: 'providerOptions',
247
+ message: 'providerOptions must be an object.',
248
+ });
249
+ for (const [namespace, options] of Object.entries(providerOptions)) {
250
+ if (options === undefined) continue;
251
+ if (namespace !== 'gateway' && namespace !== 'openai')
252
+ throw new UnsupportedFunctionalityError({
253
+ functionality: `AI Gateway Live provider options namespace: ${namespace}`,
254
+ });
255
+ if (!isRecord(options))
256
+ throw new InvalidArgumentError({
257
+ argument: `providerOptions.${namespace}`,
258
+ message: `providerOptions.${namespace} must be an object.`,
259
+ });
260
+ }
261
+ const openai = providerOptions.openai;
262
+ if (!isRecord(openai)) return;
263
+ for (const [key, value] of Object.entries(openai)) {
264
+ if (value === undefined) continue;
265
+ if (!supportedOpenAILiveOptions.has(key))
266
+ throw new UnsupportedFunctionalityError({
267
+ functionality: `AI Gateway Live OpenAI option: ${key}`,
268
+ });
269
+ if (
270
+ key === 'delegation' &&
271
+ value !== null &&
272
+ !(hasExactKeys(value, ['type']) && value.type === 'client')
273
+ )
274
+ throw new UnsupportedFunctionalityError({
275
+ functionality:
276
+ 'AI Gateway Live delegation other than { type: "client" } or null',
277
+ });
278
+ if (!isValidOpenAILiveOption(key, value))
279
+ throw new InvalidArgumentError({
280
+ argument: `providerOptions.openai.${key}`,
281
+ message: openaiLiveOptionMessages[key],
282
+ });
283
+ }
284
+ }
285
+
286
+ const openaiLiveOptionMessages: Record<string, string> = {
287
+ delegation: 'delegation must be { type: "client" } or null.',
288
+ input:
289
+ 'input must be at most 128 messages, each { type: "message", role, content: [{ type, text }] }.',
290
+ store: 'store must be a boolean.',
291
+ voice: 'voice must be { id: string } with a nonempty id.',
292
+ };
293
+
294
+ function isValidOpenAILiveOption(key: string, value: unknown): boolean {
295
+ switch (key) {
296
+ case 'delegation':
297
+ return true;
298
+ case 'store':
299
+ return typeof value === 'boolean';
300
+ case 'voice':
301
+ return (
302
+ hasExactKeys(value, ['id']) &&
303
+ typeof value.id === 'string' &&
304
+ value.id.length > 0
305
+ );
306
+ case 'input':
307
+ return (
308
+ Array.isArray(value) &&
309
+ value.length <= 128 &&
310
+ // Array.from visits holes, which `every` would skip.
311
+ Array.from(value).every(isInputMessage)
312
+ );
313
+ default:
314
+ return false;
315
+ }
316
+ }
317
+
318
+ function isInputMessage(message: unknown): boolean {
319
+ if (
320
+ !hasExactKeys(message, ['type', 'role', 'content']) ||
321
+ message.type !== 'message' ||
322
+ !Array.isArray(message.content) ||
323
+ message.content.length !== 1
324
+ )
325
+ return false;
326
+ const [part] = message.content;
327
+ if (!hasExactKeys(part, ['type', 'text']) || typeof part.text !== 'string')
328
+ return false;
329
+ return message.role === 'assistant'
330
+ ? part.type === 'text' || part.type === 'output_text'
331
+ : (message.role === 'developer' || message.role === 'user') &&
332
+ part.type === 'input_text';
333
+ }
334
+
335
+ function hasExactKeys(
336
+ value: unknown,
337
+ keys: string[],
338
+ ): value is Record<string, unknown> {
339
+ if (!isRecord(value)) return false;
340
+ const present = Object.keys(value).filter(key => value[key] !== undefined);
341
+ return (
342
+ present.length === keys.length && keys.every(key => present.includes(key))
343
+ );
344
+ }
345
+
346
+ function validateContextOptions(providerOptions: unknown): void {
347
+ if (providerOptions == null) return;
348
+ const valid =
349
+ isRecord(providerOptions) &&
350
+ Object.entries(providerOptions).every(
351
+ ([namespace, options]) =>
352
+ options === undefined ||
353
+ (namespace === 'openai' &&
354
+ isRecord(options) &&
355
+ Object.entries(options).every(
356
+ ([key, value]) =>
357
+ value === undefined ||
358
+ (key === 'channel' &&
359
+ typeof value === 'string' &&
360
+ contextChannels.has(value)),
361
+ )),
362
+ );
363
+ if (!valid)
364
+ throw new UnsupportedFunctionalityError({
365
+ functionality:
366
+ 'AI Gateway Live context options other than openai.channel commentary, instructions, or thinking',
367
+ });
368
+ }
369
+
370
+ function isSupportedAudioFormat(format: {
371
+ type: string;
372
+ rate?: number;
373
+ }): boolean {
374
+ return format.type === 'audio/pcm'
375
+ ? format.rate === 16000 || format.rate === 24000
376
+ : (format.type === 'audio/pcma' || format.type === 'audio/pcmu') &&
377
+ format.rate === 8000;
378
+ }
379
+
380
+ /** Live WebSocket URL; the model id rides `?ai-model-id=` like the realtime route. */
381
+ function toGatewayLiveUrl(baseURL: string, modelId: string): string {
382
+ const url = new URL(`${baseURL.replace(/^http/, 'ws')}/live-model`);
383
+ url.searchParams.set('ai-model-id', modelId);
384
+ return url.toString();
385
+ }
@@ -3,3 +3,19 @@ import type { GatewayModelIds } from './gateway-model-catalog';
3
3
  export type GatewayRealtimeModelId =
4
4
  | GatewayModelIds['realtime']
5
5
  | (string & {});
6
+
7
+ /**
8
+ * Realtime model IDs that use the continuous Live API by default. Other IDs use
9
+ * the realtime API unless `{ api: 'live' }` is passed.
10
+ */
11
+ export const gatewayLiveModelIds = [
12
+ 'openai/gpt-live-1',
13
+ 'openai/gpt-live-1.1',
14
+ ] as const satisfies readonly GatewayModelIds['realtime'][];
15
+
16
+ export type GatewayKnownLiveModelId = (typeof gatewayLiveModelIds)[number];
17
+
18
+ export type GatewayRealtimeOptions = {
19
+ /** Selects the Gateway API for the model ID, including for new Live models. */
20
+ api?: 'live' | 'realtime';
21
+ };