@ai-sdk/gateway 4.0.135 → 4.0.136

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.
@@ -227,6 +227,40 @@ started, AI SDK Core exposes it as a
227
227
  Use its `type`, `code`, `statusCode`, and `isRetryable` metadata to classify
228
228
  the failure without inspecting the Gateway's serialized error payload.
229
229
 
230
+ ## Image Models
231
+
232
+ AI Gateway supports image generation through `generateImage`. To reduce peak
233
+ memory when receiving large images, opt in to streaming base64 decoding:
234
+
235
+ ```ts
236
+ import { generateImage } from 'ai';
237
+ import type { GatewayProviderOptions } from '@ai-sdk/gateway';
238
+
239
+ const { image } = await generateImage({
240
+ model: 'bfl/flux-kontext-pro',
241
+ prompt: 'A mountain lake at sunrise',
242
+ providerOptions: {
243
+ gateway: {
244
+ experimental_streamingImageDecoding: true,
245
+ } satisfies GatewayProviderOptions,
246
+ },
247
+ });
248
+
249
+ console.log(image.uint8Array.byteLength);
250
+ ```
251
+
252
+ The option defaults to `false`, preserving base64 strings in provider results.
253
+ When enabled, canonical base64 images of at least 64 KiB are decoded while the
254
+ response arrives. The model returns these images as `Uint8Array`; if a response
255
+ mixes extracted bytes with smaller images, all images in that result become
256
+ bytes. Images that cannot be extracted retain the regular decoding path.
257
+
258
+ This experimental option changes what image-model middleware sees in
259
+ `result.images`. `GeneratedFile` still provides both `uint8Array` and `base64`,
260
+ but reading `base64` can require re-encoding. Validation errors contain short
261
+ placeholders for extracted data. The option is handled by the client and is
262
+ not sent to the Gateway service.
263
+
230
264
  ## Batch
231
265
 
232
266
  <Note type="warning">
@@ -534,6 +568,8 @@ const result = streamSpeech({
534
568
 
535
569
  ## Realtime Models
536
570
 
571
+ For a trusted [server-owned connection](/docs/ai-sdk-core/realtime#server-owned-connections), `getServerWebSocketConfig()` reuses Gateway HTTP authentication, protocol, team and custom headers. Only the conversation intent is supported. The identity codec passes through normalized usage only when the Gateway route includes it in its events; credentials in connection settings remain on your server.
572
+
537
573
  <Note type="warning">
538
574
  Realtime support is experimental and the API may change in patch releases.
539
575
  </Note>
@@ -776,6 +812,9 @@ It returns a `GatewayGenerationInfo` object with the following fields:
776
812
 
777
813
  - **id** _string_ - The generation ID
778
814
  - **totalCost** _number_ - Total cost in USD
815
+ - **marketCost** _number (optional)_ - Market cost in USD, excluding surcharges
816
+ - **surchargeCost** _number (optional)_ - Total surcharges applied in USD
817
+ - **gatewayCost** _number (optional)_ - Total amount debited in USD
779
818
  - **upstreamInferenceCost** _number_ - Upstream inference cost in USD (relevant for BYOK)
780
819
  - **usage** _number_ - Usage cost in USD (same as totalCost)
781
820
  - **createdAt** _string_ - ISO 8601 timestamp when the generation was created
@@ -793,6 +832,11 @@ It returns a `GatewayGenerationInfo` object with the following fields:
793
832
  - **cacheCreationTokens** _number_ - Cache creation input tokens
794
833
  - **billableWebSearchCalls** _number_ - Number of billable web search calls
795
834
 
835
+ The optional cost breakdown fields contain the values reported by AI Gateway.
836
+ Fields that are missing or `null` in the API response are omitted from the result,
837
+ so unavailable costs remain distinct from a reported cost of zero. The SDK does
838
+ not calculate these fields from other costs.
839
+
796
840
  ## Examples
797
841
 
798
842
  ### Basic Text Generation
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ai-sdk/gateway",
3
3
  "private": false,
4
- "version": "4.0.135",
4
+ "version": "4.0.136",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
7
7
  "sideEffects": false,
@@ -30,8 +30,8 @@
30
30
  }
31
31
  },
32
32
  "dependencies": {
33
- "@ai-sdk/provider": "4.0.35",
34
- "@ai-sdk/provider-utils": "5.0.74",
33
+ "@ai-sdk/provider": "4.0.36",
34
+ "@ai-sdk/provider-utils": "5.0.75",
35
35
  "@vercel/oidc": "3.2.0"
36
36
  },
37
37
  "devDependencies": {
@@ -21,6 +21,12 @@ export interface GatewayGenerationInfo {
21
21
  id: string;
22
22
  /** Total cost in USD */
23
23
  totalCost: number;
24
+ /** Market cost in USD, excluding surcharges. Omitted when unavailable. */
25
+ marketCost?: number;
26
+ /** Total surcharges applied in USD. Omitted when unavailable. */
27
+ surchargeCost?: number;
28
+ /** Total amount debited in USD. Omitted when unavailable. */
29
+ gatewayCost?: number;
24
30
  /** Upstream inference cost in USD (BYOK only) */
25
31
  upstreamInferenceCost: number;
26
32
  /** Usage cost in USD (same as totalCost) */
@@ -95,6 +101,9 @@ const gatewayGenerationInfoResponseSchema = lazySchema(() =>
95
101
  .object({
96
102
  id: z.string(),
97
103
  total_cost: z.number(),
104
+ market_cost: z.number().nullish(),
105
+ surcharge_cost: z.number().nullish(),
106
+ gateway_cost: z.number().nullish(),
98
107
  upstream_inference_cost: z.number(),
99
108
  usage: z.number(),
100
109
  created_at: z.string(),
@@ -115,6 +124,9 @@ const gatewayGenerationInfoResponseSchema = lazySchema(() =>
115
124
  .transform(
116
125
  ({
117
126
  total_cost,
127
+ market_cost,
128
+ surcharge_cost,
129
+ gateway_cost,
118
130
  upstream_inference_cost,
119
131
  created_at,
120
132
  is_byok,
@@ -131,6 +143,11 @@ const gatewayGenerationInfoResponseSchema = lazySchema(() =>
131
143
  }) => ({
132
144
  ...rest,
133
145
  totalCost: total_cost,
146
+ ...(market_cost != null ? { marketCost: market_cost } : {}),
147
+ ...(surcharge_cost != null
148
+ ? { surchargeCost: surcharge_cost }
149
+ : {}),
150
+ ...(gateway_cost != null ? { gatewayCost: gateway_cost } : {}),
134
151
  upstreamInferenceCost: upstream_inference_cost,
135
152
  createdAt: created_at,
136
153
  isByok: is_byok,
@@ -7,6 +7,7 @@ import {
7
7
  lazySchema,
8
8
  zodSchema,
9
9
  combineHeaders,
10
+ convertBase64ToUint8Array,
10
11
  convertUint8ArrayToBase64,
11
12
  createJsonErrorResponseHandler,
12
13
  createJsonResponseHandler,
@@ -70,6 +71,27 @@ export class GatewayImageModel implements ImageModelV4 {
70
71
  }: Parameters<ImageModelV4['doGenerate']>[0]): Promise<
71
72
  Awaited<ReturnType<ImageModelV4['doGenerate']>>
72
73
  > {
74
+ const gatewayOptions = providerOptions?.gateway;
75
+ const streamingImageDecoding =
76
+ gatewayOptions?.experimental_streamingImageDecoding === true;
77
+ let requestProviderOptions: typeof providerOptions | undefined =
78
+ providerOptions;
79
+ if (
80
+ gatewayOptions &&
81
+ 'experimental_streamingImageDecoding' in gatewayOptions
82
+ ) {
83
+ const { experimental_streamingImageDecoding: _, ...serviceOptions } =
84
+ gatewayOptions;
85
+ requestProviderOptions = { ...providerOptions };
86
+ if (Object.keys(serviceOptions).length > 0) {
87
+ requestProviderOptions.gateway = serviceOptions;
88
+ } else {
89
+ delete requestProviderOptions.gateway;
90
+ }
91
+ if (Object.keys(requestProviderOptions).length === 0) {
92
+ requestProviderOptions = undefined;
93
+ }
94
+ }
73
95
  const resolvedHeaders = this.config.headers
74
96
  ? await resolve(this.config.headers)
75
97
  : undefined;
@@ -87,8 +109,10 @@ export class GatewayImageModel implements ImageModelV4 {
87
109
  n,
88
110
  ...(size && { size }),
89
111
  ...(aspectRatio && { aspectRatio }),
90
- ...(seed && { seed }),
91
- ...(providerOptions && { providerOptions }),
112
+ ...(seed != null && { seed }),
113
+ ...(requestProviderOptions && {
114
+ providerOptions: requestProviderOptions,
115
+ }),
92
116
  ...(files && {
93
117
  files: files.map(file => maybeEncodeImageFile(file)),
94
118
  }),
@@ -96,6 +120,9 @@ export class GatewayImageModel implements ImageModelV4 {
96
120
  },
97
121
  successfulResponseHandler: createJsonResponseHandler(
98
122
  gatewayImageResponseSchema,
123
+ streamingImageDecoding
124
+ ? { experimental_binaryFields: ['images[*]'] }
125
+ : undefined,
99
126
  ),
100
127
  failedResponseHandler: createJsonErrorResponseHandler({
101
128
  errorSchema: z.any(),
@@ -106,7 +133,7 @@ export class GatewayImageModel implements ImageModelV4 {
106
133
  });
107
134
 
108
135
  return {
109
- images: responseBody.images, // Always base64 strings from server
136
+ images: toImageModelImages(responseBody.images),
110
137
  ...(responseBody.isRetryable != null && {
111
138
  isRetryable: responseBody.isRetryable,
112
139
  }),
@@ -156,6 +183,21 @@ function maybeEncodeImageFile(file: ImageModelV4File) {
156
183
  return file;
157
184
  }
158
185
 
186
+ // A result holds either strings or bytes. Images that the response handler
187
+ // decoded while reading arrive as `Uint8Array`, smaller ones stay base64
188
+ // strings, so a mix is decoded to bytes.
189
+ function toImageModelImages(
190
+ images: Array<string | Uint8Array>,
191
+ ): Array<string> | Array<Uint8Array> {
192
+ if (images.every((image): image is string => typeof image === 'string')) {
193
+ return images;
194
+ }
195
+
196
+ return images.map(image =>
197
+ typeof image === 'string' ? convertBase64ToUint8Array(image) : image,
198
+ );
199
+ }
200
+
159
201
  const providerMetadataEntrySchema = () =>
160
202
  z
161
203
  .object({
@@ -196,7 +238,10 @@ const gatewayImageUsageSchema = () =>
196
238
  const gatewayImageResponseSchema = lazySchema(() =>
197
239
  zodSchema(
198
240
  z.object({
199
- images: z.array(z.string()), // Always base64 strings over the wire
241
+ // Base64 strings over the wire. Large ones are decoded to bytes while the
242
+ // response is read (`experimental_binaryFields`), see
243
+ // `toImageModelImages`.
244
+ images: z.array(z.union([z.string(), z.instanceof(Uint8Array)])),
200
245
  isRetryable: z.boolean().optional(),
201
246
  warnings: z.array(gatewayImageWarningSchema()).optional(),
202
247
  providerMetadata: z
@@ -294,11 +294,10 @@ export type GatewayModelId =
294
294
  | 'tencent/hy-mt2-plus'
295
295
  | 'tencent/hy-mt2-pro'
296
296
  | 'tencent/hy3'
297
+ | 'tencent/hy4'
297
298
  | 'tencent/hy4-preview'
298
299
  | 'thinkingmachines/inkling'
299
300
  | 'thinkingmachines/inkling-small'
300
- | 'xiaomi/mimo-v2.5'
301
- | 'xiaomi/mimo-v2.5-pro'
302
301
  | 'xiaomi/mimo-v2.6-flash'
303
302
  | 'xiaomi/mimo-v2.6-pro'
304
303
  | 'xiaomi/mimo-v2.6-pro-ultraspeed'
@@ -59,6 +59,14 @@ export type GatewayProviderOptions<QUESTION_ID extends string = string> = {
59
59
  /** Enables automatic caching behavior when supported by the Gateway. */
60
60
  caching?: 'auto';
61
61
 
62
+ /**
63
+ * Experimental, image models only: decode large base64 images while reading
64
+ * the response to reduce peak memory. Extracted images are returned as bytes;
65
+ * if a result mixes extracted and small images, all are returned as bytes.
66
+ * Defaults to false. Image models remove this client option from requests.
67
+ */
68
+ experimental_streamingImageDecoding?: boolean;
69
+
62
70
  /** Filter to providers that do not train on prompt data. */
63
71
  disallowPromptTraining?: boolean;
64
72
 
@@ -764,6 +764,7 @@ export function createGateway(
764
764
  baseURL,
765
765
  teamIdOrSlug: options.teamIdOrSlug,
766
766
  createClientSecret: mintClientSecret,
767
+ getHeaders,
767
768
  });
768
769
  provider.experimental_realtime = Object.assign(
769
770
  (modelId: GatewayRealtimeModelId) => createRealtimeModel(modelId),
@@ -3,15 +3,19 @@ import type {
3
3
  Experimental_RealtimeModelV4ClientEvent as RealtimeModelV4ClientEvent,
4
4
  Experimental_RealtimeModelV4ClientSecretOptions as RealtimeModelV4ClientSecretOptions,
5
5
  Experimental_RealtimeModelV4ClientSecretResult as RealtimeModelV4ClientSecretResult,
6
+ Experimental_RealtimeModelV4ServerConnection as RealtimeModelV4ServerConnection,
6
7
  Experimental_RealtimeModelV4ServerEvent as RealtimeModelV4ServerEvent,
7
8
  Experimental_RealtimeModelV4SessionConfig as RealtimeModelV4SessionConfig,
9
+ Experimental_RealtimeModelV4SessionIntent as RealtimeModelV4SessionIntent,
8
10
  } from '@ai-sdk/provider';
11
+ import { removeUndefinedEntries } from '@ai-sdk/provider-utils';
9
12
  import { getGatewayRealtimeProtocols } from './gateway-realtime-auth';
10
13
 
11
14
  export type GatewayRealtimeModelConfig = {
12
15
  provider: string;
13
16
  baseURL: string;
14
17
  teamIdOrSlug?: string;
18
+ getHeaders: () => Promise<Record<string, string | undefined>>;
15
19
  /**
16
20
  * Mints a short-lived client secret (`vcst_`) for this model via the
17
21
  * Gateway's `/v1/realtime/client-secrets` endpoint. Implemented by the
@@ -35,6 +39,11 @@ export type GatewayRealtimeModelConfig = {
35
39
  */
36
40
  export class GatewayRealtimeModel implements RealtimeModelV4 {
37
41
  readonly specificationVersion = 'v4' as const;
42
+ readonly capabilities = {
43
+ conversation: 'turn-based',
44
+ transports: ['websocket'],
45
+ connections: ['client-secret-websocket', 'server-websocket'],
46
+ } as const;
38
47
  readonly provider: string;
39
48
  readonly modelId: string;
40
49
 
@@ -84,18 +93,47 @@ export class GatewayRealtimeModel implements RealtimeModelV4 {
84
93
  };
85
94
  }
86
95
 
96
+ async getServerWebSocketConfig(options?: {
97
+ intent?: RealtimeModelV4SessionIntent;
98
+ }): Promise<RealtimeModelV4ServerConnection> {
99
+ this.assertConversationIntent(options);
100
+
101
+ return {
102
+ url: toGatewayRealtimeUrl(this.config.baseURL, this.modelId),
103
+ headers: removeUndefinedEntries(await this.config.getHeaders()),
104
+ };
105
+ }
106
+
107
+ private assertConversationIntent(options?: {
108
+ intent?: RealtimeModelV4SessionIntent;
109
+ }): void {
110
+ if (options?.intent != null && options.intent !== 'conversation') {
111
+ throw new Error(
112
+ `AI Gateway realtime does not support the '${options.intent}' session intent on the normalized realtime route.`,
113
+ );
114
+ }
115
+ }
116
+
87
117
  parseServerEvent(raw: unknown): RealtimeModelV4ServerEvent {
88
118
  // The Gateway emits normalized AI SDK realtime events, so no
89
119
  // provider-specific mapping is needed on the client.
90
120
  return raw as RealtimeModelV4ServerEvent;
91
121
  }
92
122
 
93
- serializeClientEvent(event: RealtimeModelV4ClientEvent): unknown {
123
+ serializeClientEvent(
124
+ event: RealtimeModelV4ClientEvent,
125
+ options?: { intent?: RealtimeModelV4SessionIntent },
126
+ ): unknown {
127
+ this.assertConversationIntent(options);
94
128
  // The Gateway accepts normalized AI SDK realtime events directly.
95
129
  return event;
96
130
  }
97
131
 
98
- buildSessionConfig(config: RealtimeModelV4SessionConfig): unknown {
132
+ buildSessionConfig(
133
+ config: RealtimeModelV4SessionConfig,
134
+ options?: { intent?: RealtimeModelV4SessionIntent },
135
+ ): unknown {
136
+ this.assertConversationIntent(options);
99
137
  // The session config is already normalized; the Gateway maps it to the
100
138
  // upstream provider's session payload server-side.
101
139
  return config;
@@ -65,6 +65,7 @@ export class GatewayTranscriptionModel implements TranscriptionModelV4 {
65
65
  audio,
66
66
  mediaType,
67
67
  providerOptions,
68
+ timestampGranularities,
68
69
  headers,
69
70
  abortSignal,
70
71
  }: Parameters<TranscriptionModelV4['doGenerate']>[0]): Promise<
@@ -108,6 +109,14 @@ export class GatewayTranscriptionModel implements TranscriptionModelV4 {
108
109
  const warnings = [
109
110
  ...(responseBody.warnings ?? []),
110
111
  ] as Array<SharedV4Warning>;
112
+ if (timestampGranularities?.length) {
113
+ warnings.push({
114
+ type: 'unsupported',
115
+ feature: 'timestampGranularities',
116
+ details:
117
+ 'The AI Gateway adapter does not forward the shared timestampGranularities option.',
118
+ });
119
+ }
111
120
  if (
112
121
  isXaiTranscriptionModel(this.modelId) &&
113
122
  requestsXaiDiarization(providerOptions) &&
@@ -124,6 +133,7 @@ export class GatewayTranscriptionModel implements TranscriptionModelV4 {
124
133
  return {
125
134
  text: responseBody.text,
126
135
  segments: responseBody.segments ?? [],
136
+ ...(responseBody.words != null && { words: responseBody.words }),
127
137
  language: responseBody.language ?? undefined,
128
138
  durationInSeconds: responseBody.durationInSeconds ?? undefined,
129
139
  warnings,
@@ -497,6 +507,15 @@ const gatewayTranscriptionResponseSchema = lazySchema(() =>
497
507
  }),
498
508
  )
499
509
  .optional(),
510
+ words: z
511
+ .array(
512
+ z.object({
513
+ text: z.string(),
514
+ startSecond: z.number(),
515
+ endSecond: z.number(),
516
+ }),
517
+ )
518
+ .nullish(),
500
519
  language: z.string().nullish(),
501
520
  durationInSeconds: z.number().nullish(),
502
521
  warnings: z.array(gatewayTranscriptionWarningSchema()).optional(),
@@ -354,7 +354,7 @@ export class GatewayVideoModel implements VideoModelV4 {
354
354
  ...(resolution && { resolution }),
355
355
  ...(duration && { duration }),
356
356
  ...(fps && { fps }),
357
- ...(seed && { seed }),
357
+ ...(seed != null && { seed }),
358
358
  ...(generateAudio !== undefined && { generateAudio }),
359
359
  ...(providerOptions && { providerOptions }),
360
360
  ...(image && { image: maybeEncodeVideoFile(image) }),
@@ -411,6 +411,10 @@ const providerMetadataEntrySchema = () =>
411
411
 
412
412
  const gatewayVideoDataSchema = () =>
413
413
  z.union([
414
+ z.object({
415
+ type: z.literal('uploaded'),
416
+ mediaType: z.string(),
417
+ }),
414
418
  z.object({
415
419
  type: z.literal('url'),
416
420
  url: z.string(),
package/src/zod.ts CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  boolean,
5
5
  discriminatedUnion,
6
6
  enum as enumType,
7
+ instanceof as instanceOf,
7
8
  literal,
8
9
  json,
9
10
  number,
@@ -22,6 +23,7 @@ export const z = {
22
23
  boolean,
23
24
  discriminatedUnion,
24
25
  enum: enumType,
26
+ instanceof: instanceOf,
25
27
  literal,
26
28
  json,
27
29
  number,