@ai-sdk/gateway 4.0.0-beta.47 → 4.0.0-beta.49

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.mjs DELETED
@@ -1,1866 +0,0 @@
1
- // src/gateway-provider.ts
2
- import {
3
- loadOptionalSetting,
4
- withoutTrailingSlash
5
- } from "@ai-sdk/provider-utils";
6
-
7
- // src/errors/as-gateway-error.ts
8
- import { APICallError } from "@ai-sdk/provider";
9
-
10
- // src/errors/create-gateway-error.ts
11
- import { z as z2 } from "zod/v4";
12
-
13
- // src/errors/gateway-error.ts
14
- var marker = "vercel.ai.gateway.error";
15
- var symbol = Symbol.for(marker);
16
- var _a, _b;
17
- var GatewayError = class _GatewayError extends (_b = Error, _a = symbol, _b) {
18
- constructor({
19
- message,
20
- statusCode = 500,
21
- cause,
22
- generationId
23
- }) {
24
- super(generationId ? `${message} [${generationId}]` : message);
25
- this[_a] = true;
26
- this.statusCode = statusCode;
27
- this.cause = cause;
28
- this.generationId = generationId;
29
- }
30
- /**
31
- * Checks if the given error is a Gateway Error.
32
- * @param {unknown} error - The error to check.
33
- * @returns {boolean} True if the error is a Gateway Error, false otherwise.
34
- */
35
- static isInstance(error) {
36
- return _GatewayError.hasMarker(error);
37
- }
38
- static hasMarker(error) {
39
- return typeof error === "object" && error !== null && symbol in error && error[symbol] === true;
40
- }
41
- };
42
-
43
- // src/errors/gateway-authentication-error.ts
44
- var name = "GatewayAuthenticationError";
45
- var marker2 = `vercel.ai.gateway.error.${name}`;
46
- var symbol2 = Symbol.for(marker2);
47
- var _a2, _b2;
48
- var GatewayAuthenticationError = class _GatewayAuthenticationError extends (_b2 = GatewayError, _a2 = symbol2, _b2) {
49
- constructor({
50
- message = "Authentication failed",
51
- statusCode = 401,
52
- cause,
53
- generationId
54
- } = {}) {
55
- super({ message, statusCode, cause, generationId });
56
- this[_a2] = true;
57
- // used in isInstance
58
- this.name = name;
59
- this.type = "authentication_error";
60
- }
61
- static isInstance(error) {
62
- return GatewayError.hasMarker(error) && symbol2 in error;
63
- }
64
- /**
65
- * Creates a contextual error message when authentication fails
66
- */
67
- static createContextualError({
68
- apiKeyProvided,
69
- oidcTokenProvided,
70
- statusCode = 401,
71
- cause,
72
- generationId
73
- }) {
74
- let contextualMessage;
75
- if (apiKeyProvided) {
76
- contextualMessage = `AI Gateway authentication failed: Invalid API key.
77
-
78
- Create a new API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
79
-
80
- Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.`;
81
- } else if (oidcTokenProvided) {
82
- contextualMessage = `AI Gateway authentication failed: Invalid OIDC token.
83
-
84
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.
85
-
86
- Alternatively, use an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys`;
87
- } else {
88
- contextualMessage = `AI Gateway authentication failed: No authentication provided.
89
-
90
- Option 1 - API key:
91
- Create an API key: https://vercel.com/d?to=%2F%5Bteam%5D%2F%7E%2Fai%2Fapi-keys
92
- Provide via 'apiKey' option or 'AI_GATEWAY_API_KEY' environment variable.
93
-
94
- Option 2 - OIDC token:
95
- Run 'npx vercel link' to link your project, then 'vc env pull' to fetch the token.`;
96
- }
97
- return new _GatewayAuthenticationError({
98
- message: contextualMessage,
99
- statusCode,
100
- cause,
101
- generationId
102
- });
103
- }
104
- };
105
-
106
- // src/errors/gateway-invalid-request-error.ts
107
- var name2 = "GatewayInvalidRequestError";
108
- var marker3 = `vercel.ai.gateway.error.${name2}`;
109
- var symbol3 = Symbol.for(marker3);
110
- var _a3, _b3;
111
- var GatewayInvalidRequestError = class extends (_b3 = GatewayError, _a3 = symbol3, _b3) {
112
- constructor({
113
- message = "Invalid request",
114
- statusCode = 400,
115
- cause,
116
- generationId
117
- } = {}) {
118
- super({ message, statusCode, cause, generationId });
119
- this[_a3] = true;
120
- // used in isInstance
121
- this.name = name2;
122
- this.type = "invalid_request_error";
123
- }
124
- static isInstance(error) {
125
- return GatewayError.hasMarker(error) && symbol3 in error;
126
- }
127
- };
128
-
129
- // src/errors/gateway-rate-limit-error.ts
130
- var name3 = "GatewayRateLimitError";
131
- var marker4 = `vercel.ai.gateway.error.${name3}`;
132
- var symbol4 = Symbol.for(marker4);
133
- var _a4, _b4;
134
- var GatewayRateLimitError = class extends (_b4 = GatewayError, _a4 = symbol4, _b4) {
135
- constructor({
136
- message = "Rate limit exceeded",
137
- statusCode = 429,
138
- cause,
139
- generationId
140
- } = {}) {
141
- super({ message, statusCode, cause, generationId });
142
- this[_a4] = true;
143
- // used in isInstance
144
- this.name = name3;
145
- this.type = "rate_limit_exceeded";
146
- }
147
- static isInstance(error) {
148
- return GatewayError.hasMarker(error) && symbol4 in error;
149
- }
150
- };
151
-
152
- // src/errors/gateway-model-not-found-error.ts
153
- import { z } from "zod/v4";
154
- import { lazySchema, zodSchema } from "@ai-sdk/provider-utils";
155
- var name4 = "GatewayModelNotFoundError";
156
- var marker5 = `vercel.ai.gateway.error.${name4}`;
157
- var symbol5 = Symbol.for(marker5);
158
- var modelNotFoundParamSchema = lazySchema(
159
- () => zodSchema(
160
- z.object({
161
- modelId: z.string()
162
- })
163
- )
164
- );
165
- var _a5, _b5;
166
- var GatewayModelNotFoundError = class extends (_b5 = GatewayError, _a5 = symbol5, _b5) {
167
- constructor({
168
- message = "Model not found",
169
- statusCode = 404,
170
- modelId,
171
- cause,
172
- generationId
173
- } = {}) {
174
- super({ message, statusCode, cause, generationId });
175
- this[_a5] = true;
176
- // used in isInstance
177
- this.name = name4;
178
- this.type = "model_not_found";
179
- this.modelId = modelId;
180
- }
181
- static isInstance(error) {
182
- return GatewayError.hasMarker(error) && symbol5 in error;
183
- }
184
- };
185
-
186
- // src/errors/gateway-internal-server-error.ts
187
- var name5 = "GatewayInternalServerError";
188
- var marker6 = `vercel.ai.gateway.error.${name5}`;
189
- var symbol6 = Symbol.for(marker6);
190
- var _a6, _b6;
191
- var GatewayInternalServerError = class extends (_b6 = GatewayError, _a6 = symbol6, _b6) {
192
- constructor({
193
- message = "Internal server error",
194
- statusCode = 500,
195
- cause,
196
- generationId
197
- } = {}) {
198
- super({ message, statusCode, cause, generationId });
199
- this[_a6] = true;
200
- // used in isInstance
201
- this.name = name5;
202
- this.type = "internal_server_error";
203
- }
204
- static isInstance(error) {
205
- return GatewayError.hasMarker(error) && symbol6 in error;
206
- }
207
- };
208
-
209
- // src/errors/gateway-response-error.ts
210
- var name6 = "GatewayResponseError";
211
- var marker7 = `vercel.ai.gateway.error.${name6}`;
212
- var symbol7 = Symbol.for(marker7);
213
- var _a7, _b7;
214
- var GatewayResponseError = class extends (_b7 = GatewayError, _a7 = symbol7, _b7) {
215
- constructor({
216
- message = "Invalid response from Gateway",
217
- statusCode = 502,
218
- response,
219
- validationError,
220
- cause,
221
- generationId
222
- } = {}) {
223
- super({ message, statusCode, cause, generationId });
224
- this[_a7] = true;
225
- // used in isInstance
226
- this.name = name6;
227
- this.type = "response_error";
228
- this.response = response;
229
- this.validationError = validationError;
230
- }
231
- static isInstance(error) {
232
- return GatewayError.hasMarker(error) && symbol7 in error;
233
- }
234
- };
235
-
236
- // src/errors/create-gateway-error.ts
237
- import {
238
- lazySchema as lazySchema2,
239
- safeValidateTypes,
240
- zodSchema as zodSchema2
241
- } from "@ai-sdk/provider-utils";
242
- async function createGatewayErrorFromResponse({
243
- response,
244
- statusCode,
245
- defaultMessage = "Gateway request failed",
246
- cause,
247
- authMethod
248
- }) {
249
- var _a9;
250
- const parseResult = await safeValidateTypes({
251
- value: response,
252
- schema: gatewayErrorResponseSchema
253
- });
254
- if (!parseResult.success) {
255
- const rawGenerationId = typeof response === "object" && response !== null && "generationId" in response ? response.generationId : void 0;
256
- return new GatewayResponseError({
257
- message: `Invalid error response format: ${defaultMessage}`,
258
- statusCode,
259
- response,
260
- validationError: parseResult.error,
261
- cause,
262
- generationId: rawGenerationId
263
- });
264
- }
265
- const validatedResponse = parseResult.value;
266
- const errorType = validatedResponse.error.type;
267
- const message = validatedResponse.error.message;
268
- const generationId = (_a9 = validatedResponse.generationId) != null ? _a9 : void 0;
269
- switch (errorType) {
270
- case "authentication_error":
271
- return GatewayAuthenticationError.createContextualError({
272
- apiKeyProvided: authMethod === "api-key",
273
- oidcTokenProvided: authMethod === "oidc",
274
- statusCode,
275
- cause,
276
- generationId
277
- });
278
- case "invalid_request_error":
279
- return new GatewayInvalidRequestError({
280
- message,
281
- statusCode,
282
- cause,
283
- generationId
284
- });
285
- case "rate_limit_exceeded":
286
- return new GatewayRateLimitError({
287
- message,
288
- statusCode,
289
- cause,
290
- generationId
291
- });
292
- case "model_not_found": {
293
- const modelResult = await safeValidateTypes({
294
- value: validatedResponse.error.param,
295
- schema: modelNotFoundParamSchema
296
- });
297
- return new GatewayModelNotFoundError({
298
- message,
299
- statusCode,
300
- modelId: modelResult.success ? modelResult.value.modelId : void 0,
301
- cause,
302
- generationId
303
- });
304
- }
305
- case "internal_server_error":
306
- return new GatewayInternalServerError({
307
- message,
308
- statusCode,
309
- cause,
310
- generationId
311
- });
312
- default:
313
- return new GatewayInternalServerError({
314
- message,
315
- statusCode,
316
- cause,
317
- generationId
318
- });
319
- }
320
- }
321
- var gatewayErrorResponseSchema = lazySchema2(
322
- () => zodSchema2(
323
- z2.object({
324
- error: z2.object({
325
- message: z2.string(),
326
- type: z2.string().nullish(),
327
- param: z2.unknown().nullish(),
328
- code: z2.union([z2.string(), z2.number()]).nullish()
329
- }),
330
- generationId: z2.string().nullish()
331
- })
332
- )
333
- );
334
-
335
- // src/errors/gateway-timeout-error.ts
336
- var name7 = "GatewayTimeoutError";
337
- var marker8 = `vercel.ai.gateway.error.${name7}`;
338
- var symbol8 = Symbol.for(marker8);
339
- var _a8, _b8;
340
- var GatewayTimeoutError = class _GatewayTimeoutError extends (_b8 = GatewayError, _a8 = symbol8, _b8) {
341
- constructor({
342
- message = "Request timed out",
343
- statusCode = 408,
344
- cause,
345
- generationId
346
- } = {}) {
347
- super({ message, statusCode, cause, generationId });
348
- this[_a8] = true;
349
- // used in isInstance
350
- this.name = name7;
351
- this.type = "timeout_error";
352
- }
353
- static isInstance(error) {
354
- return GatewayError.hasMarker(error) && symbol8 in error;
355
- }
356
- /**
357
- * Creates a helpful timeout error message with troubleshooting guidance
358
- */
359
- static createTimeoutError({
360
- originalMessage,
361
- statusCode = 408,
362
- cause,
363
- generationId
364
- }) {
365
- const message = `Gateway request timed out: ${originalMessage}
366
-
367
- This is a client-side timeout. To resolve this, increase your timeout configuration: https://vercel.com/docs/ai-gateway/capabilities/video-generation#extending-timeouts-for-node.js`;
368
- return new _GatewayTimeoutError({
369
- message,
370
- statusCode,
371
- cause,
372
- generationId
373
- });
374
- }
375
- };
376
-
377
- // src/errors/as-gateway-error.ts
378
- function isTimeoutError(error) {
379
- if (!(error instanceof Error)) {
380
- return false;
381
- }
382
- const errorCode = error.code;
383
- if (typeof errorCode === "string") {
384
- const undiciTimeoutCodes = [
385
- "UND_ERR_HEADERS_TIMEOUT",
386
- "UND_ERR_BODY_TIMEOUT",
387
- "UND_ERR_CONNECT_TIMEOUT"
388
- ];
389
- return undiciTimeoutCodes.includes(errorCode);
390
- }
391
- return false;
392
- }
393
- async function asGatewayError(error, authMethod) {
394
- var _a9;
395
- if (GatewayError.isInstance(error)) {
396
- return error;
397
- }
398
- if (isTimeoutError(error)) {
399
- return GatewayTimeoutError.createTimeoutError({
400
- originalMessage: error instanceof Error ? error.message : "Unknown error",
401
- cause: error
402
- });
403
- }
404
- if (APICallError.isInstance(error)) {
405
- if (error.cause && isTimeoutError(error.cause)) {
406
- return GatewayTimeoutError.createTimeoutError({
407
- originalMessage: error.message,
408
- cause: error
409
- });
410
- }
411
- return await createGatewayErrorFromResponse({
412
- response: extractApiCallResponse(error),
413
- statusCode: (_a9 = error.statusCode) != null ? _a9 : 500,
414
- defaultMessage: "Gateway request failed",
415
- cause: error,
416
- authMethod
417
- });
418
- }
419
- return await createGatewayErrorFromResponse({
420
- response: {},
421
- statusCode: 500,
422
- defaultMessage: error instanceof Error ? `Gateway request failed: ${error.message}` : "Unknown Gateway error",
423
- cause: error,
424
- authMethod
425
- });
426
- }
427
-
428
- // src/errors/extract-api-call-response.ts
429
- function extractApiCallResponse(error) {
430
- if (error.data !== void 0) {
431
- return error.data;
432
- }
433
- if (error.responseBody != null) {
434
- try {
435
- return JSON.parse(error.responseBody);
436
- } catch (e) {
437
- return error.responseBody;
438
- }
439
- }
440
- return {};
441
- }
442
-
443
- // src/errors/parse-auth-method.ts
444
- import { z as z3 } from "zod/v4";
445
- import {
446
- lazySchema as lazySchema3,
447
- safeValidateTypes as safeValidateTypes2,
448
- zodSchema as zodSchema3
449
- } from "@ai-sdk/provider-utils";
450
- var GATEWAY_AUTH_METHOD_HEADER = "ai-gateway-auth-method";
451
- async function parseAuthMethod(headers) {
452
- const result = await safeValidateTypes2({
453
- value: headers[GATEWAY_AUTH_METHOD_HEADER],
454
- schema: gatewayAuthMethodSchema
455
- });
456
- return result.success ? result.value : void 0;
457
- }
458
- var gatewayAuthMethodSchema = lazySchema3(
459
- () => zodSchema3(z3.union([z3.literal("api-key"), z3.literal("oidc")]))
460
- );
461
-
462
- // src/gateway-fetch-metadata.ts
463
- import {
464
- createJsonErrorResponseHandler,
465
- createJsonResponseHandler,
466
- getFromApi,
467
- lazySchema as lazySchema4,
468
- resolve,
469
- zodSchema as zodSchema4
470
- } from "@ai-sdk/provider-utils";
471
- import { z as z4 } from "zod/v4";
472
- var GatewayFetchMetadata = class {
473
- constructor(config) {
474
- this.config = config;
475
- }
476
- async getAvailableModels() {
477
- try {
478
- const { value } = await getFromApi({
479
- url: `${this.config.baseURL}/config`,
480
- headers: await resolve(this.config.headers()),
481
- successfulResponseHandler: createJsonResponseHandler(
482
- gatewayAvailableModelsResponseSchema
483
- ),
484
- failedResponseHandler: createJsonErrorResponseHandler({
485
- errorSchema: z4.any(),
486
- errorToMessage: (data) => data
487
- }),
488
- fetch: this.config.fetch
489
- });
490
- return value;
491
- } catch (error) {
492
- throw await asGatewayError(error);
493
- }
494
- }
495
- async getCredits() {
496
- try {
497
- const baseUrl = new URL(this.config.baseURL);
498
- const { value } = await getFromApi({
499
- url: `${baseUrl.origin}/v1/credits`,
500
- headers: await resolve(this.config.headers()),
501
- successfulResponseHandler: createJsonResponseHandler(
502
- gatewayCreditsResponseSchema
503
- ),
504
- failedResponseHandler: createJsonErrorResponseHandler({
505
- errorSchema: z4.any(),
506
- errorToMessage: (data) => data
507
- }),
508
- fetch: this.config.fetch
509
- });
510
- return value;
511
- } catch (error) {
512
- throw await asGatewayError(error);
513
- }
514
- }
515
- };
516
- var gatewayAvailableModelsResponseSchema = lazySchema4(
517
- () => zodSchema4(
518
- z4.object({
519
- models: z4.array(
520
- z4.object({
521
- id: z4.string(),
522
- name: z4.string(),
523
- description: z4.string().nullish(),
524
- pricing: z4.object({
525
- input: z4.string(),
526
- output: z4.string(),
527
- input_cache_read: z4.string().nullish(),
528
- input_cache_write: z4.string().nullish()
529
- }).transform(
530
- ({ input, output, input_cache_read, input_cache_write }) => ({
531
- input,
532
- output,
533
- ...input_cache_read ? { cachedInputTokens: input_cache_read } : {},
534
- ...input_cache_write ? { cacheCreationInputTokens: input_cache_write } : {}
535
- })
536
- ).nullish(),
537
- specification: z4.object({
538
- specificationVersion: z4.literal("v4"),
539
- provider: z4.string(),
540
- modelId: z4.string()
541
- }),
542
- modelType: z4.enum(["embedding", "image", "language", "video"]).nullish()
543
- })
544
- )
545
- })
546
- )
547
- );
548
- var gatewayCreditsResponseSchema = lazySchema4(
549
- () => zodSchema4(
550
- z4.object({
551
- balance: z4.string(),
552
- total_used: z4.string()
553
- }).transform(({ balance, total_used }) => ({
554
- balance,
555
- totalUsed: total_used
556
- }))
557
- )
558
- );
559
-
560
- // src/gateway-spend-report.ts
561
- import {
562
- createJsonErrorResponseHandler as createJsonErrorResponseHandler2,
563
- createJsonResponseHandler as createJsonResponseHandler2,
564
- getFromApi as getFromApi2,
565
- lazySchema as lazySchema5,
566
- resolve as resolve2,
567
- zodSchema as zodSchema5
568
- } from "@ai-sdk/provider-utils";
569
- import { z as z5 } from "zod/v4";
570
- var GatewaySpendReport = class {
571
- constructor(config) {
572
- this.config = config;
573
- }
574
- async getSpendReport(params) {
575
- try {
576
- const baseUrl = new URL(this.config.baseURL);
577
- const searchParams = new URLSearchParams();
578
- searchParams.set("start_date", params.startDate);
579
- searchParams.set("end_date", params.endDate);
580
- if (params.groupBy) {
581
- searchParams.set("group_by", params.groupBy);
582
- }
583
- if (params.datePart) {
584
- searchParams.set("date_part", params.datePart);
585
- }
586
- if (params.userId) {
587
- searchParams.set("user_id", params.userId);
588
- }
589
- if (params.model) {
590
- searchParams.set("model", params.model);
591
- }
592
- if (params.provider) {
593
- searchParams.set("provider", params.provider);
594
- }
595
- if (params.credentialType) {
596
- searchParams.set("credential_type", params.credentialType);
597
- }
598
- if (params.tags && params.tags.length > 0) {
599
- searchParams.set("tags", params.tags.join(","));
600
- }
601
- const { value } = await getFromApi2({
602
- url: `${baseUrl.origin}/v1/report?${searchParams.toString()}`,
603
- headers: await resolve2(this.config.headers()),
604
- successfulResponseHandler: createJsonResponseHandler2(
605
- gatewaySpendReportResponseSchema
606
- ),
607
- failedResponseHandler: createJsonErrorResponseHandler2({
608
- errorSchema: z5.any(),
609
- errorToMessage: (data) => data
610
- }),
611
- fetch: this.config.fetch
612
- });
613
- return value;
614
- } catch (error) {
615
- throw await asGatewayError(error);
616
- }
617
- }
618
- };
619
- var gatewaySpendReportResponseSchema = lazySchema5(
620
- () => zodSchema5(
621
- z5.object({
622
- results: z5.array(
623
- z5.object({
624
- day: z5.string().optional(),
625
- hour: z5.string().optional(),
626
- user: z5.string().optional(),
627
- model: z5.string().optional(),
628
- tag: z5.string().optional(),
629
- provider: z5.string().optional(),
630
- credential_type: z5.enum(["byok", "system"]).optional(),
631
- total_cost: z5.number(),
632
- market_cost: z5.number().optional(),
633
- input_tokens: z5.number().optional(),
634
- output_tokens: z5.number().optional(),
635
- cached_input_tokens: z5.number().optional(),
636
- cache_creation_input_tokens: z5.number().optional(),
637
- reasoning_tokens: z5.number().optional(),
638
- request_count: z5.number().optional()
639
- }).transform(
640
- ({
641
- credential_type,
642
- total_cost,
643
- market_cost,
644
- input_tokens,
645
- output_tokens,
646
- cached_input_tokens,
647
- cache_creation_input_tokens,
648
- reasoning_tokens,
649
- request_count,
650
- ...rest
651
- }) => ({
652
- ...rest,
653
- ...credential_type !== void 0 ? { credentialType: credential_type } : {},
654
- totalCost: total_cost,
655
- ...market_cost !== void 0 ? { marketCost: market_cost } : {},
656
- ...input_tokens !== void 0 ? { inputTokens: input_tokens } : {},
657
- ...output_tokens !== void 0 ? { outputTokens: output_tokens } : {},
658
- ...cached_input_tokens !== void 0 ? { cachedInputTokens: cached_input_tokens } : {},
659
- ...cache_creation_input_tokens !== void 0 ? { cacheCreationInputTokens: cache_creation_input_tokens } : {},
660
- ...reasoning_tokens !== void 0 ? { reasoningTokens: reasoning_tokens } : {},
661
- ...request_count !== void 0 ? { requestCount: request_count } : {}
662
- })
663
- )
664
- )
665
- })
666
- )
667
- );
668
-
669
- // src/gateway-generation-info.ts
670
- import {
671
- createJsonErrorResponseHandler as createJsonErrorResponseHandler3,
672
- createJsonResponseHandler as createJsonResponseHandler3,
673
- getFromApi as getFromApi3,
674
- lazySchema as lazySchema6,
675
- resolve as resolve3,
676
- zodSchema as zodSchema6
677
- } from "@ai-sdk/provider-utils";
678
- import { z as z6 } from "zod/v4";
679
- var GatewayGenerationInfoFetcher = class {
680
- constructor(config) {
681
- this.config = config;
682
- }
683
- async getGenerationInfo(params) {
684
- try {
685
- const baseUrl = new URL(this.config.baseURL);
686
- const { value } = await getFromApi3({
687
- url: `${baseUrl.origin}/v1/generation?id=${encodeURIComponent(params.id)}`,
688
- headers: await resolve3(this.config.headers()),
689
- successfulResponseHandler: createJsonResponseHandler3(
690
- gatewayGenerationInfoResponseSchema
691
- ),
692
- failedResponseHandler: createJsonErrorResponseHandler3({
693
- errorSchema: z6.any(),
694
- errorToMessage: (data) => data
695
- }),
696
- fetch: this.config.fetch
697
- });
698
- return value;
699
- } catch (error) {
700
- throw await asGatewayError(error);
701
- }
702
- }
703
- };
704
- var gatewayGenerationInfoResponseSchema = lazySchema6(
705
- () => zodSchema6(
706
- z6.object({
707
- data: z6.object({
708
- id: z6.string(),
709
- total_cost: z6.number(),
710
- upstream_inference_cost: z6.number(),
711
- usage: z6.number(),
712
- created_at: z6.string(),
713
- model: z6.string(),
714
- is_byok: z6.boolean(),
715
- provider_name: z6.string(),
716
- streamed: z6.boolean(),
717
- finish_reason: z6.string(),
718
- latency: z6.number(),
719
- generation_time: z6.number(),
720
- native_tokens_prompt: z6.number(),
721
- native_tokens_completion: z6.number(),
722
- native_tokens_reasoning: z6.number(),
723
- native_tokens_cached: z6.number(),
724
- native_tokens_cache_creation: z6.number(),
725
- billable_web_search_calls: z6.number()
726
- }).transform(
727
- ({
728
- total_cost,
729
- upstream_inference_cost,
730
- created_at,
731
- is_byok,
732
- provider_name,
733
- finish_reason,
734
- generation_time,
735
- native_tokens_prompt,
736
- native_tokens_completion,
737
- native_tokens_reasoning,
738
- native_tokens_cached,
739
- native_tokens_cache_creation,
740
- billable_web_search_calls,
741
- ...rest
742
- }) => ({
743
- ...rest,
744
- totalCost: total_cost,
745
- upstreamInferenceCost: upstream_inference_cost,
746
- createdAt: created_at,
747
- isByok: is_byok,
748
- providerName: provider_name,
749
- finishReason: finish_reason,
750
- generationTime: generation_time,
751
- promptTokens: native_tokens_prompt,
752
- completionTokens: native_tokens_completion,
753
- reasoningTokens: native_tokens_reasoning,
754
- cachedTokens: native_tokens_cached,
755
- cacheCreationTokens: native_tokens_cache_creation,
756
- billableWebSearchCalls: billable_web_search_calls
757
- })
758
- )
759
- }).transform(({ data }) => data)
760
- )
761
- );
762
-
763
- // src/gateway-language-model.ts
764
- import {
765
- combineHeaders,
766
- createEventSourceResponseHandler,
767
- createJsonErrorResponseHandler as createJsonErrorResponseHandler4,
768
- createJsonResponseHandler as createJsonResponseHandler4,
769
- postJsonToApi,
770
- resolve as resolve4
771
- } from "@ai-sdk/provider-utils";
772
- import { z as z7 } from "zod/v4";
773
- var GatewayLanguageModel = class {
774
- constructor(modelId, config) {
775
- this.modelId = modelId;
776
- this.config = config;
777
- this.specificationVersion = "v4";
778
- this.supportedUrls = { "*/*": [/.*/] };
779
- }
780
- get provider() {
781
- return this.config.provider;
782
- }
783
- async getArgs(options) {
784
- const { abortSignal: _abortSignal, ...optionsWithoutSignal } = options;
785
- return {
786
- args: this.maybeEncodeFileParts(optionsWithoutSignal),
787
- warnings: []
788
- };
789
- }
790
- async doGenerate(options) {
791
- const { args, warnings } = await this.getArgs(options);
792
- const { abortSignal } = options;
793
- const resolvedHeaders = await resolve4(this.config.headers());
794
- try {
795
- const {
796
- responseHeaders,
797
- value: responseBody,
798
- rawValue: rawResponse
799
- } = await postJsonToApi({
800
- url: this.getUrl(),
801
- headers: combineHeaders(
802
- resolvedHeaders,
803
- options.headers,
804
- this.getModelConfigHeaders(this.modelId, false),
805
- await resolve4(this.config.o11yHeaders)
806
- ),
807
- body: args,
808
- successfulResponseHandler: createJsonResponseHandler4(z7.any()),
809
- failedResponseHandler: createJsonErrorResponseHandler4({
810
- errorSchema: z7.any(),
811
- errorToMessage: (data) => data
812
- }),
813
- ...abortSignal && { abortSignal },
814
- fetch: this.config.fetch
815
- });
816
- return {
817
- ...responseBody,
818
- request: { body: args },
819
- response: { headers: responseHeaders, body: rawResponse },
820
- warnings
821
- };
822
- } catch (error) {
823
- throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
824
- }
825
- }
826
- async doStream(options) {
827
- const { args, warnings } = await this.getArgs(options);
828
- const { abortSignal } = options;
829
- const resolvedHeaders = await resolve4(this.config.headers());
830
- try {
831
- const { value: response, responseHeaders } = await postJsonToApi({
832
- url: this.getUrl(),
833
- headers: combineHeaders(
834
- resolvedHeaders,
835
- options.headers,
836
- this.getModelConfigHeaders(this.modelId, true),
837
- await resolve4(this.config.o11yHeaders)
838
- ),
839
- body: args,
840
- successfulResponseHandler: createEventSourceResponseHandler(z7.any()),
841
- failedResponseHandler: createJsonErrorResponseHandler4({
842
- errorSchema: z7.any(),
843
- errorToMessage: (data) => data
844
- }),
845
- ...abortSignal && { abortSignal },
846
- fetch: this.config.fetch
847
- });
848
- return {
849
- stream: response.pipeThrough(
850
- new TransformStream({
851
- start(controller) {
852
- if (warnings.length > 0) {
853
- controller.enqueue({ type: "stream-start", warnings });
854
- }
855
- },
856
- transform(chunk, controller) {
857
- if (chunk.success) {
858
- const streamPart = chunk.value;
859
- if (streamPart.type === "raw" && !options.includeRawChunks) {
860
- return;
861
- }
862
- if (streamPart.type === "response-metadata" && streamPart.timestamp && typeof streamPart.timestamp === "string") {
863
- streamPart.timestamp = new Date(streamPart.timestamp);
864
- }
865
- controller.enqueue(streamPart);
866
- } else {
867
- controller.error(
868
- chunk.error
869
- );
870
- }
871
- }
872
- })
873
- ),
874
- request: { body: args },
875
- response: { headers: responseHeaders }
876
- };
877
- } catch (error) {
878
- throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
879
- }
880
- }
881
- isFilePart(part) {
882
- return part && typeof part === "object" && "type" in part && part.type === "file";
883
- }
884
- /**
885
- * Encodes file parts in the prompt to base64. Mutates the passed options
886
- * instance directly to avoid copying the file data.
887
- * @param options - The options to encode.
888
- * @returns The options with the file parts encoded.
889
- */
890
- maybeEncodeFileParts(options) {
891
- for (const message of options.prompt) {
892
- for (const part of message.content) {
893
- if (this.isFilePart(part)) {
894
- const filePart = part;
895
- if (filePart.data instanceof Uint8Array) {
896
- const buffer = Uint8Array.from(filePart.data);
897
- const base64Data = Buffer.from(buffer).toString("base64");
898
- filePart.data = new URL(
899
- `data:${filePart.mediaType || "application/octet-stream"};base64,${base64Data}`
900
- );
901
- }
902
- }
903
- }
904
- }
905
- return options;
906
- }
907
- getUrl() {
908
- return `${this.config.baseURL}/language-model`;
909
- }
910
- getModelConfigHeaders(modelId, streaming) {
911
- return {
912
- "ai-language-model-specification-version": "4",
913
- "ai-language-model-id": modelId,
914
- "ai-language-model-streaming": String(streaming)
915
- };
916
- }
917
- };
918
-
919
- // src/gateway-embedding-model.ts
920
- import {
921
- combineHeaders as combineHeaders2,
922
- createJsonErrorResponseHandler as createJsonErrorResponseHandler5,
923
- createJsonResponseHandler as createJsonResponseHandler5,
924
- lazySchema as lazySchema7,
925
- postJsonToApi as postJsonToApi2,
926
- resolve as resolve5,
927
- zodSchema as zodSchema7
928
- } from "@ai-sdk/provider-utils";
929
- import { z as z8 } from "zod/v4";
930
- var GatewayEmbeddingModel = class {
931
- constructor(modelId, config) {
932
- this.modelId = modelId;
933
- this.config = config;
934
- this.specificationVersion = "v4";
935
- this.maxEmbeddingsPerCall = 2048;
936
- this.supportsParallelCalls = true;
937
- }
938
- get provider() {
939
- return this.config.provider;
940
- }
941
- async doEmbed({
942
- values,
943
- headers,
944
- abortSignal,
945
- providerOptions
946
- }) {
947
- var _a9;
948
- const resolvedHeaders = await resolve5(this.config.headers());
949
- try {
950
- const {
951
- responseHeaders,
952
- value: responseBody,
953
- rawValue
954
- } = await postJsonToApi2({
955
- url: this.getUrl(),
956
- headers: combineHeaders2(
957
- resolvedHeaders,
958
- headers != null ? headers : {},
959
- this.getModelConfigHeaders(),
960
- await resolve5(this.config.o11yHeaders)
961
- ),
962
- body: {
963
- values,
964
- ...providerOptions ? { providerOptions } : {}
965
- },
966
- successfulResponseHandler: createJsonResponseHandler5(
967
- gatewayEmbeddingResponseSchema
968
- ),
969
- failedResponseHandler: createJsonErrorResponseHandler5({
970
- errorSchema: z8.any(),
971
- errorToMessage: (data) => data
972
- }),
973
- ...abortSignal && { abortSignal },
974
- fetch: this.config.fetch
975
- });
976
- return {
977
- embeddings: responseBody.embeddings,
978
- usage: (_a9 = responseBody.usage) != null ? _a9 : void 0,
979
- providerMetadata: responseBody.providerMetadata,
980
- response: { headers: responseHeaders, body: rawValue },
981
- warnings: []
982
- };
983
- } catch (error) {
984
- throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
985
- }
986
- }
987
- getUrl() {
988
- return `${this.config.baseURL}/embedding-model`;
989
- }
990
- getModelConfigHeaders() {
991
- return {
992
- "ai-embedding-model-specification-version": "4",
993
- "ai-model-id": this.modelId
994
- };
995
- }
996
- };
997
- var gatewayEmbeddingResponseSchema = lazySchema7(
998
- () => zodSchema7(
999
- z8.object({
1000
- embeddings: z8.array(z8.array(z8.number())),
1001
- usage: z8.object({ tokens: z8.number() }).nullish(),
1002
- providerMetadata: z8.record(z8.string(), z8.record(z8.string(), z8.unknown())).optional()
1003
- })
1004
- )
1005
- );
1006
-
1007
- // src/gateway-image-model.ts
1008
- import {
1009
- combineHeaders as combineHeaders3,
1010
- convertUint8ArrayToBase64,
1011
- createJsonResponseHandler as createJsonResponseHandler6,
1012
- createJsonErrorResponseHandler as createJsonErrorResponseHandler6,
1013
- postJsonToApi as postJsonToApi3,
1014
- resolve as resolve6
1015
- } from "@ai-sdk/provider-utils";
1016
- import { z as z9 } from "zod/v4";
1017
- var GatewayImageModel = class {
1018
- constructor(modelId, config) {
1019
- this.modelId = modelId;
1020
- this.config = config;
1021
- this.specificationVersion = "v4";
1022
- // Set a very large number to prevent client-side splitting of requests
1023
- this.maxImagesPerCall = Number.MAX_SAFE_INTEGER;
1024
- }
1025
- get provider() {
1026
- return this.config.provider;
1027
- }
1028
- async doGenerate({
1029
- prompt,
1030
- n,
1031
- size,
1032
- aspectRatio,
1033
- seed,
1034
- files,
1035
- mask,
1036
- providerOptions,
1037
- headers,
1038
- abortSignal
1039
- }) {
1040
- var _a9, _b9, _c, _d;
1041
- const resolvedHeaders = await resolve6(this.config.headers());
1042
- try {
1043
- const { responseHeaders, value: responseBody } = await postJsonToApi3({
1044
- url: this.getUrl(),
1045
- headers: combineHeaders3(
1046
- resolvedHeaders,
1047
- headers != null ? headers : {},
1048
- this.getModelConfigHeaders(),
1049
- await resolve6(this.config.o11yHeaders)
1050
- ),
1051
- body: {
1052
- prompt,
1053
- n,
1054
- ...size && { size },
1055
- ...aspectRatio && { aspectRatio },
1056
- ...seed && { seed },
1057
- ...providerOptions && { providerOptions },
1058
- ...files && {
1059
- files: files.map((file) => maybeEncodeImageFile(file))
1060
- },
1061
- ...mask && { mask: maybeEncodeImageFile(mask) }
1062
- },
1063
- successfulResponseHandler: createJsonResponseHandler6(
1064
- gatewayImageResponseSchema
1065
- ),
1066
- failedResponseHandler: createJsonErrorResponseHandler6({
1067
- errorSchema: z9.any(),
1068
- errorToMessage: (data) => data
1069
- }),
1070
- ...abortSignal && { abortSignal },
1071
- fetch: this.config.fetch
1072
- });
1073
- return {
1074
- images: responseBody.images,
1075
- // Always base64 strings from server
1076
- warnings: (_a9 = responseBody.warnings) != null ? _a9 : [],
1077
- providerMetadata: responseBody.providerMetadata,
1078
- response: {
1079
- timestamp: /* @__PURE__ */ new Date(),
1080
- modelId: this.modelId,
1081
- headers: responseHeaders
1082
- },
1083
- ...responseBody.usage != null && {
1084
- usage: {
1085
- inputTokens: (_b9 = responseBody.usage.inputTokens) != null ? _b9 : void 0,
1086
- outputTokens: (_c = responseBody.usage.outputTokens) != null ? _c : void 0,
1087
- totalTokens: (_d = responseBody.usage.totalTokens) != null ? _d : void 0
1088
- }
1089
- }
1090
- };
1091
- } catch (error) {
1092
- throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
1093
- }
1094
- }
1095
- getUrl() {
1096
- return `${this.config.baseURL}/image-model`;
1097
- }
1098
- getModelConfigHeaders() {
1099
- return {
1100
- "ai-image-model-specification-version": "4",
1101
- "ai-model-id": this.modelId
1102
- };
1103
- }
1104
- };
1105
- function maybeEncodeImageFile(file) {
1106
- if (file.type === "file" && file.data instanceof Uint8Array) {
1107
- return {
1108
- ...file,
1109
- data: convertUint8ArrayToBase64(file.data)
1110
- };
1111
- }
1112
- return file;
1113
- }
1114
- var providerMetadataEntrySchema = z9.object({
1115
- images: z9.array(z9.unknown()).optional()
1116
- }).catchall(z9.unknown());
1117
- var gatewayImageWarningSchema = z9.discriminatedUnion("type", [
1118
- z9.object({
1119
- type: z9.literal("unsupported"),
1120
- feature: z9.string(),
1121
- details: z9.string().optional()
1122
- }),
1123
- z9.object({
1124
- type: z9.literal("compatibility"),
1125
- feature: z9.string(),
1126
- details: z9.string().optional()
1127
- }),
1128
- z9.object({
1129
- type: z9.literal("other"),
1130
- message: z9.string()
1131
- })
1132
- ]);
1133
- var gatewayImageUsageSchema = z9.object({
1134
- inputTokens: z9.number().nullish(),
1135
- outputTokens: z9.number().nullish(),
1136
- totalTokens: z9.number().nullish()
1137
- });
1138
- var gatewayImageResponseSchema = z9.object({
1139
- images: z9.array(z9.string()),
1140
- // Always base64 strings over the wire
1141
- warnings: z9.array(gatewayImageWarningSchema).optional(),
1142
- providerMetadata: z9.record(z9.string(), providerMetadataEntrySchema).optional(),
1143
- usage: gatewayImageUsageSchema.optional()
1144
- });
1145
-
1146
- // src/gateway-video-model.ts
1147
- import { APICallError as APICallError2 } from "@ai-sdk/provider";
1148
- import {
1149
- combineHeaders as combineHeaders4,
1150
- convertUint8ArrayToBase64 as convertUint8ArrayToBase642,
1151
- createJsonErrorResponseHandler as createJsonErrorResponseHandler7,
1152
- parseJsonEventStream,
1153
- postJsonToApi as postJsonToApi4,
1154
- resolve as resolve7
1155
- } from "@ai-sdk/provider-utils";
1156
- import { z as z10 } from "zod/v4";
1157
- var GatewayVideoModel = class {
1158
- constructor(modelId, config) {
1159
- this.modelId = modelId;
1160
- this.config = config;
1161
- this.specificationVersion = "v4";
1162
- // Set a very large number to prevent client-side splitting of requests
1163
- this.maxVideosPerCall = Number.MAX_SAFE_INTEGER;
1164
- }
1165
- get provider() {
1166
- return this.config.provider;
1167
- }
1168
- async doGenerate({
1169
- prompt,
1170
- n,
1171
- aspectRatio,
1172
- resolution,
1173
- duration,
1174
- fps,
1175
- seed,
1176
- image,
1177
- providerOptions,
1178
- headers,
1179
- abortSignal
1180
- }) {
1181
- var _a9;
1182
- const resolvedHeaders = await resolve7(this.config.headers());
1183
- try {
1184
- const { responseHeaders, value: responseBody } = await postJsonToApi4({
1185
- url: this.getUrl(),
1186
- headers: combineHeaders4(
1187
- resolvedHeaders,
1188
- headers != null ? headers : {},
1189
- this.getModelConfigHeaders(),
1190
- await resolve7(this.config.o11yHeaders),
1191
- { accept: "text/event-stream" }
1192
- ),
1193
- body: {
1194
- prompt,
1195
- n,
1196
- ...aspectRatio && { aspectRatio },
1197
- ...resolution && { resolution },
1198
- ...duration && { duration },
1199
- ...fps && { fps },
1200
- ...seed && { seed },
1201
- ...providerOptions && { providerOptions },
1202
- ...image && { image: maybeEncodeVideoFile(image) }
1203
- },
1204
- successfulResponseHandler: async ({
1205
- response,
1206
- url,
1207
- requestBodyValues
1208
- }) => {
1209
- if (response.body == null) {
1210
- throw new APICallError2({
1211
- message: "SSE response body is empty",
1212
- url,
1213
- requestBodyValues,
1214
- statusCode: response.status
1215
- });
1216
- }
1217
- const eventStream = parseJsonEventStream({
1218
- stream: response.body,
1219
- schema: gatewayVideoEventSchema
1220
- });
1221
- const reader = eventStream.getReader();
1222
- const { done, value: parseResult } = await reader.read();
1223
- reader.releaseLock();
1224
- if (done || !parseResult) {
1225
- throw new APICallError2({
1226
- message: "SSE stream ended without a data event",
1227
- url,
1228
- requestBodyValues,
1229
- statusCode: response.status
1230
- });
1231
- }
1232
- if (!parseResult.success) {
1233
- throw new APICallError2({
1234
- message: "Failed to parse video SSE event",
1235
- cause: parseResult.error,
1236
- url,
1237
- requestBodyValues,
1238
- statusCode: response.status
1239
- });
1240
- }
1241
- const event = parseResult.value;
1242
- if (event.type === "error") {
1243
- throw new APICallError2({
1244
- message: event.message,
1245
- statusCode: event.statusCode,
1246
- url,
1247
- requestBodyValues,
1248
- responseHeaders: Object.fromEntries([...response.headers]),
1249
- responseBody: JSON.stringify(event),
1250
- data: {
1251
- error: {
1252
- message: event.message,
1253
- type: event.errorType,
1254
- param: event.param
1255
- }
1256
- }
1257
- });
1258
- }
1259
- return {
1260
- value: {
1261
- videos: event.videos,
1262
- warnings: event.warnings,
1263
- providerMetadata: event.providerMetadata
1264
- },
1265
- responseHeaders: Object.fromEntries([...response.headers])
1266
- };
1267
- },
1268
- failedResponseHandler: createJsonErrorResponseHandler7({
1269
- errorSchema: z10.any(),
1270
- errorToMessage: (data) => data
1271
- }),
1272
- ...abortSignal && { abortSignal },
1273
- fetch: this.config.fetch
1274
- });
1275
- return {
1276
- videos: responseBody.videos,
1277
- warnings: (_a9 = responseBody.warnings) != null ? _a9 : [],
1278
- providerMetadata: responseBody.providerMetadata,
1279
- response: {
1280
- timestamp: /* @__PURE__ */ new Date(),
1281
- modelId: this.modelId,
1282
- headers: responseHeaders
1283
- }
1284
- };
1285
- } catch (error) {
1286
- throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
1287
- }
1288
- }
1289
- getUrl() {
1290
- return `${this.config.baseURL}/video-model`;
1291
- }
1292
- getModelConfigHeaders() {
1293
- return {
1294
- "ai-video-model-specification-version": "4",
1295
- "ai-model-id": this.modelId
1296
- };
1297
- }
1298
- };
1299
- function maybeEncodeVideoFile(file) {
1300
- if (file.type === "file" && file.data instanceof Uint8Array) {
1301
- return {
1302
- ...file,
1303
- data: convertUint8ArrayToBase642(file.data)
1304
- };
1305
- }
1306
- return file;
1307
- }
1308
- var providerMetadataEntrySchema2 = z10.object({
1309
- videos: z10.array(z10.unknown()).optional()
1310
- }).catchall(z10.unknown());
1311
- var gatewayVideoDataSchema = z10.union([
1312
- z10.object({
1313
- type: z10.literal("url"),
1314
- url: z10.string(),
1315
- mediaType: z10.string()
1316
- }),
1317
- z10.object({
1318
- type: z10.literal("base64"),
1319
- data: z10.string(),
1320
- mediaType: z10.string()
1321
- })
1322
- ]);
1323
- var gatewayVideoWarningSchema = z10.discriminatedUnion("type", [
1324
- z10.object({
1325
- type: z10.literal("unsupported"),
1326
- feature: z10.string(),
1327
- details: z10.string().optional()
1328
- }),
1329
- z10.object({
1330
- type: z10.literal("compatibility"),
1331
- feature: z10.string(),
1332
- details: z10.string().optional()
1333
- }),
1334
- z10.object({
1335
- type: z10.literal("other"),
1336
- message: z10.string()
1337
- })
1338
- ]);
1339
- var gatewayVideoEventSchema = z10.discriminatedUnion("type", [
1340
- z10.object({
1341
- type: z10.literal("result"),
1342
- videos: z10.array(gatewayVideoDataSchema),
1343
- warnings: z10.array(gatewayVideoWarningSchema).optional(),
1344
- providerMetadata: z10.record(z10.string(), providerMetadataEntrySchema2).optional()
1345
- }),
1346
- z10.object({
1347
- type: z10.literal("error"),
1348
- message: z10.string(),
1349
- errorType: z10.string(),
1350
- statusCode: z10.number(),
1351
- param: z10.unknown().nullable()
1352
- })
1353
- ]);
1354
-
1355
- // src/gateway-reranking-model.ts
1356
- import {
1357
- combineHeaders as combineHeaders5,
1358
- createJsonErrorResponseHandler as createJsonErrorResponseHandler8,
1359
- createJsonResponseHandler as createJsonResponseHandler7,
1360
- lazySchema as lazySchema8,
1361
- postJsonToApi as postJsonToApi5,
1362
- resolve as resolve8,
1363
- zodSchema as zodSchema8
1364
- } from "@ai-sdk/provider-utils";
1365
- import { z as z11 } from "zod/v4";
1366
- var GatewayRerankingModel = class {
1367
- constructor(modelId, config) {
1368
- this.modelId = modelId;
1369
- this.config = config;
1370
- this.specificationVersion = "v4";
1371
- }
1372
- get provider() {
1373
- return this.config.provider;
1374
- }
1375
- async doRerank({
1376
- documents,
1377
- query,
1378
- topN,
1379
- headers,
1380
- abortSignal,
1381
- providerOptions
1382
- }) {
1383
- const resolvedHeaders = await resolve8(this.config.headers());
1384
- try {
1385
- const {
1386
- responseHeaders,
1387
- value: responseBody,
1388
- rawValue
1389
- } = await postJsonToApi5({
1390
- url: this.getUrl(),
1391
- headers: combineHeaders5(
1392
- resolvedHeaders,
1393
- headers != null ? headers : {},
1394
- this.getModelConfigHeaders(),
1395
- await resolve8(this.config.o11yHeaders)
1396
- ),
1397
- body: {
1398
- documents,
1399
- query,
1400
- ...topN != null ? { topN } : {},
1401
- ...providerOptions ? { providerOptions } : {}
1402
- },
1403
- successfulResponseHandler: createJsonResponseHandler7(
1404
- gatewayRerankingResponseSchema
1405
- ),
1406
- failedResponseHandler: createJsonErrorResponseHandler8({
1407
- errorSchema: z11.any(),
1408
- errorToMessage: (data) => data
1409
- }),
1410
- ...abortSignal && { abortSignal },
1411
- fetch: this.config.fetch
1412
- });
1413
- return {
1414
- ranking: responseBody.ranking,
1415
- providerMetadata: responseBody.providerMetadata,
1416
- response: { headers: responseHeaders, body: rawValue },
1417
- warnings: []
1418
- };
1419
- } catch (error) {
1420
- throw await asGatewayError(error, await parseAuthMethod(resolvedHeaders));
1421
- }
1422
- }
1423
- getUrl() {
1424
- return `${this.config.baseURL}/reranking-model`;
1425
- }
1426
- getModelConfigHeaders() {
1427
- return {
1428
- "ai-reranking-model-specification-version": "4",
1429
- "ai-model-id": this.modelId
1430
- };
1431
- }
1432
- };
1433
- var gatewayRerankingResponseSchema = lazySchema8(
1434
- () => zodSchema8(
1435
- z11.object({
1436
- ranking: z11.array(
1437
- z11.object({
1438
- index: z11.number(),
1439
- relevanceScore: z11.number()
1440
- })
1441
- ),
1442
- providerMetadata: z11.record(z11.string(), z11.record(z11.string(), z11.unknown())).optional()
1443
- })
1444
- )
1445
- );
1446
-
1447
- // src/tool/parallel-search.ts
1448
- import {
1449
- createProviderToolFactoryWithOutputSchema,
1450
- lazySchema as lazySchema9,
1451
- zodSchema as zodSchema9
1452
- } from "@ai-sdk/provider-utils";
1453
- import { z as z12 } from "zod";
1454
- var parallelSearchInputSchema = lazySchema9(
1455
- () => zodSchema9(
1456
- z12.object({
1457
- objective: z12.string().describe(
1458
- "Natural-language description of the web research goal, including source or freshness guidance and broader context from the task. Maximum 5000 characters."
1459
- ),
1460
- search_queries: z12.array(z12.string()).optional().describe(
1461
- "Optional search queries to supplement the objective. Maximum 200 characters per query."
1462
- ),
1463
- mode: z12.enum(["one-shot", "agentic"]).optional().describe(
1464
- 'Mode preset: "one-shot" for comprehensive results with longer excerpts (default), "agentic" for concise, token-efficient results for multi-step workflows.'
1465
- ),
1466
- max_results: z12.number().optional().describe(
1467
- "Maximum number of results to return (1-20). Defaults to 10 if not specified."
1468
- ),
1469
- source_policy: z12.object({
1470
- include_domains: z12.array(z12.string()).optional().describe("List of domains to include in search results."),
1471
- exclude_domains: z12.array(z12.string()).optional().describe("List of domains to exclude from search results."),
1472
- after_date: z12.string().optional().describe(
1473
- "Only include results published after this date (ISO 8601 format)."
1474
- )
1475
- }).optional().describe(
1476
- "Source policy for controlling which domains to include/exclude and freshness."
1477
- ),
1478
- excerpts: z12.object({
1479
- max_chars_per_result: z12.number().optional().describe("Maximum characters per result."),
1480
- max_chars_total: z12.number().optional().describe("Maximum total characters across all results.")
1481
- }).optional().describe("Excerpt configuration for controlling result length."),
1482
- fetch_policy: z12.object({
1483
- max_age_seconds: z12.number().optional().describe(
1484
- "Maximum age in seconds for cached content. Set to 0 to always fetch fresh content."
1485
- )
1486
- }).optional().describe("Fetch policy for controlling content freshness.")
1487
- })
1488
- )
1489
- );
1490
- var parallelSearchOutputSchema = lazySchema9(
1491
- () => zodSchema9(
1492
- z12.union([
1493
- // Success response
1494
- z12.object({
1495
- searchId: z12.string(),
1496
- results: z12.array(
1497
- z12.object({
1498
- url: z12.string(),
1499
- title: z12.string(),
1500
- excerpt: z12.string(),
1501
- publishDate: z12.string().nullable().optional(),
1502
- relevanceScore: z12.number().optional()
1503
- })
1504
- )
1505
- }),
1506
- // Error response
1507
- z12.object({
1508
- error: z12.enum([
1509
- "api_error",
1510
- "rate_limit",
1511
- "timeout",
1512
- "invalid_input",
1513
- "configuration_error",
1514
- "unknown"
1515
- ]),
1516
- statusCode: z12.number().optional(),
1517
- message: z12.string()
1518
- })
1519
- ])
1520
- )
1521
- );
1522
- var parallelSearchToolFactory = createProviderToolFactoryWithOutputSchema({
1523
- id: "gateway.parallel_search",
1524
- inputSchema: parallelSearchInputSchema,
1525
- outputSchema: parallelSearchOutputSchema
1526
- });
1527
- var parallelSearch = (config = {}) => parallelSearchToolFactory(config);
1528
-
1529
- // src/tool/perplexity-search.ts
1530
- import {
1531
- createProviderToolFactoryWithOutputSchema as createProviderToolFactoryWithOutputSchema2,
1532
- lazySchema as lazySchema10,
1533
- zodSchema as zodSchema10
1534
- } from "@ai-sdk/provider-utils";
1535
- import { z as z13 } from "zod";
1536
- var perplexitySearchInputSchema = lazySchema10(
1537
- () => zodSchema10(
1538
- z13.object({
1539
- query: z13.union([z13.string(), z13.array(z13.string())]).describe(
1540
- "Search query (string) or multiple queries (array of up to 5 strings). Multi-query searches return combined results from all queries."
1541
- ),
1542
- max_results: z13.number().optional().describe(
1543
- "Maximum number of search results to return (1-20, default: 10)"
1544
- ),
1545
- max_tokens_per_page: z13.number().optional().describe(
1546
- "Maximum number of tokens to extract per search result page (256-2048, default: 2048)"
1547
- ),
1548
- max_tokens: z13.number().optional().describe(
1549
- "Maximum total tokens across all search results (default: 25000, max: 1000000)"
1550
- ),
1551
- country: z13.string().optional().describe(
1552
- "Two-letter ISO 3166-1 alpha-2 country code for regional search results (e.g., 'US', 'GB', 'FR')"
1553
- ),
1554
- search_domain_filter: z13.array(z13.string()).optional().describe(
1555
- "List of domains to include or exclude from search results (max 20). To include: ['nature.com', 'science.org']. To exclude: ['-example.com', '-spam.net']"
1556
- ),
1557
- search_language_filter: z13.array(z13.string()).optional().describe(
1558
- "List of ISO 639-1 language codes to filter results (max 10, lowercase). Examples: ['en', 'fr', 'de']"
1559
- ),
1560
- search_after_date: z13.string().optional().describe(
1561
- "Include only results published after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."
1562
- ),
1563
- search_before_date: z13.string().optional().describe(
1564
- "Include only results published before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."
1565
- ),
1566
- last_updated_after_filter: z13.string().optional().describe(
1567
- "Include only results last updated after this date. Format: 'MM/DD/YYYY' (e.g., '3/1/2025'). Cannot be used with search_recency_filter."
1568
- ),
1569
- last_updated_before_filter: z13.string().optional().describe(
1570
- "Include only results last updated before this date. Format: 'MM/DD/YYYY' (e.g., '3/15/2025'). Cannot be used with search_recency_filter."
1571
- ),
1572
- search_recency_filter: z13.enum(["day", "week", "month", "year"]).optional().describe(
1573
- "Filter results by relative time period. Cannot be used with search_after_date or search_before_date."
1574
- )
1575
- })
1576
- )
1577
- );
1578
- var perplexitySearchOutputSchema = lazySchema10(
1579
- () => zodSchema10(
1580
- z13.union([
1581
- // Success response
1582
- z13.object({
1583
- results: z13.array(
1584
- z13.object({
1585
- title: z13.string(),
1586
- url: z13.string(),
1587
- snippet: z13.string(),
1588
- date: z13.string().optional(),
1589
- lastUpdated: z13.string().optional()
1590
- })
1591
- ),
1592
- id: z13.string()
1593
- }),
1594
- // Error response
1595
- z13.object({
1596
- error: z13.enum([
1597
- "api_error",
1598
- "rate_limit",
1599
- "timeout",
1600
- "invalid_input",
1601
- "unknown"
1602
- ]),
1603
- statusCode: z13.number().optional(),
1604
- message: z13.string()
1605
- })
1606
- ])
1607
- )
1608
- );
1609
- var perplexitySearchToolFactory = createProviderToolFactoryWithOutputSchema2({
1610
- id: "gateway.perplexity_search",
1611
- inputSchema: perplexitySearchInputSchema,
1612
- outputSchema: perplexitySearchOutputSchema
1613
- });
1614
- var perplexitySearch = (config = {}) => perplexitySearchToolFactory(config);
1615
-
1616
- // src/gateway-tools.ts
1617
- var gatewayTools = {
1618
- /**
1619
- * Search the web using Parallel AI's Search API for LLM-optimized excerpts.
1620
- *
1621
- * Takes a natural language objective and returns relevant excerpts,
1622
- * replacing multiple keyword searches with a single call for broad
1623
- * or complex queries. Supports different search types for depth vs
1624
- * breadth tradeoffs.
1625
- */
1626
- parallelSearch,
1627
- /**
1628
- * Search the web using Perplexity's Search API for real-time information,
1629
- * news, research papers, and articles.
1630
- *
1631
- * Provides ranked search results with advanced filtering options including
1632
- * domain, language, date range, and recency filters.
1633
- */
1634
- perplexitySearch
1635
- };
1636
-
1637
- // src/vercel-environment.ts
1638
- import { getContext } from "@vercel/oidc";
1639
- import { getVercelOidcToken } from "@vercel/oidc";
1640
- async function getVercelRequestId() {
1641
- var _a9;
1642
- return (_a9 = getContext().headers) == null ? void 0 : _a9["x-vercel-id"];
1643
- }
1644
-
1645
- // src/gateway-provider.ts
1646
- import { withUserAgentSuffix } from "@ai-sdk/provider-utils";
1647
-
1648
- // src/version.ts
1649
- var VERSION = true ? "4.0.0-beta.47" : "0.0.0-test";
1650
-
1651
- // src/gateway-provider.ts
1652
- var AI_GATEWAY_PROTOCOL_VERSION = "0.0.1";
1653
- function createGatewayProvider(options = {}) {
1654
- var _a9, _b9;
1655
- let pendingMetadata = null;
1656
- let metadataCache = null;
1657
- const cacheRefreshMillis = (_a9 = options.metadataCacheRefreshMillis) != null ? _a9 : 1e3 * 60 * 5;
1658
- let lastFetchTime = 0;
1659
- const baseURL = (_b9 = withoutTrailingSlash(options.baseURL)) != null ? _b9 : "https://ai-gateway.vercel.sh/v3/ai";
1660
- const getHeaders = async () => {
1661
- try {
1662
- const auth = await getGatewayAuthToken(options);
1663
- return withUserAgentSuffix(
1664
- {
1665
- Authorization: `Bearer ${auth.token}`,
1666
- "ai-gateway-protocol-version": AI_GATEWAY_PROTOCOL_VERSION,
1667
- [GATEWAY_AUTH_METHOD_HEADER]: auth.authMethod,
1668
- ...options.headers
1669
- },
1670
- `ai-sdk/gateway/${VERSION}`
1671
- );
1672
- } catch (error) {
1673
- throw GatewayAuthenticationError.createContextualError({
1674
- apiKeyProvided: false,
1675
- oidcTokenProvided: false,
1676
- statusCode: 401,
1677
- cause: error
1678
- });
1679
- }
1680
- };
1681
- const createO11yHeaders = () => {
1682
- const deploymentId = loadOptionalSetting({
1683
- settingValue: void 0,
1684
- environmentVariableName: "VERCEL_DEPLOYMENT_ID"
1685
- });
1686
- const environment = loadOptionalSetting({
1687
- settingValue: void 0,
1688
- environmentVariableName: "VERCEL_ENV"
1689
- });
1690
- const region = loadOptionalSetting({
1691
- settingValue: void 0,
1692
- environmentVariableName: "VERCEL_REGION"
1693
- });
1694
- const projectId = loadOptionalSetting({
1695
- settingValue: void 0,
1696
- environmentVariableName: "VERCEL_PROJECT_ID"
1697
- });
1698
- return async () => {
1699
- const requestId = await getVercelRequestId();
1700
- return {
1701
- ...deploymentId && { "ai-o11y-deployment-id": deploymentId },
1702
- ...environment && { "ai-o11y-environment": environment },
1703
- ...region && { "ai-o11y-region": region },
1704
- ...requestId && { "ai-o11y-request-id": requestId },
1705
- ...projectId && { "ai-o11y-project-id": projectId }
1706
- };
1707
- };
1708
- };
1709
- const createLanguageModel = (modelId) => {
1710
- return new GatewayLanguageModel(modelId, {
1711
- provider: "gateway",
1712
- baseURL,
1713
- headers: getHeaders,
1714
- fetch: options.fetch,
1715
- o11yHeaders: createO11yHeaders()
1716
- });
1717
- };
1718
- const getAvailableModels = async () => {
1719
- var _a10, _b10, _c;
1720
- const now = (_c = (_b10 = (_a10 = options._internal) == null ? void 0 : _a10.currentDate) == null ? void 0 : _b10.call(_a10).getTime()) != null ? _c : Date.now();
1721
- if (!pendingMetadata || now - lastFetchTime > cacheRefreshMillis) {
1722
- lastFetchTime = now;
1723
- pendingMetadata = new GatewayFetchMetadata({
1724
- baseURL,
1725
- headers: getHeaders,
1726
- fetch: options.fetch
1727
- }).getAvailableModels().then((metadata) => {
1728
- metadataCache = metadata;
1729
- return metadata;
1730
- }).catch(async (error) => {
1731
- throw await asGatewayError(
1732
- error,
1733
- await parseAuthMethod(await getHeaders())
1734
- );
1735
- });
1736
- }
1737
- return metadataCache ? Promise.resolve(metadataCache) : pendingMetadata;
1738
- };
1739
- const getCredits = async () => {
1740
- return new GatewayFetchMetadata({
1741
- baseURL,
1742
- headers: getHeaders,
1743
- fetch: options.fetch
1744
- }).getCredits().catch(async (error) => {
1745
- throw await asGatewayError(
1746
- error,
1747
- await parseAuthMethod(await getHeaders())
1748
- );
1749
- });
1750
- };
1751
- const getSpendReport = async (params) => {
1752
- return new GatewaySpendReport({
1753
- baseURL,
1754
- headers: getHeaders,
1755
- fetch: options.fetch
1756
- }).getSpendReport(params).catch(async (error) => {
1757
- throw await asGatewayError(
1758
- error,
1759
- await parseAuthMethod(await getHeaders())
1760
- );
1761
- });
1762
- };
1763
- const getGenerationInfo = async (params) => {
1764
- return new GatewayGenerationInfoFetcher({
1765
- baseURL,
1766
- headers: getHeaders,
1767
- fetch: options.fetch
1768
- }).getGenerationInfo(params).catch(async (error) => {
1769
- throw await asGatewayError(
1770
- error,
1771
- await parseAuthMethod(await getHeaders())
1772
- );
1773
- });
1774
- };
1775
- const provider = function(modelId) {
1776
- if (new.target) {
1777
- throw new Error(
1778
- "The Gateway Provider model function cannot be called with the new keyword."
1779
- );
1780
- }
1781
- return createLanguageModel(modelId);
1782
- };
1783
- provider.specificationVersion = "v4";
1784
- provider.getAvailableModels = getAvailableModels;
1785
- provider.getCredits = getCredits;
1786
- provider.getSpendReport = getSpendReport;
1787
- provider.getGenerationInfo = getGenerationInfo;
1788
- provider.imageModel = (modelId) => {
1789
- return new GatewayImageModel(modelId, {
1790
- provider: "gateway",
1791
- baseURL,
1792
- headers: getHeaders,
1793
- fetch: options.fetch,
1794
- o11yHeaders: createO11yHeaders()
1795
- });
1796
- };
1797
- provider.languageModel = createLanguageModel;
1798
- const createEmbeddingModel = (modelId) => {
1799
- return new GatewayEmbeddingModel(modelId, {
1800
- provider: "gateway",
1801
- baseURL,
1802
- headers: getHeaders,
1803
- fetch: options.fetch,
1804
- o11yHeaders: createO11yHeaders()
1805
- });
1806
- };
1807
- provider.embeddingModel = createEmbeddingModel;
1808
- provider.textEmbeddingModel = createEmbeddingModel;
1809
- provider.videoModel = (modelId) => {
1810
- return new GatewayVideoModel(modelId, {
1811
- provider: "gateway",
1812
- baseURL,
1813
- headers: getHeaders,
1814
- fetch: options.fetch,
1815
- o11yHeaders: createO11yHeaders()
1816
- });
1817
- };
1818
- const createRerankingModel = (modelId) => {
1819
- return new GatewayRerankingModel(modelId, {
1820
- provider: "gateway",
1821
- baseURL,
1822
- headers: getHeaders,
1823
- fetch: options.fetch,
1824
- o11yHeaders: createO11yHeaders()
1825
- });
1826
- };
1827
- provider.rerankingModel = createRerankingModel;
1828
- provider.reranking = createRerankingModel;
1829
- provider.chat = provider.languageModel;
1830
- provider.embedding = provider.embeddingModel;
1831
- provider.image = provider.imageModel;
1832
- provider.video = provider.videoModel;
1833
- provider.tools = gatewayTools;
1834
- return provider;
1835
- }
1836
- var gateway = createGatewayProvider();
1837
- async function getGatewayAuthToken(options) {
1838
- const apiKey = loadOptionalSetting({
1839
- settingValue: options.apiKey,
1840
- environmentVariableName: "AI_GATEWAY_API_KEY"
1841
- });
1842
- if (apiKey) {
1843
- return {
1844
- token: apiKey,
1845
- authMethod: "api-key"
1846
- };
1847
- }
1848
- const oidcToken = await getVercelOidcToken();
1849
- return {
1850
- token: oidcToken,
1851
- authMethod: "oidc"
1852
- };
1853
- }
1854
- export {
1855
- GatewayAuthenticationError,
1856
- GatewayError,
1857
- GatewayInternalServerError,
1858
- GatewayInvalidRequestError,
1859
- GatewayModelNotFoundError,
1860
- GatewayRateLimitError,
1861
- GatewayResponseError,
1862
- createGatewayProvider as createGateway,
1863
- createGatewayProvider,
1864
- gateway
1865
- };
1866
- //# sourceMappingURL=index.mjs.map