@ai-sdk/google-vertex 5.0.0-beta.5 → 5.0.0-beta.52

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.
Files changed (55) hide show
  1. package/CHANGELOG.md +430 -8
  2. package/README.md +65 -1
  3. package/dist/anthropic/edge/index.d.ts +61 -16
  4. package/dist/anthropic/edge/index.js +67 -60
  5. package/dist/anthropic/edge/index.js.map +1 -1
  6. package/dist/anthropic/index.d.ts +61 -16
  7. package/dist/anthropic/index.js +57 -55
  8. package/dist/anthropic/index.js.map +1 -1
  9. package/dist/edge/index.d.ts +31 -22
  10. package/dist/edge/index.js +217 -176
  11. package/dist/edge/index.js.map +1 -1
  12. package/dist/index.d.ts +31 -22
  13. package/dist/index.js +208 -173
  14. package/dist/index.js.map +1 -1
  15. package/dist/maas/edge/index.d.ts +76 -0
  16. package/dist/maas/edge/index.js +196 -0
  17. package/dist/maas/edge/index.js.map +1 -0
  18. package/dist/maas/index.d.ts +60 -0
  19. package/dist/maas/index.js +101 -0
  20. package/dist/maas/index.js.map +1 -0
  21. package/docs/16-google-vertex.mdx +226 -6
  22. package/maas/edge.d.ts +1 -0
  23. package/maas/index.d.ts +1 -0
  24. package/package.json +29 -18
  25. package/src/anthropic/edge/google-vertex-anthropic-provider-edge.ts +1 -2
  26. package/src/anthropic/google-vertex-anthropic-messages-options.ts +1 -0
  27. package/src/anthropic/google-vertex-anthropic-provider-node.ts +1 -2
  28. package/src/anthropic/google-vertex-anthropic-provider.ts +33 -8
  29. package/src/edge/google-vertex-provider-edge.ts +1 -2
  30. package/src/google-vertex-config.ts +1 -1
  31. package/src/google-vertex-embedding-model.ts +23 -6
  32. package/src/google-vertex-embedding-options.ts +2 -0
  33. package/src/google-vertex-image-model.ts +38 -18
  34. package/src/google-vertex-options.ts +0 -1
  35. package/src/google-vertex-provider-node.ts +1 -2
  36. package/src/google-vertex-provider.ts +12 -12
  37. package/src/google-vertex-video-model.ts +7 -7
  38. package/src/maas/edge/google-vertex-maas-provider-edge.ts +65 -0
  39. package/src/maas/edge/index.ts +9 -0
  40. package/src/maas/google-vertex-maas-options.ts +15 -0
  41. package/src/maas/google-vertex-maas-provider-node.ts +64 -0
  42. package/src/maas/google-vertex-maas-provider.ts +111 -0
  43. package/src/maas/index.ts +9 -0
  44. package/dist/anthropic/edge/index.d.mts +0 -231
  45. package/dist/anthropic/edge/index.mjs +0 -259
  46. package/dist/anthropic/edge/index.mjs.map +0 -1
  47. package/dist/anthropic/index.d.mts +0 -215
  48. package/dist/anthropic/index.mjs +0 -164
  49. package/dist/anthropic/index.mjs.map +0 -1
  50. package/dist/edge/index.d.mts +0 -160
  51. package/dist/edge/index.mjs +0 -1049
  52. package/dist/edge/index.mjs.map +0 -1
  53. package/dist/index.d.mts +0 -219
  54. package/dist/index.mjs +0 -960
  55. package/dist/index.mjs.map +0 -1
@@ -1,1049 +0,0 @@
1
- // src/edge/google-vertex-provider-edge.ts
2
- import { loadOptionalSetting as loadOptionalSetting3, resolve as resolve5 } from "@ai-sdk/provider-utils";
3
-
4
- // src/google-vertex-provider.ts
5
- import { GoogleGenerativeAILanguageModel as GoogleGenerativeAILanguageModel2 } from "@ai-sdk/google/internal";
6
- import {
7
- generateId,
8
- loadOptionalSetting,
9
- loadSetting,
10
- normalizeHeaders,
11
- resolve as resolve4,
12
- withoutTrailingSlash,
13
- withUserAgentSuffix
14
- } from "@ai-sdk/provider-utils";
15
-
16
- // src/version.ts
17
- var VERSION = true ? "5.0.0-beta.5" : "0.0.0-test";
18
-
19
- // src/google-vertex-embedding-model.ts
20
- import {
21
- TooManyEmbeddingValuesForCallError
22
- } from "@ai-sdk/provider";
23
- import {
24
- combineHeaders,
25
- createJsonResponseHandler,
26
- postJsonToApi,
27
- resolve,
28
- parseProviderOptions
29
- } from "@ai-sdk/provider-utils";
30
- import { z as z3 } from "zod/v4";
31
-
32
- // src/google-vertex-error.ts
33
- import { createJsonErrorResponseHandler } from "@ai-sdk/provider-utils";
34
- import { z } from "zod/v4";
35
- var googleVertexErrorDataSchema = z.object({
36
- error: z.object({
37
- code: z.number().nullable(),
38
- message: z.string(),
39
- status: z.string()
40
- })
41
- });
42
- var googleVertexFailedResponseHandler = createJsonErrorResponseHandler(
43
- {
44
- errorSchema: googleVertexErrorDataSchema,
45
- errorToMessage: (data) => data.error.message
46
- }
47
- );
48
-
49
- // src/google-vertex-embedding-options.ts
50
- import { z as z2 } from "zod/v4";
51
- var googleVertexEmbeddingModelOptions = z2.object({
52
- /**
53
- * Optional. Optional reduced dimension for the output embedding.
54
- * If set, excessive values in the output embedding are truncated from the end.
55
- */
56
- outputDimensionality: z2.number().optional(),
57
- /**
58
- * Optional. Specifies the task type for generating embeddings.
59
- * Supported task types:
60
- * - SEMANTIC_SIMILARITY: Optimized for text similarity.
61
- * - CLASSIFICATION: Optimized for text classification.
62
- * - CLUSTERING: Optimized for clustering texts based on similarity.
63
- * - RETRIEVAL_DOCUMENT: Optimized for document retrieval.
64
- * - RETRIEVAL_QUERY: Optimized for query-based retrieval.
65
- * - QUESTION_ANSWERING: Optimized for answering questions.
66
- * - FACT_VERIFICATION: Optimized for verifying factual information.
67
- * - CODE_RETRIEVAL_QUERY: Optimized for retrieving code blocks based on natural language queries.
68
- */
69
- taskType: z2.enum([
70
- "SEMANTIC_SIMILARITY",
71
- "CLASSIFICATION",
72
- "CLUSTERING",
73
- "RETRIEVAL_DOCUMENT",
74
- "RETRIEVAL_QUERY",
75
- "QUESTION_ANSWERING",
76
- "FACT_VERIFICATION",
77
- "CODE_RETRIEVAL_QUERY"
78
- ]).optional(),
79
- /**
80
- * Optional. The title of the document being embedded.
81
- * Only valid when task_type is set to 'RETRIEVAL_DOCUMENT'.
82
- * Helps the model produce better embeddings by providing additional context.
83
- */
84
- title: z2.string().optional(),
85
- /**
86
- * Optional. When set to true, input text will be truncated. When set to false,
87
- * an error is returned if the input text is longer than the maximum length supported by the model. Defaults to true.
88
- */
89
- autoTruncate: z2.boolean().optional()
90
- });
91
-
92
- // src/google-vertex-embedding-model.ts
93
- var GoogleVertexEmbeddingModel = class {
94
- constructor(modelId, config) {
95
- this.specificationVersion = "v3";
96
- this.maxEmbeddingsPerCall = 2048;
97
- this.supportsParallelCalls = true;
98
- this.modelId = modelId;
99
- this.config = config;
100
- }
101
- get provider() {
102
- return this.config.provider;
103
- }
104
- async doEmbed({
105
- values,
106
- headers,
107
- abortSignal,
108
- providerOptions
109
- }) {
110
- let googleOptions = await parseProviderOptions({
111
- provider: "vertex",
112
- providerOptions,
113
- schema: googleVertexEmbeddingModelOptions
114
- });
115
- if (googleOptions == null) {
116
- googleOptions = await parseProviderOptions({
117
- provider: "google",
118
- providerOptions,
119
- schema: googleVertexEmbeddingModelOptions
120
- });
121
- }
122
- googleOptions = googleOptions != null ? googleOptions : {};
123
- if (values.length > this.maxEmbeddingsPerCall) {
124
- throw new TooManyEmbeddingValuesForCallError({
125
- provider: this.provider,
126
- modelId: this.modelId,
127
- maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
128
- values
129
- });
130
- }
131
- const mergedHeaders = combineHeaders(
132
- await resolve(this.config.headers),
133
- headers
134
- );
135
- const url = `${this.config.baseURL}/models/${this.modelId}:predict`;
136
- const {
137
- responseHeaders,
138
- value: response,
139
- rawValue
140
- } = await postJsonToApi({
141
- url,
142
- headers: mergedHeaders,
143
- body: {
144
- instances: values.map((value) => ({
145
- content: value,
146
- task_type: googleOptions.taskType,
147
- title: googleOptions.title
148
- })),
149
- parameters: {
150
- outputDimensionality: googleOptions.outputDimensionality,
151
- autoTruncate: googleOptions.autoTruncate
152
- }
153
- },
154
- failedResponseHandler: googleVertexFailedResponseHandler,
155
- successfulResponseHandler: createJsonResponseHandler(
156
- googleVertexTextEmbeddingResponseSchema
157
- ),
158
- abortSignal,
159
- fetch: this.config.fetch
160
- });
161
- return {
162
- warnings: [],
163
- embeddings: response.predictions.map(
164
- (prediction) => prediction.embeddings.values
165
- ),
166
- usage: {
167
- tokens: response.predictions.reduce(
168
- (tokenCount, prediction) => tokenCount + prediction.embeddings.statistics.token_count,
169
- 0
170
- )
171
- },
172
- response: { headers: responseHeaders, body: rawValue }
173
- };
174
- }
175
- };
176
- var googleVertexTextEmbeddingResponseSchema = z3.object({
177
- predictions: z3.array(
178
- z3.object({
179
- embeddings: z3.object({
180
- values: z3.array(z3.number()),
181
- statistics: z3.object({
182
- token_count: z3.number()
183
- })
184
- })
185
- })
186
- )
187
- });
188
-
189
- // src/google-vertex-image-model.ts
190
- import { GoogleGenerativeAILanguageModel } from "@ai-sdk/google/internal";
191
- import {
192
- combineHeaders as combineHeaders2,
193
- convertToBase64,
194
- convertUint8ArrayToBase64,
195
- createJsonResponseHandler as createJsonResponseHandler2,
196
- generateId as defaultGenerateId,
197
- parseProviderOptions as parseProviderOptions2,
198
- postJsonToApi as postJsonToApi2,
199
- resolve as resolve2
200
- } from "@ai-sdk/provider-utils";
201
- import { z as z4 } from "zod/v4";
202
- var GoogleVertexImageModel = class {
203
- constructor(modelId, config) {
204
- this.modelId = modelId;
205
- this.config = config;
206
- this.specificationVersion = "v3";
207
- }
208
- get maxImagesPerCall() {
209
- if (isGeminiModel(this.modelId)) {
210
- return 10;
211
- }
212
- return 4;
213
- }
214
- get provider() {
215
- return this.config.provider;
216
- }
217
- async doGenerate(options) {
218
- if (isGeminiModel(this.modelId)) {
219
- return this.doGenerateGemini(options);
220
- }
221
- return this.doGenerateImagen(options);
222
- }
223
- async doGenerateImagen({
224
- prompt,
225
- n,
226
- size,
227
- aspectRatio,
228
- seed,
229
- providerOptions,
230
- headers,
231
- abortSignal,
232
- files,
233
- mask
234
- }) {
235
- var _a, _b, _c, _d, _e, _f, _g;
236
- const warnings = [];
237
- if (size != null) {
238
- warnings.push({
239
- type: "unsupported",
240
- feature: "size",
241
- details: "This model does not support the `size` option. Use `aspectRatio` instead."
242
- });
243
- }
244
- const vertexImageOptions = await parseProviderOptions2({
245
- provider: "vertex",
246
- providerOptions,
247
- schema: googleVertexImageModelOptionsSchema
248
- });
249
- const { edit, ...otherOptions } = vertexImageOptions != null ? vertexImageOptions : {};
250
- const { mode: editMode, baseSteps, maskMode, maskDilation } = edit != null ? edit : {};
251
- const isEditMode = files != null && files.length > 0;
252
- let body;
253
- if (isEditMode) {
254
- const referenceImages = [];
255
- for (let i = 0; i < files.length; i++) {
256
- const file = files[i];
257
- referenceImages.push({
258
- referenceType: "REFERENCE_TYPE_RAW",
259
- referenceId: i + 1,
260
- referenceImage: {
261
- bytesBase64Encoded: getBase64Data(file)
262
- }
263
- });
264
- }
265
- if (mask != null) {
266
- referenceImages.push({
267
- referenceType: "REFERENCE_TYPE_MASK",
268
- referenceId: files.length + 1,
269
- referenceImage: {
270
- bytesBase64Encoded: getBase64Data(mask)
271
- },
272
- maskImageConfig: {
273
- maskMode: maskMode != null ? maskMode : "MASK_MODE_USER_PROVIDED",
274
- ...maskDilation != null ? { dilation: maskDilation } : {}
275
- }
276
- });
277
- }
278
- body = {
279
- instances: [
280
- {
281
- prompt,
282
- referenceImages
283
- }
284
- ],
285
- parameters: {
286
- sampleCount: n,
287
- ...aspectRatio != null ? { aspectRatio } : {},
288
- ...seed != null ? { seed } : {},
289
- editMode: editMode != null ? editMode : "EDIT_MODE_INPAINT_INSERTION",
290
- ...baseSteps != null ? { editConfig: { baseSteps } } : {},
291
- ...otherOptions
292
- }
293
- };
294
- } else {
295
- body = {
296
- instances: [{ prompt }],
297
- parameters: {
298
- sampleCount: n,
299
- ...aspectRatio != null ? { aspectRatio } : {},
300
- ...seed != null ? { seed } : {},
301
- ...otherOptions
302
- }
303
- };
304
- }
305
- const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
306
- const { value: response, responseHeaders } = await postJsonToApi2({
307
- url: `${this.config.baseURL}/models/${this.modelId}:predict`,
308
- headers: combineHeaders2(await resolve2(this.config.headers), headers),
309
- body,
310
- failedResponseHandler: googleVertexFailedResponseHandler,
311
- successfulResponseHandler: createJsonResponseHandler2(
312
- vertexImageResponseSchema
313
- ),
314
- abortSignal,
315
- fetch: this.config.fetch
316
- });
317
- return {
318
- images: (_e = (_d = response.predictions) == null ? void 0 : _d.map(
319
- ({ bytesBase64Encoded }) => bytesBase64Encoded
320
- )) != null ? _e : [],
321
- warnings,
322
- response: {
323
- timestamp: currentDate,
324
- modelId: this.modelId,
325
- headers: responseHeaders
326
- },
327
- providerMetadata: {
328
- vertex: {
329
- images: (_g = (_f = response.predictions) == null ? void 0 : _f.map((prediction) => {
330
- const {
331
- // normalize revised prompt property
332
- prompt: revisedPrompt
333
- } = prediction;
334
- return { ...revisedPrompt != null && { revisedPrompt } };
335
- })) != null ? _g : []
336
- }
337
- }
338
- };
339
- }
340
- async doGenerateGemini({
341
- prompt,
342
- n,
343
- size,
344
- aspectRatio,
345
- seed,
346
- providerOptions,
347
- headers,
348
- abortSignal,
349
- files,
350
- mask
351
- }) {
352
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
353
- const warnings = [];
354
- if (mask != null) {
355
- throw new Error(
356
- "Gemini image models do not support mask-based image editing."
357
- );
358
- }
359
- if (n != null && n > 1) {
360
- throw new Error(
361
- "Gemini image models do not support generating a set number of images per call. Use n=1 or omit the n parameter."
362
- );
363
- }
364
- if (size != null) {
365
- warnings.push({
366
- type: "unsupported",
367
- feature: "size",
368
- details: "This model does not support the `size` option. Use `aspectRatio` instead."
369
- });
370
- }
371
- const userContent = [];
372
- if (prompt != null) {
373
- userContent.push({ type: "text", text: prompt });
374
- }
375
- if (files != null && files.length > 0) {
376
- for (const file of files) {
377
- if (file.type === "url") {
378
- userContent.push({
379
- type: "file",
380
- data: new URL(file.url),
381
- mediaType: "image/*"
382
- });
383
- } else {
384
- userContent.push({
385
- type: "file",
386
- data: typeof file.data === "string" ? file.data : new Uint8Array(file.data),
387
- mediaType: file.mediaType
388
- });
389
- }
390
- }
391
- }
392
- const languageModelPrompt = [
393
- { role: "user", content: userContent }
394
- ];
395
- const languageModel = new GoogleGenerativeAILanguageModel(this.modelId, {
396
- provider: this.config.provider,
397
- baseURL: this.config.baseURL,
398
- headers: (_a = this.config.headers) != null ? _a : {},
399
- fetch: this.config.fetch,
400
- generateId: (_b = this.config.generateId) != null ? _b : defaultGenerateId,
401
- supportedUrls: () => ({
402
- "*": [/^https?:\/\/.*$/, /^gs:\/\/.*$/]
403
- })
404
- });
405
- const result = await languageModel.doGenerate({
406
- prompt: languageModelPrompt,
407
- seed,
408
- providerOptions: {
409
- vertex: {
410
- responseModalities: ["IMAGE"],
411
- imageConfig: aspectRatio ? {
412
- aspectRatio
413
- } : void 0,
414
- ...(_c = providerOptions == null ? void 0 : providerOptions.vertex) != null ? _c : {}
415
- }
416
- },
417
- headers,
418
- abortSignal
419
- });
420
- const currentDate = (_f = (_e = (_d = this.config._internal) == null ? void 0 : _d.currentDate) == null ? void 0 : _e.call(_d)) != null ? _f : /* @__PURE__ */ new Date();
421
- const images = [];
422
- for (const part of result.content) {
423
- if (part.type === "file" && part.mediaType.startsWith("image/")) {
424
- images.push(convertToBase64(part.data));
425
- }
426
- }
427
- return {
428
- images,
429
- warnings,
430
- providerMetadata: {
431
- vertex: {
432
- images: images.map(() => ({}))
433
- }
434
- },
435
- response: {
436
- timestamp: currentDate,
437
- modelId: this.modelId,
438
- headers: (_g = result.response) == null ? void 0 : _g.headers
439
- },
440
- usage: result.usage ? {
441
- inputTokens: result.usage.inputTokens.total,
442
- outputTokens: result.usage.outputTokens.total,
443
- totalTokens: ((_h = result.usage.inputTokens.total) != null ? _h : 0) + ((_i = result.usage.outputTokens.total) != null ? _i : 0)
444
- } : void 0
445
- };
446
- }
447
- };
448
- function isGeminiModel(modelId) {
449
- return modelId.startsWith("gemini-");
450
- }
451
- var vertexImageResponseSchema = z4.object({
452
- predictions: z4.array(
453
- z4.object({
454
- bytesBase64Encoded: z4.string(),
455
- mimeType: z4.string(),
456
- prompt: z4.string().nullish()
457
- })
458
- ).nullish()
459
- });
460
- var googleVertexImageModelOptionsSchema = z4.object({
461
- negativePrompt: z4.string().nullish(),
462
- personGeneration: z4.enum(["dont_allow", "allow_adult", "allow_all"]).nullish(),
463
- safetySetting: z4.enum([
464
- "block_low_and_above",
465
- "block_medium_and_above",
466
- "block_only_high",
467
- "block_none"
468
- ]).nullish(),
469
- addWatermark: z4.boolean().nullish(),
470
- storageUri: z4.string().nullish(),
471
- sampleImageSize: z4.enum(["1K", "2K"]).nullish(),
472
- /**
473
- * Configuration for image editing operations
474
- */
475
- edit: z4.object({
476
- /**
477
- * An integer that represents the number of sampling steps.
478
- * A higher value offers better image quality, a lower value offers better latency.
479
- * Try 35 steps to start. If the quality doesn't meet your requirements,
480
- * increase the value towards an upper limit of 75.
481
- */
482
- baseSteps: z4.number().nullish(),
483
- // Edit mode options
484
- // https://cloud.google.com/vertex-ai/generative-ai/docs/image/edit-insert-objects
485
- mode: z4.enum([
486
- "EDIT_MODE_INPAINT_INSERTION",
487
- "EDIT_MODE_INPAINT_REMOVAL",
488
- "EDIT_MODE_OUTPAINT",
489
- "EDIT_MODE_CONTROLLED_EDITING",
490
- "EDIT_MODE_PRODUCT_IMAGE",
491
- "EDIT_MODE_BGSWAP"
492
- ]).nullish(),
493
- /**
494
- * The mask mode to use.
495
- * - `MASK_MODE_DEFAULT` - Default value for mask mode.
496
- * - `MASK_MODE_USER_PROVIDED` - User provided mask. No segmentation needed.
497
- * - `MASK_MODE_DETECTION_BOX` - Mask from detected bounding boxes.
498
- * - `MASK_MODE_CLOTHING_AREA` - Masks from segmenting the clothing area with open-vocab segmentation.
499
- * - `MASK_MODE_PARSED_PERSON` - Masks from segmenting the person body and clothing using the person-parsing model.
500
- */
501
- maskMode: z4.enum([
502
- "MASK_MODE_DEFAULT",
503
- "MASK_MODE_USER_PROVIDED",
504
- "MASK_MODE_DETECTION_BOX",
505
- "MASK_MODE_CLOTHING_AREA",
506
- "MASK_MODE_PARSED_PERSON"
507
- ]).nullish(),
508
- /**
509
- * Optional. A float value between 0 and 1, inclusive, that represents the
510
- * percentage of the image width to grow the mask by. Using dilation helps
511
- * compensate for imprecise masks. We recommend a value of 0.01.
512
- */
513
- maskDilation: z4.number().nullish()
514
- }).nullish()
515
- });
516
- function getBase64Data(file) {
517
- if (file.type === "url") {
518
- throw new Error(
519
- "URL-based images are not supported for Google Vertex image editing. Please provide the image data directly."
520
- );
521
- }
522
- if (typeof file.data === "string") {
523
- return file.data;
524
- }
525
- return convertUint8ArrayToBase64(file.data);
526
- }
527
-
528
- // src/google-vertex-tools.ts
529
- import { googleTools } from "@ai-sdk/google/internal";
530
- var googleVertexTools = {
531
- googleSearch: googleTools.googleSearch,
532
- enterpriseWebSearch: googleTools.enterpriseWebSearch,
533
- googleMaps: googleTools.googleMaps,
534
- urlContext: googleTools.urlContext,
535
- fileSearch: googleTools.fileSearch,
536
- codeExecution: googleTools.codeExecution,
537
- vertexRagStore: googleTools.vertexRagStore
538
- };
539
-
540
- // src/google-vertex-video-model.ts
541
- import {
542
- AISDKError
543
- } from "@ai-sdk/provider";
544
- import {
545
- combineHeaders as combineHeaders3,
546
- convertUint8ArrayToBase64 as convertUint8ArrayToBase642,
547
- createJsonResponseHandler as createJsonResponseHandler3,
548
- delay,
549
- lazySchema,
550
- parseProviderOptions as parseProviderOptions3,
551
- postJsonToApi as postJsonToApi3,
552
- resolve as resolve3,
553
- zodSchema
554
- } from "@ai-sdk/provider-utils";
555
- import { z as z5 } from "zod/v4";
556
- var GoogleVertexVideoModel = class {
557
- constructor(modelId, config) {
558
- this.modelId = modelId;
559
- this.config = config;
560
- this.specificationVersion = "v3";
561
- }
562
- get provider() {
563
- return this.config.provider;
564
- }
565
- get maxVideosPerCall() {
566
- return 4;
567
- }
568
- async doGenerate(options) {
569
- var _a, _b, _c, _d, _e, _f;
570
- const currentDate = (_c = (_b = (_a = this.config._internal) == null ? void 0 : _a.currentDate) == null ? void 0 : _b.call(_a)) != null ? _c : /* @__PURE__ */ new Date();
571
- const warnings = [];
572
- const vertexOptions = await parseProviderOptions3({
573
- provider: "vertex",
574
- providerOptions: options.providerOptions,
575
- schema: googleVertexVideoModelOptionsSchema
576
- });
577
- const instances = [{}];
578
- const instance = instances[0];
579
- if (options.prompt != null) {
580
- instance.prompt = options.prompt;
581
- }
582
- if (options.image != null) {
583
- if (options.image.type === "url") {
584
- warnings.push({
585
- type: "unsupported",
586
- feature: "URL-based image input",
587
- details: "Vertex AI video models require base64-encoded images or GCS URIs. URL will be ignored."
588
- });
589
- } else {
590
- const base64Data = typeof options.image.data === "string" ? options.image.data : convertUint8ArrayToBase642(options.image.data);
591
- instance.image = {
592
- bytesBase64Encoded: base64Data,
593
- mimeType: options.image.mediaType
594
- };
595
- }
596
- }
597
- if ((vertexOptions == null ? void 0 : vertexOptions.referenceImages) != null) {
598
- instance.referenceImages = vertexOptions.referenceImages;
599
- }
600
- const parameters = {
601
- sampleCount: options.n
602
- };
603
- if (options.aspectRatio) {
604
- parameters.aspectRatio = options.aspectRatio;
605
- }
606
- if (options.resolution) {
607
- const resolutionMap = {
608
- "1280x720": "720p",
609
- "1920x1080": "1080p",
610
- "3840x2160": "4k"
611
- };
612
- parameters.resolution = resolutionMap[options.resolution] || options.resolution;
613
- }
614
- if (options.duration) {
615
- parameters.durationSeconds = options.duration;
616
- }
617
- if (options.seed) {
618
- parameters.seed = options.seed;
619
- }
620
- if (vertexOptions != null) {
621
- const opts = vertexOptions;
622
- if (opts.personGeneration !== void 0 && opts.personGeneration !== null) {
623
- parameters.personGeneration = opts.personGeneration;
624
- }
625
- if (opts.negativePrompt !== void 0 && opts.negativePrompt !== null) {
626
- parameters.negativePrompt = opts.negativePrompt;
627
- }
628
- if (opts.generateAudio !== void 0 && opts.generateAudio !== null) {
629
- parameters.generateAudio = opts.generateAudio;
630
- }
631
- if (opts.gcsOutputDirectory !== void 0 && opts.gcsOutputDirectory !== null) {
632
- parameters.gcsOutputDirectory = opts.gcsOutputDirectory;
633
- }
634
- for (const [key, value] of Object.entries(opts)) {
635
- if (![
636
- "pollIntervalMs",
637
- "pollTimeoutMs",
638
- "personGeneration",
639
- "negativePrompt",
640
- "generateAudio",
641
- "gcsOutputDirectory",
642
- "referenceImages"
643
- ].includes(key)) {
644
- parameters[key] = value;
645
- }
646
- }
647
- }
648
- const { value: operation } = await postJsonToApi3({
649
- url: `${this.config.baseURL}/models/${this.modelId}:predictLongRunning`,
650
- headers: combineHeaders3(
651
- await resolve3(this.config.headers),
652
- options.headers
653
- ),
654
- body: {
655
- instances,
656
- parameters
657
- },
658
- successfulResponseHandler: createJsonResponseHandler3(
659
- vertexOperationSchema
660
- ),
661
- failedResponseHandler: googleVertexFailedResponseHandler,
662
- abortSignal: options.abortSignal,
663
- fetch: this.config.fetch
664
- });
665
- const operationName = operation.name;
666
- if (!operationName) {
667
- throw new AISDKError({
668
- name: "VERTEX_VIDEO_GENERATION_ERROR",
669
- message: "No operation name returned from API"
670
- });
671
- }
672
- const pollIntervalMs = (_d = vertexOptions == null ? void 0 : vertexOptions.pollIntervalMs) != null ? _d : 1e4;
673
- const pollTimeoutMs = (_e = vertexOptions == null ? void 0 : vertexOptions.pollTimeoutMs) != null ? _e : 6e5;
674
- const startTime = Date.now();
675
- let finalOperation = operation;
676
- let responseHeaders;
677
- while (!finalOperation.done) {
678
- if (Date.now() - startTime > pollTimeoutMs) {
679
- throw new AISDKError({
680
- name: "VERTEX_VIDEO_GENERATION_TIMEOUT",
681
- message: `Video generation timed out after ${pollTimeoutMs}ms`
682
- });
683
- }
684
- await delay(pollIntervalMs);
685
- if ((_f = options.abortSignal) == null ? void 0 : _f.aborted) {
686
- throw new AISDKError({
687
- name: "VERTEX_VIDEO_GENERATION_ABORTED",
688
- message: "Video generation request was aborted"
689
- });
690
- }
691
- const { value: statusOperation, responseHeaders: pollHeaders } = await postJsonToApi3({
692
- url: `${this.config.baseURL}/models/${this.modelId}:fetchPredictOperation`,
693
- headers: combineHeaders3(
694
- await resolve3(this.config.headers),
695
- options.headers
696
- ),
697
- body: {
698
- operationName
699
- },
700
- successfulResponseHandler: createJsonResponseHandler3(
701
- vertexOperationSchema
702
- ),
703
- failedResponseHandler: googleVertexFailedResponseHandler,
704
- abortSignal: options.abortSignal,
705
- fetch: this.config.fetch
706
- });
707
- finalOperation = statusOperation;
708
- responseHeaders = pollHeaders;
709
- }
710
- if (finalOperation.error) {
711
- throw new AISDKError({
712
- name: "VERTEX_VIDEO_GENERATION_FAILED",
713
- message: `Video generation failed: ${finalOperation.error.message}`
714
- });
715
- }
716
- const response = finalOperation.response;
717
- if (!(response == null ? void 0 : response.videos) || response.videos.length === 0) {
718
- throw new AISDKError({
719
- name: "VERTEX_VIDEO_GENERATION_ERROR",
720
- message: `No videos in response. Response: ${JSON.stringify(finalOperation)}`
721
- });
722
- }
723
- const videos = [];
724
- const videoMetadata = [];
725
- for (const video of response.videos) {
726
- if (video.bytesBase64Encoded) {
727
- videos.push({
728
- type: "base64",
729
- data: video.bytesBase64Encoded,
730
- mediaType: video.mimeType || "video/mp4"
731
- });
732
- videoMetadata.push({
733
- mimeType: video.mimeType
734
- });
735
- } else if (video.gcsUri) {
736
- videos.push({
737
- type: "url",
738
- url: video.gcsUri,
739
- mediaType: video.mimeType || "video/mp4"
740
- });
741
- videoMetadata.push({
742
- gcsUri: video.gcsUri,
743
- mimeType: video.mimeType
744
- });
745
- }
746
- }
747
- if (videos.length === 0) {
748
- throw new AISDKError({
749
- name: "VERTEX_VIDEO_GENERATION_ERROR",
750
- message: "No valid videos in response"
751
- });
752
- }
753
- return {
754
- videos,
755
- warnings,
756
- response: {
757
- timestamp: currentDate,
758
- modelId: this.modelId,
759
- headers: responseHeaders
760
- },
761
- providerMetadata: {
762
- "google-vertex": {
763
- videos: videoMetadata
764
- }
765
- }
766
- };
767
- }
768
- };
769
- var vertexOperationSchema = z5.object({
770
- name: z5.string().nullish(),
771
- done: z5.boolean().nullish(),
772
- error: z5.object({
773
- code: z5.number().nullish(),
774
- message: z5.string(),
775
- status: z5.string().nullish()
776
- }).nullish(),
777
- response: z5.object({
778
- videos: z5.array(
779
- z5.object({
780
- bytesBase64Encoded: z5.string().nullish(),
781
- gcsUri: z5.string().nullish(),
782
- mimeType: z5.string().nullish()
783
- })
784
- ).nullish(),
785
- raiMediaFilteredCount: z5.number().nullish()
786
- }).nullish()
787
- });
788
- var googleVertexVideoModelOptionsSchema = lazySchema(
789
- () => zodSchema(
790
- z5.object({
791
- pollIntervalMs: z5.number().positive().nullish(),
792
- pollTimeoutMs: z5.number().positive().nullish(),
793
- personGeneration: z5.enum(["dont_allow", "allow_adult", "allow_all"]).nullish(),
794
- negativePrompt: z5.string().nullish(),
795
- generateAudio: z5.boolean().nullish(),
796
- gcsOutputDirectory: z5.string().nullish(),
797
- referenceImages: z5.array(
798
- z5.object({
799
- bytesBase64Encoded: z5.string().nullish(),
800
- gcsUri: z5.string().nullish()
801
- })
802
- ).nullish()
803
- }).passthrough()
804
- )
805
- );
806
-
807
- // src/google-vertex-provider.ts
808
- var EXPRESS_MODE_BASE_URL = "https://aiplatform.googleapis.com/v1/publishers/google";
809
- function createExpressModeFetch(apiKey, customFetch) {
810
- return async (url, init) => {
811
- const modifiedInit = {
812
- ...init,
813
- headers: {
814
- ...(init == null ? void 0 : init.headers) ? normalizeHeaders(init.headers) : {},
815
- "x-goog-api-key": apiKey
816
- }
817
- };
818
- return (customFetch != null ? customFetch : fetch)(url.toString(), modifiedInit);
819
- };
820
- }
821
- function createVertex(options = {}) {
822
- const apiKey = loadOptionalSetting({
823
- settingValue: options.apiKey,
824
- environmentVariableName: "GOOGLE_VERTEX_API_KEY"
825
- });
826
- const loadVertexProject = () => loadSetting({
827
- settingValue: options.project,
828
- settingName: "project",
829
- environmentVariableName: "GOOGLE_VERTEX_PROJECT",
830
- description: "Google Vertex project"
831
- });
832
- const loadVertexLocation = () => loadSetting({
833
- settingValue: options.location,
834
- settingName: "location",
835
- environmentVariableName: "GOOGLE_VERTEX_LOCATION",
836
- description: "Google Vertex location"
837
- });
838
- const loadBaseURL = () => {
839
- var _a, _b;
840
- if (apiKey) {
841
- return (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : EXPRESS_MODE_BASE_URL;
842
- }
843
- const region = loadVertexLocation();
844
- const project = loadVertexProject();
845
- const baseHost = `${region === "global" ? "" : region + "-"}aiplatform.googleapis.com`;
846
- return (_b = withoutTrailingSlash(options.baseURL)) != null ? _b : `https://${baseHost}/v1beta1/projects/${project}/locations/${region}/publishers/google`;
847
- };
848
- const createConfig = (name) => {
849
- const getHeaders = async () => {
850
- var _a;
851
- const originalHeaders = await resolve4((_a = options.headers) != null ? _a : {});
852
- return withUserAgentSuffix(
853
- originalHeaders,
854
- `ai-sdk/google-vertex/${VERSION}`
855
- );
856
- };
857
- return {
858
- provider: `google.vertex.${name}`,
859
- headers: getHeaders,
860
- fetch: apiKey ? createExpressModeFetch(apiKey, options.fetch) : options.fetch,
861
- baseURL: loadBaseURL()
862
- };
863
- };
864
- const createChatModel = (modelId) => {
865
- var _a;
866
- return new GoogleGenerativeAILanguageModel2(modelId, {
867
- ...createConfig("chat"),
868
- generateId: (_a = options.generateId) != null ? _a : generateId,
869
- supportedUrls: () => ({
870
- "*": [
871
- // HTTP URLs:
872
- /^https?:\/\/.*$/,
873
- // Google Cloud Storage URLs:
874
- /^gs:\/\/.*$/
875
- ]
876
- })
877
- });
878
- };
879
- const createEmbeddingModel = (modelId) => new GoogleVertexEmbeddingModel(modelId, createConfig("embedding"));
880
- const createImageModel = (modelId) => {
881
- var _a;
882
- return new GoogleVertexImageModel(modelId, {
883
- ...createConfig("image"),
884
- generateId: (_a = options.generateId) != null ? _a : generateId
885
- });
886
- };
887
- const createVideoModel = (modelId) => {
888
- var _a;
889
- return new GoogleVertexVideoModel(modelId, {
890
- ...createConfig("video"),
891
- generateId: (_a = options.generateId) != null ? _a : generateId
892
- });
893
- };
894
- const provider = function(modelId) {
895
- if (new.target) {
896
- throw new Error(
897
- "The Google Vertex AI model function cannot be called with the new keyword."
898
- );
899
- }
900
- return createChatModel(modelId);
901
- };
902
- provider.specificationVersion = "v3";
903
- provider.languageModel = createChatModel;
904
- provider.embeddingModel = createEmbeddingModel;
905
- provider.textEmbeddingModel = createEmbeddingModel;
906
- provider.image = createImageModel;
907
- provider.imageModel = createImageModel;
908
- provider.video = createVideoModel;
909
- provider.videoModel = createVideoModel;
910
- provider.tools = googleVertexTools;
911
- return provider;
912
- }
913
-
914
- // src/edge/google-vertex-auth-edge.ts
915
- import {
916
- loadOptionalSetting as loadOptionalSetting2,
917
- loadSetting as loadSetting2,
918
- withUserAgentSuffix as withUserAgentSuffix2,
919
- getRuntimeEnvironmentUserAgent
920
- } from "@ai-sdk/provider-utils";
921
- var loadCredentials = async () => {
922
- try {
923
- return {
924
- clientEmail: loadSetting2({
925
- settingValue: void 0,
926
- settingName: "clientEmail",
927
- environmentVariableName: "GOOGLE_CLIENT_EMAIL",
928
- description: "Google client email"
929
- }),
930
- privateKey: loadSetting2({
931
- settingValue: void 0,
932
- settingName: "privateKey",
933
- environmentVariableName: "GOOGLE_PRIVATE_KEY",
934
- description: "Google private key"
935
- }),
936
- privateKeyId: loadOptionalSetting2({
937
- settingValue: void 0,
938
- environmentVariableName: "GOOGLE_PRIVATE_KEY_ID"
939
- })
940
- };
941
- } catch (error) {
942
- throw new Error(`Failed to load Google credentials: ${error.message}`);
943
- }
944
- };
945
- var base64url = (str) => {
946
- return btoa(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
947
- };
948
- var importPrivateKey = async (pemKey) => {
949
- const pemHeader = "-----BEGIN PRIVATE KEY-----";
950
- const pemFooter = "-----END PRIVATE KEY-----";
951
- const pemContents = pemKey.replace(pemHeader, "").replace(pemFooter, "").replace(/\s/g, "");
952
- const binaryString = atob(pemContents);
953
- const binaryData = new Uint8Array(binaryString.length);
954
- for (let i = 0; i < binaryString.length; i++) {
955
- binaryData[i] = binaryString.charCodeAt(i);
956
- }
957
- return await crypto.subtle.importKey(
958
- "pkcs8",
959
- binaryData,
960
- { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
961
- true,
962
- ["sign"]
963
- );
964
- };
965
- var buildJwt = async (credentials) => {
966
- const now = Math.floor(Date.now() / 1e3);
967
- const header = {
968
- alg: "RS256",
969
- typ: "JWT"
970
- };
971
- if (credentials.privateKeyId) {
972
- header.kid = credentials.privateKeyId;
973
- }
974
- const payload = {
975
- iss: credentials.clientEmail,
976
- scope: "https://www.googleapis.com/auth/cloud-platform",
977
- aud: "https://oauth2.googleapis.com/token",
978
- exp: now + 3600,
979
- iat: now
980
- };
981
- const privateKey = await importPrivateKey(credentials.privateKey);
982
- const signingInput = `${base64url(JSON.stringify(header))}.${base64url(
983
- JSON.stringify(payload)
984
- )}`;
985
- const encoder = new TextEncoder();
986
- const data = encoder.encode(signingInput);
987
- const signature = await crypto.subtle.sign(
988
- "RSASSA-PKCS1-v1_5",
989
- privateKey,
990
- data
991
- );
992
- const signatureBase64 = base64url(
993
- String.fromCharCode(...new Uint8Array(signature))
994
- );
995
- return `${base64url(JSON.stringify(header))}.${base64url(
996
- JSON.stringify(payload)
997
- )}.${signatureBase64}`;
998
- };
999
- async function generateAuthToken(credentials) {
1000
- try {
1001
- const creds = credentials || await loadCredentials();
1002
- const jwt = await buildJwt(creds);
1003
- const response = await fetch("https://oauth2.googleapis.com/token", {
1004
- method: "POST",
1005
- headers: withUserAgentSuffix2(
1006
- { "Content-Type": "application/x-www-form-urlencoded" },
1007
- `ai-sdk/google-vertex/${VERSION}`,
1008
- getRuntimeEnvironmentUserAgent()
1009
- ),
1010
- body: new URLSearchParams({
1011
- grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
1012
- assertion: jwt
1013
- })
1014
- });
1015
- if (!response.ok) {
1016
- throw new Error(`Token request failed: ${response.statusText}`);
1017
- }
1018
- const data = await response.json();
1019
- return data.access_token;
1020
- } catch (error) {
1021
- throw error;
1022
- }
1023
- }
1024
-
1025
- // src/edge/google-vertex-provider-edge.ts
1026
- function createVertex2(options = {}) {
1027
- const apiKey = loadOptionalSetting3({
1028
- settingValue: options.apiKey,
1029
- environmentVariableName: "GOOGLE_VERTEX_API_KEY"
1030
- });
1031
- if (apiKey) {
1032
- return createVertex(options);
1033
- }
1034
- return createVertex({
1035
- ...options,
1036
- headers: async () => ({
1037
- Authorization: `Bearer ${await generateAuthToken(
1038
- options.googleCredentials
1039
- )}`,
1040
- ...await resolve5(options.headers)
1041
- })
1042
- });
1043
- }
1044
- var vertex = createVertex2();
1045
- export {
1046
- createVertex2 as createVertex,
1047
- vertex
1048
- };
1049
- //# sourceMappingURL=index.mjs.map