@ai-sdk/gateway 0.0.0-02dba89b-20251009204516

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.
package/dist/index.js ADDED
@@ -0,0 +1,841 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name7 in all)
8
+ __defProp(target, name7, { get: all[name7], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ GatewayAuthenticationError: () => GatewayAuthenticationError,
24
+ GatewayError: () => GatewayError,
25
+ GatewayInternalServerError: () => GatewayInternalServerError,
26
+ GatewayInvalidRequestError: () => GatewayInvalidRequestError,
27
+ GatewayModelNotFoundError: () => GatewayModelNotFoundError,
28
+ GatewayRateLimitError: () => GatewayRateLimitError,
29
+ GatewayResponseError: () => GatewayResponseError,
30
+ createGateway: () => createGatewayProvider,
31
+ createGatewayProvider: () => createGatewayProvider,
32
+ gateway: () => gateway
33
+ });
34
+ module.exports = __toCommonJS(src_exports);
35
+
36
+ // src/gateway-provider.ts
37
+ var import_provider2 = require("@ai-sdk/provider");
38
+ var import_provider_utils4 = require("@ai-sdk/provider-utils");
39
+
40
+ // src/errors/as-gateway-error.ts
41
+ var import_provider = require("@ai-sdk/provider");
42
+
43
+ // src/errors/create-gateway-error.ts
44
+ var import_v42 = require("zod/v4");
45
+
46
+ // src/errors/gateway-error.ts
47
+ var marker = "vercel.ai.gateway.error";
48
+ var symbol = Symbol.for(marker);
49
+ var _a, _b;
50
+ var GatewayError = class _GatewayError extends (_b = Error, _a = symbol, _b) {
51
+ constructor({
52
+ message,
53
+ statusCode = 500,
54
+ cause
55
+ }) {
56
+ super(message);
57
+ this[_a] = true;
58
+ this.statusCode = statusCode;
59
+ this.cause = cause;
60
+ }
61
+ /**
62
+ * Checks if the given error is a Gateway Error.
63
+ * @param {unknown} error - The error to check.
64
+ * @returns {boolean} True if the error is a Gateway Error, false otherwise.
65
+ */
66
+ static isInstance(error) {
67
+ return _GatewayError.hasMarker(error);
68
+ }
69
+ static hasMarker(error) {
70
+ return typeof error === "object" && error !== null && symbol in error && error[symbol] === true;
71
+ }
72
+ };
73
+
74
+ // src/errors/gateway-authentication-error.ts
75
+ var name = "GatewayAuthenticationError";
76
+ var marker2 = `vercel.ai.gateway.error.${name}`;
77
+ var symbol2 = Symbol.for(marker2);
78
+ var _a2, _b2;
79
+ var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b2 = GatewayError, _a2 = symbol2, _b2) {
80
+ constructor({
81
+ message = "Authentication failed",
82
+ statusCode = 401,
83
+ cause
84
+ } = {}) {
85
+ super({ message, statusCode, cause });
86
+ this[_a2] = true;
87
+ // used in isInstance
88
+ this.name = name;
89
+ this.type = "authentication_error";
90
+ }
91
+ static isInstance(error) {
92
+ return GatewayError.hasMarker(error) && symbol2 in error;
93
+ }
94
+ /**
95
+ * Creates a contextual error message when authentication fails
96
+ */
97
+ static createContextualError({
98
+ apiKeyProvided,
99
+ oidcTokenProvided,
100
+ message = "Authentication failed",
101
+ statusCode = 401,
102
+ cause
103
+ }) {
104
+ let contextualMessage;
105
+ if (apiKeyProvided) {
106
+ contextualMessage = `AI Gateway authentication failed: Invalid API key provided.
107
+
108
+ The token is expected to be provided via the 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`;
109
+ } else if (oidcTokenProvided) {
110
+ contextualMessage = `AI Gateway authentication failed: Invalid OIDC token provided.
111
+
112
+ The token is expected to be provided via the 'VERCEL_OIDC_TOKEN' environment variable. It expires every 12 hours.
113
+ - make sure your Vercel project settings have OIDC enabled
114
+ - if running locally with 'vercel dev', the token is automatically obtained and refreshed
115
+ - if running locally with your own dev server, run 'vercel env pull' to fetch the token
116
+ - in production/preview, the token is automatically obtained and refreshed
117
+
118
+ Alternative: Provide an API key via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`;
119
+ } else {
120
+ contextualMessage = `AI Gateway authentication failed: No authentication provided.
121
+
122
+ Provide either an API key or OIDC token.
123
+
124
+ API key instructions:
125
+
126
+ The token is expected to be provided via the 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
127
+
128
+ OIDC token instructions:
129
+
130
+ The token is expected to be provided via the 'VERCEL_OIDC_TOKEN' environment variable. It expires every 12 hours.
131
+ - make sure your Vercel project settings have OIDC enabled
132
+ - if running locally with 'vercel dev', the token is automatically obtained and refreshed
133
+ - if running locally with your own dev server, run 'vercel env pull' to fetch the token
134
+ - in production/preview, the token is automatically obtained and refreshed`;
135
+ }
136
+ return new _GatewayAuthenticationError({
137
+ message: contextualMessage,
138
+ statusCode,
139
+ cause
140
+ });
141
+ }
142
+ };
143
+
144
+ // src/errors/gateway-invalid-request-error.ts
145
+ var name2 = "GatewayInvalidRequestError";
146
+ var marker3 = `vercel.ai.gateway.error.${name2}`;
147
+ var symbol3 = Symbol.for(marker3);
148
+ var _a3, _b3;
149
+ var GatewayInvalidRequestError = class extends (_b3 = GatewayError, _a3 = symbol3, _b3) {
150
+ constructor({
151
+ message = "Invalid request",
152
+ statusCode = 400,
153
+ cause
154
+ } = {}) {
155
+ super({ message, statusCode, cause });
156
+ this[_a3] = true;
157
+ // used in isInstance
158
+ this.name = name2;
159
+ this.type = "invalid_request_error";
160
+ }
161
+ static isInstance(error) {
162
+ return GatewayError.hasMarker(error) && symbol3 in error;
163
+ }
164
+ };
165
+
166
+ // src/errors/gateway-rate-limit-error.ts
167
+ var name3 = "GatewayRateLimitError";
168
+ var marker4 = `vercel.ai.gateway.error.${name3}`;
169
+ var symbol4 = Symbol.for(marker4);
170
+ var _a4, _b4;
171
+ var GatewayRateLimitError = class extends (_b4 = GatewayError, _a4 = symbol4, _b4) {
172
+ constructor({
173
+ message = "Rate limit exceeded",
174
+ statusCode = 429,
175
+ cause
176
+ } = {}) {
177
+ super({ message, statusCode, cause });
178
+ this[_a4] = true;
179
+ // used in isInstance
180
+ this.name = name3;
181
+ this.type = "rate_limit_exceeded";
182
+ }
183
+ static isInstance(error) {
184
+ return GatewayError.hasMarker(error) && symbol4 in error;
185
+ }
186
+ };
187
+
188
+ // src/errors/gateway-model-not-found-error.ts
189
+ var import_v4 = require("zod/v4");
190
+ var name4 = "GatewayModelNotFoundError";
191
+ var marker5 = `vercel.ai.gateway.error.${name4}`;
192
+ var symbol5 = Symbol.for(marker5);
193
+ var modelNotFoundParamSchema = import_v4.z.object({
194
+ modelId: import_v4.z.string()
195
+ });
196
+ var _a5, _b5;
197
+ var GatewayModelNotFoundError = class extends (_b5 = GatewayError, _a5 = symbol5, _b5) {
198
+ constructor({
199
+ message = "Model not found",
200
+ statusCode = 404,
201
+ modelId,
202
+ cause
203
+ } = {}) {
204
+ super({ message, statusCode, cause });
205
+ this[_a5] = true;
206
+ // used in isInstance
207
+ this.name = name4;
208
+ this.type = "model_not_found";
209
+ this.modelId = modelId;
210
+ }
211
+ static isInstance(error) {
212
+ return GatewayError.hasMarker(error) && symbol5 in error;
213
+ }
214
+ };
215
+
216
+ // src/errors/gateway-internal-server-error.ts
217
+ var name5 = "GatewayInternalServerError";
218
+ var marker6 = `vercel.ai.gateway.error.${name5}`;
219
+ var symbol6 = Symbol.for(marker6);
220
+ var _a6, _b6;
221
+ var GatewayInternalServerError = class extends (_b6 = GatewayError, _a6 = symbol6, _b6) {
222
+ constructor({
223
+ message = "Internal server error",
224
+ statusCode = 500,
225
+ cause
226
+ } = {}) {
227
+ super({ message, statusCode, cause });
228
+ this[_a6] = true;
229
+ // used in isInstance
230
+ this.name = name5;
231
+ this.type = "internal_server_error";
232
+ }
233
+ static isInstance(error) {
234
+ return GatewayError.hasMarker(error) && symbol6 in error;
235
+ }
236
+ };
237
+
238
+ // src/errors/gateway-response-error.ts
239
+ var name6 = "GatewayResponseError";
240
+ var marker7 = `vercel.ai.gateway.error.${name6}`;
241
+ var symbol7 = Symbol.for(marker7);
242
+ var _a7, _b7;
243
+ var GatewayResponseError = class extends (_b7 = GatewayError, _a7 = symbol7, _b7) {
244
+ constructor({
245
+ message = "Invalid response from Gateway",
246
+ statusCode = 502,
247
+ response,
248
+ validationError,
249
+ cause
250
+ } = {}) {
251
+ super({ message, statusCode, cause });
252
+ this[_a7] = true;
253
+ // used in isInstance
254
+ this.name = name6;
255
+ this.type = "response_error";
256
+ this.response = response;
257
+ this.validationError = validationError;
258
+ }
259
+ static isInstance(error) {
260
+ return GatewayError.hasMarker(error) && symbol7 in error;
261
+ }
262
+ };
263
+
264
+ // src/errors/create-gateway-error.ts
265
+ function createGatewayErrorFromResponse({
266
+ response,
267
+ statusCode,
268
+ defaultMessage = "Gateway request failed",
269
+ cause,
270
+ authMethod
271
+ }) {
272
+ const parseResult = gatewayErrorResponseSchema.safeParse(response);
273
+ if (!parseResult.success) {
274
+ return new GatewayResponseError({
275
+ message: `Invalid error response format: ${defaultMessage}`,
276
+ statusCode,
277
+ response,
278
+ validationError: parseResult.error,
279
+ cause
280
+ });
281
+ }
282
+ const validatedResponse = parseResult.data;
283
+ const errorType = validatedResponse.error.type;
284
+ const message = validatedResponse.error.message;
285
+ switch (errorType) {
286
+ case "authentication_error":
287
+ return GatewayAuthenticationError.createContextualError({
288
+ apiKeyProvided: authMethod === "api-key",
289
+ oidcTokenProvided: authMethod === "oidc",
290
+ statusCode,
291
+ cause
292
+ });
293
+ case "invalid_request_error":
294
+ return new GatewayInvalidRequestError({ message, statusCode, cause });
295
+ case "rate_limit_exceeded":
296
+ return new GatewayRateLimitError({ message, statusCode, cause });
297
+ case "model_not_found": {
298
+ const modelResult = modelNotFoundParamSchema.safeParse(
299
+ validatedResponse.error.param
300
+ );
301
+ return new GatewayModelNotFoundError({
302
+ message,
303
+ statusCode,
304
+ modelId: modelResult.success ? modelResult.data.modelId : void 0,
305
+ cause
306
+ });
307
+ }
308
+ case "internal_server_error":
309
+ return new GatewayInternalServerError({ message, statusCode, cause });
310
+ default:
311
+ return new GatewayInternalServerError({ message, statusCode, cause });
312
+ }
313
+ }
314
+ var gatewayErrorResponseSchema = import_v42.z.object({
315
+ error: import_v42.z.object({
316
+ message: import_v42.z.string(),
317
+ type: import_v42.z.string().nullish(),
318
+ param: import_v42.z.unknown().nullish(),
319
+ code: import_v42.z.union([import_v42.z.string(), import_v42.z.number()]).nullish()
320
+ })
321
+ });
322
+
323
+ // src/errors/as-gateway-error.ts
324
+ function asGatewayError(error, authMethod) {
325
+ var _a8;
326
+ if (GatewayError.isInstance(error)) {
327
+ return error;
328
+ }
329
+ if (import_provider.APICallError.isInstance(error)) {
330
+ return createGatewayErrorFromResponse({
331
+ response: extractApiCallResponse(error),
332
+ statusCode: (_a8 = error.statusCode) != null ? _a8 : 500,
333
+ defaultMessage: "Gateway request failed",
334
+ cause: error,
335
+ authMethod
336
+ });
337
+ }
338
+ return createGatewayErrorFromResponse({
339
+ response: {},
340
+ statusCode: 500,
341
+ defaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : "Unknown Gateway error",
342
+ cause: error,
343
+ authMethod
344
+ });
345
+ }
346
+
347
+ // src/errors/extract-api-call-response.ts
348
+ function extractApiCallResponse(error) {
349
+ if (error.data !== void 0) {
350
+ return error.data;
351
+ }
352
+ if (error.responseBody != null) {
353
+ try {
354
+ return JSON.parse(error.responseBody);
355
+ } catch (e) {
356
+ return error.responseBody;
357
+ }
358
+ }
359
+ return {};
360
+ }
361
+
362
+ // src/errors/parse-auth-method.ts
363
+ var import_v43 = require("zod/v4");
364
+ var GATEWAY_AUTH_METHOD_HEADER = "ai-gateway-auth-method";
365
+ function parseAuthMethod(headers) {
366
+ const result = gatewayAuthMethodSchema.safeParse(
367
+ headers[GATEWAY_AUTH_METHOD_HEADER]
368
+ );
369
+ return result.success ? result.data : void 0;
370
+ }
371
+ var gatewayAuthMethodSchema = import_v43.z.union([
372
+ import_v43.z.literal("api-key"),
373
+ import_v43.z.literal("oidc")
374
+ ]);
375
+
376
+ // src/gateway-fetch-metadata.ts
377
+ var import_provider_utils = require("@ai-sdk/provider-utils");
378
+ var import_v44 = require("zod/v4");
379
+ var GatewayFetchMetadata = class {
380
+ constructor(config) {
381
+ this.config = config;
382
+ }
383
+ async getAvailableModels() {
384
+ try {
385
+ const { value } = await (0, import_provider_utils.getFromApi)({
386
+ url: `${this.config.baseURL}/config`,
387
+ headers: await (0, import_provider_utils.resolve)(this.config.headers()),
388
+ successfulResponseHandler: (0, import_provider_utils.createJsonResponseHandler)(
389
+ gatewayFetchMetadataSchema
390
+ ),
391
+ failedResponseHandler: (0, import_provider_utils.createJsonErrorResponseHandler)({
392
+ errorSchema: import_v44.z.any(),
393
+ errorToMessage: (data) => data
394
+ }),
395
+ fetch: this.config.fetch
396
+ });
397
+ return value;
398
+ } catch (error) {
399
+ throw asGatewayError(error);
400
+ }
401
+ }
402
+ async getCredits() {
403
+ try {
404
+ const baseUrl = new URL(this.config.baseURL);
405
+ const { value } = await (0, import_provider_utils.getFromApi)({
406
+ url: `${baseUrl.origin}/v1/credits`,
407
+ headers: await (0, import_provider_utils.resolve)(this.config.headers()),
408
+ successfulResponseHandler: (0, import_provider_utils.createJsonResponseHandler)(gatewayCreditsSchema),
409
+ failedResponseHandler: (0, import_provider_utils.createJsonErrorResponseHandler)({
410
+ errorSchema: import_v44.z.any(),
411
+ errorToMessage: (data) => data
412
+ }),
413
+ fetch: this.config.fetch
414
+ });
415
+ return value;
416
+ } catch (error) {
417
+ throw asGatewayError(error);
418
+ }
419
+ }
420
+ };
421
+ var gatewayLanguageModelSpecificationSchema = import_v44.z.object({
422
+ specificationVersion: import_v44.z.literal("v2"),
423
+ provider: import_v44.z.string(),
424
+ modelId: import_v44.z.string()
425
+ });
426
+ var gatewayLanguageModelPricingSchema = import_v44.z.object({
427
+ input: import_v44.z.string(),
428
+ output: import_v44.z.string(),
429
+ input_cache_read: import_v44.z.string().nullish(),
430
+ input_cache_write: import_v44.z.string().nullish()
431
+ }).transform(({ input, output, input_cache_read, input_cache_write }) => ({
432
+ input,
433
+ output,
434
+ ...input_cache_read ? { cachedInputTokens: input_cache_read } : {},
435
+ ...input_cache_write ? { cacheCreationInputTokens: input_cache_write } : {}
436
+ }));
437
+ var gatewayLanguageModelEntrySchema = import_v44.z.object({
438
+ id: import_v44.z.string(),
439
+ name: import_v44.z.string(),
440
+ description: import_v44.z.string().nullish(),
441
+ pricing: gatewayLanguageModelPricingSchema.nullish(),
442
+ specification: gatewayLanguageModelSpecificationSchema,
443
+ modelType: import_v44.z.enum(["language", "embedding", "image"]).nullish()
444
+ });
445
+ var gatewayFetchMetadataSchema = import_v44.z.object({
446
+ models: import_v44.z.array(gatewayLanguageModelEntrySchema)
447
+ });
448
+ var gatewayCreditsSchema = import_v44.z.object({
449
+ balance: import_v44.z.string(),
450
+ total_used: import_v44.z.string()
451
+ }).transform(({ balance, total_used }) => ({
452
+ balance,
453
+ totalUsed: total_used
454
+ }));
455
+
456
+ // src/gateway-language-model.ts
457
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
458
+ var import_v45 = require("zod/v4");
459
+ var GatewayLanguageModel = class {
460
+ constructor(modelId, config) {
461
+ this.modelId = modelId;
462
+ this.config = config;
463
+ this.specificationVersion = "v2";
464
+ this.supportedUrls = { "*/*": [/.*/] };
465
+ }
466
+ get provider() {
467
+ return this.config.provider;
468
+ }
469
+ async getArgs(options) {
470
+ const { abortSignal: _abortSignal, ...optionsWithoutSignal } = options;
471
+ return {
472
+ args: this.maybeEncodeFileParts(optionsWithoutSignal),
473
+ warnings: []
474
+ };
475
+ }
476
+ async doGenerate(options) {
477
+ const { args, warnings } = await this.getArgs(options);
478
+ const { abortSignal } = options;
479
+ const resolvedHeaders = await (0, import_provider_utils2.resolve)(this.config.headers());
480
+ try {
481
+ const {
482
+ responseHeaders,
483
+ value: responseBody,
484
+ rawValue: rawResponse
485
+ } = await (0, import_provider_utils2.postJsonToApi)({
486
+ url: this.getUrl(),
487
+ headers: (0, import_provider_utils2.combineHeaders)(
488
+ resolvedHeaders,
489
+ options.headers,
490
+ this.getModelConfigHeaders(this.modelId, false),
491
+ await (0, import_provider_utils2.resolve)(this.config.o11yHeaders)
492
+ ),
493
+ body: args,
494
+ successfulResponseHandler: (0, import_provider_utils2.createJsonResponseHandler)(import_v45.z.any()),
495
+ failedResponseHandler: (0, import_provider_utils2.createJsonErrorResponseHandler)({
496
+ errorSchema: import_v45.z.any(),
497
+ errorToMessage: (data) => data
498
+ }),
499
+ ...abortSignal && { abortSignal },
500
+ fetch: this.config.fetch
501
+ });
502
+ return {
503
+ ...responseBody,
504
+ request: { body: args },
505
+ response: { headers: responseHeaders, body: rawResponse },
506
+ warnings
507
+ };
508
+ } catch (error) {
509
+ throw asGatewayError(error, parseAuthMethod(resolvedHeaders));
510
+ }
511
+ }
512
+ async doStream(options) {
513
+ const { args, warnings } = await this.getArgs(options);
514
+ const { abortSignal } = options;
515
+ const resolvedHeaders = await (0, import_provider_utils2.resolve)(this.config.headers());
516
+ try {
517
+ const { value: response, responseHeaders } = await (0, import_provider_utils2.postJsonToApi)({
518
+ url: this.getUrl(),
519
+ headers: (0, import_provider_utils2.combineHeaders)(
520
+ resolvedHeaders,
521
+ options.headers,
522
+ this.getModelConfigHeaders(this.modelId, true),
523
+ await (0, import_provider_utils2.resolve)(this.config.o11yHeaders)
524
+ ),
525
+ body: args,
526
+ successfulResponseHandler: (0, import_provider_utils2.createEventSourceResponseHandler)(import_v45.z.any()),
527
+ failedResponseHandler: (0, import_provider_utils2.createJsonErrorResponseHandler)({
528
+ errorSchema: import_v45.z.any(),
529
+ errorToMessage: (data) => data
530
+ }),
531
+ ...abortSignal && { abortSignal },
532
+ fetch: this.config.fetch
533
+ });
534
+ return {
535
+ stream: response.pipeThrough(
536
+ new TransformStream({
537
+ start(controller) {
538
+ if (warnings.length > 0) {
539
+ controller.enqueue({ type: "stream-start", warnings });
540
+ }
541
+ },
542
+ transform(chunk, controller) {
543
+ if (chunk.success) {
544
+ const streamPart = chunk.value;
545
+ if (streamPart.type === "raw" && !options.includeRawChunks) {
546
+ return;
547
+ }
548
+ if (streamPart.type === "response-metadata" && streamPart.timestamp && typeof streamPart.timestamp === "string") {
549
+ streamPart.timestamp = new Date(streamPart.timestamp);
550
+ }
551
+ controller.enqueue(streamPart);
552
+ } else {
553
+ controller.error(
554
+ chunk.error
555
+ );
556
+ }
557
+ }
558
+ })
559
+ ),
560
+ request: { body: args },
561
+ response: { headers: responseHeaders }
562
+ };
563
+ } catch (error) {
564
+ throw asGatewayError(error, parseAuthMethod(resolvedHeaders));
565
+ }
566
+ }
567
+ isFilePart(part) {
568
+ return part && typeof part === "object" && "type" in part && part.type === "file";
569
+ }
570
+ /**
571
+ * Encodes file parts in the prompt to base64. Mutates the passed options
572
+ * instance directly to avoid copying the file data.
573
+ * @param options - The options to encode.
574
+ * @returns The options with the file parts encoded.
575
+ */
576
+ maybeEncodeFileParts(options) {
577
+ for (const message of options.prompt) {
578
+ for (const part of message.content) {
579
+ if (this.isFilePart(part)) {
580
+ const filePart = part;
581
+ if (filePart.data instanceof Uint8Array) {
582
+ const buffer = Uint8Array.from(filePart.data);
583
+ const base64Data = Buffer.from(buffer).toString("base64");
584
+ filePart.data = new URL(
585
+ `data:${filePart.mediaType || "application/octet-stream"};base64,${base64Data}`
586
+ );
587
+ }
588
+ }
589
+ }
590
+ }
591
+ return options;
592
+ }
593
+ getUrl() {
594
+ return `${this.config.baseURL}/language-model`;
595
+ }
596
+ getModelConfigHeaders(modelId, streaming) {
597
+ return {
598
+ "ai-language-model-specification-version": "2",
599
+ "ai-language-model-id": modelId,
600
+ "ai-language-model-streaming": String(streaming)
601
+ };
602
+ }
603
+ };
604
+
605
+ // src/gateway-embedding-model.ts
606
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
607
+ var import_v46 = require("zod/v4");
608
+ var GatewayEmbeddingModel = class {
609
+ constructor(modelId, config) {
610
+ this.modelId = modelId;
611
+ this.config = config;
612
+ this.specificationVersion = "v2";
613
+ this.maxEmbeddingsPerCall = 2048;
614
+ this.supportsParallelCalls = true;
615
+ }
616
+ get provider() {
617
+ return this.config.provider;
618
+ }
619
+ async doEmbed({
620
+ values,
621
+ headers,
622
+ abortSignal,
623
+ providerOptions
624
+ }) {
625
+ var _a8;
626
+ const resolvedHeaders = await (0, import_provider_utils3.resolve)(this.config.headers());
627
+ try {
628
+ const {
629
+ responseHeaders,
630
+ value: responseBody,
631
+ rawValue
632
+ } = await (0, import_provider_utils3.postJsonToApi)({
633
+ url: this.getUrl(),
634
+ headers: (0, import_provider_utils3.combineHeaders)(
635
+ resolvedHeaders,
636
+ headers != null ? headers : {},
637
+ this.getModelConfigHeaders(),
638
+ await (0, import_provider_utils3.resolve)(this.config.o11yHeaders)
639
+ ),
640
+ body: {
641
+ input: values.length === 1 ? values[0] : values,
642
+ ...providerOptions ? { providerOptions } : {}
643
+ },
644
+ successfulResponseHandler: (0, import_provider_utils3.createJsonResponseHandler)(
645
+ gatewayEmbeddingResponseSchema
646
+ ),
647
+ failedResponseHandler: (0, import_provider_utils3.createJsonErrorResponseHandler)({
648
+ errorSchema: import_v46.z.any(),
649
+ errorToMessage: (data) => data
650
+ }),
651
+ ...abortSignal && { abortSignal },
652
+ fetch: this.config.fetch
653
+ });
654
+ return {
655
+ embeddings: responseBody.embeddings,
656
+ usage: (_a8 = responseBody.usage) != null ? _a8 : void 0,
657
+ providerMetadata: responseBody.providerMetadata,
658
+ response: { headers: responseHeaders, body: rawValue }
659
+ };
660
+ } catch (error) {
661
+ throw asGatewayError(error, parseAuthMethod(resolvedHeaders));
662
+ }
663
+ }
664
+ getUrl() {
665
+ return `${this.config.baseURL}/embedding-model`;
666
+ }
667
+ getModelConfigHeaders() {
668
+ return {
669
+ "ai-embedding-model-specification-version": "2",
670
+ "ai-model-id": this.modelId
671
+ };
672
+ }
673
+ };
674
+ var gatewayEmbeddingResponseSchema = import_v46.z.object({
675
+ embeddings: import_v46.z.array(import_v46.z.array(import_v46.z.number())),
676
+ usage: import_v46.z.object({ tokens: import_v46.z.number() }).nullish(),
677
+ providerMetadata: import_v46.z.record(import_v46.z.string(), import_v46.z.record(import_v46.z.string(), import_v46.z.unknown())).optional()
678
+ });
679
+
680
+ // src/vercel-environment.ts
681
+ var import_oidc = require("@vercel/oidc");
682
+ var import_oidc2 = require("@vercel/oidc");
683
+ async function getVercelRequestId() {
684
+ var _a8;
685
+ return (_a8 = (0, import_oidc.getContext)().headers) == null ? void 0 : _a8["x-vercel-id"];
686
+ }
687
+
688
+ // src/gateway-provider.ts
689
+ var import_provider_utils5 = require("@ai-sdk/provider-utils");
690
+
691
+ // src/version.ts
692
+ var VERSION = true ? "0.0.0-02dba89b-20251009204516" : "0.0.0-test";
693
+
694
+ // src/gateway-provider.ts
695
+ var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
696
+ function createGatewayProvider(options = {}) {
697
+ var _a8, _b8;
698
+ let pendingMetadata = null;
699
+ let metadataCache = null;
700
+ const cacheRefreshMillis = (_a8 = options.metadataCacheRefreshMillis) != null ? _a8 : 1e3 * 60 * 5;
701
+ let lastFetchTime = 0;
702
+ const baseURL = (_b8 = (0, import_provider_utils4.withoutTrailingSlash)(options.baseURL)) != null ? _b8 : "https://ai-gateway.vercel.sh/v1/ai";
703
+ const getHeaders = async () => {
704
+ const auth = await getGatewayAuthToken(options);
705
+ if (auth) {
706
+ return (0, import_provider_utils5.withUserAgentSuffix)(
707
+ {
708
+ Authorization: `Bearer ${auth.token}`,
709
+ "ai-gateway-protocol-version": AI_GATEWAY_PROTOCOL_VERSION,
710
+ [GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod,
711
+ ...options.headers
712
+ },
713
+ `ai-sdk/gateway/${VERSION}`
714
+ );
715
+ }
716
+ throw GatewayAuthenticationError.createContextualError({
717
+ apiKeyProvided: false,
718
+ oidcTokenProvided: false,
719
+ statusCode: 401
720
+ });
721
+ };
722
+ const createO11yHeaders = () => {
723
+ const deploymentId = (0, import_provider_utils4.loadOptionalSetting)({
724
+ settingValue: void 0,
725
+ environmentVariableName: "VERCEL_DEPLOYMENT_ID"
726
+ });
727
+ const environment = (0, import_provider_utils4.loadOptionalSetting)({
728
+ settingValue: void 0,
729
+ environmentVariableName: "VERCEL_ENV"
730
+ });
731
+ const region = (0, import_provider_utils4.loadOptionalSetting)({
732
+ settingValue: void 0,
733
+ environmentVariableName: "VERCEL_REGION"
734
+ });
735
+ return async () => {
736
+ const requestId = await getVercelRequestId();
737
+ return {
738
+ ...deploymentId && { "ai-o11y-deployment-id": deploymentId },
739
+ ...environment && { "ai-o11y-environment": environment },
740
+ ...region && { "ai-o11y-region": region },
741
+ ...requestId && { "ai-o11y-request-id": requestId }
742
+ };
743
+ };
744
+ };
745
+ const createLanguageModel = (modelId) => {
746
+ return new GatewayLanguageModel(modelId, {
747
+ provider: "gateway",
748
+ baseURL,
749
+ headers: getHeaders,
750
+ fetch: options.fetch,
751
+ o11yHeaders: createO11yHeaders()
752
+ });
753
+ };
754
+ const getAvailableModels = async () => {
755
+ var _a9, _b9, _c;
756
+ const now = (_c = (_b9 = (_a9 = options._internal) == null ? void 0 : _a9.currentDate) == null ? void 0 : _b9.call(_a9).getTime()) != null ? _c : Date.now();
757
+ if (!pendingMetadata || now - lastFetchTime > cacheRefreshMillis) {
758
+ lastFetchTime = now;
759
+ pendingMetadata = new GatewayFetchMetadata({
760
+ baseURL,
761
+ headers: getHeaders,
762
+ fetch: options.fetch
763
+ }).getAvailableModels().then((metadata) => {
764
+ metadataCache = metadata;
765
+ return metadata;
766
+ }).catch(async (error) => {
767
+ throw asGatewayError(error, parseAuthMethod(await getHeaders()));
768
+ });
769
+ }
770
+ return metadataCache ? Promise.resolve(metadataCache) : pendingMetadata;
771
+ };
772
+ const getCredits = async () => {
773
+ return new GatewayFetchMetadata({
774
+ baseURL,
775
+ headers: getHeaders,
776
+ fetch: options.fetch
777
+ }).getCredits().catch(async (error) => {
778
+ throw asGatewayError(error, parseAuthMethod(await getHeaders()));
779
+ });
780
+ };
781
+ const provider = function(modelId) {
782
+ if (new.target) {
783
+ throw new Error(
784
+ "The Gateway Provider model function cannot be called with the new keyword."
785
+ );
786
+ }
787
+ return createLanguageModel(modelId);
788
+ };
789
+ provider.getAvailableModels = getAvailableModels;
790
+ provider.getCredits = getCredits;
791
+ provider.imageModel = (modelId) => {
792
+ throw new import_provider2.NoSuchModelError({ modelId, modelType: "imageModel" });
793
+ };
794
+ provider.languageModel = createLanguageModel;
795
+ provider.textEmbeddingModel = (modelId) => {
796
+ return new GatewayEmbeddingModel(modelId, {
797
+ provider: "gateway",
798
+ baseURL,
799
+ headers: getHeaders,
800
+ fetch: options.fetch,
801
+ o11yHeaders: createO11yHeaders()
802
+ });
803
+ };
804
+ return provider;
805
+ }
806
+ var gateway = createGatewayProvider();
807
+ async function getGatewayAuthToken(options) {
808
+ const apiKey = (0, import_provider_utils4.loadOptionalSetting)({
809
+ settingValue: options.apiKey,
810
+ environmentVariableName: "AI_GATEWAY_API_KEY"
811
+ });
812
+ if (apiKey) {
813
+ return {
814
+ token: apiKey,
815
+ authMethod: "api-key"
816
+ };
817
+ }
818
+ try {
819
+ const oidcToken = await (0, import_oidc2.getVercelOidcToken)();
820
+ return {
821
+ token: oidcToken,
822
+ authMethod: "oidc"
823
+ };
824
+ } catch (e) {
825
+ return null;
826
+ }
827
+ }
828
+ // Annotate the CommonJS export names for ESM import in node:
829
+ 0 && (module.exports = {
830
+ GatewayAuthenticationError,
831
+ GatewayError,
832
+ GatewayInternalServerError,
833
+ GatewayInvalidRequestError,
834
+ GatewayModelNotFoundError,
835
+ GatewayRateLimitError,
836
+ GatewayResponseError,
837
+ createGateway,
838
+ createGatewayProvider,
839
+ gateway
840
+ });
841
+ //# sourceMappingURL=index.js.map