@ai-sdk/google-vertex 0.0.40 → 0.0.43

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/CHANGELOG.md CHANGED
@@ -1,5 +1,36 @@
1
1
  # @ai-sdk/google-vertex
2
2
 
3
+ ## 0.0.43
4
+
5
+ ### Patch Changes
6
+
7
+ - 4360e2d: feat (provider/vertex): expose search grounding metadata
8
+ - e7823a3: feat (provider/vertex): add embedding support
9
+
10
+ ## 0.0.42
11
+
12
+ ### Patch Changes
13
+
14
+ - aa98cdb: chore: more flexible dependency versioning
15
+ - 1486128: feat: add supportsUrl to language model specification
16
+ - 1486128: feat (provider/google): support native file URLs without download
17
+ - 3b1b69a: feat: provider-defined tools
18
+ - Updated dependencies [aa98cdb]
19
+ - Updated dependencies [1486128]
20
+ - Updated dependencies [7b937c5]
21
+ - Updated dependencies [3b1b69a]
22
+ - Updated dependencies [811a317]
23
+ - @ai-sdk/provider-utils@1.0.22
24
+ - @ai-sdk/provider@0.0.26
25
+
26
+ ## 0.0.41
27
+
28
+ ### Patch Changes
29
+
30
+ - Updated dependencies [b9b0d7b]
31
+ - @ai-sdk/provider@0.0.25
32
+ - @ai-sdk/provider-utils@1.0.21
33
+
3
34
  ## 0.0.40
4
35
 
5
36
  ### Patch Changes
package/dist/index.js CHANGED
@@ -26,14 +26,13 @@ __export(src_exports, {
26
26
  module.exports = __toCommonJS(src_exports);
27
27
 
28
28
  // src/google-vertex-provider.ts
29
- var import_provider3 = require("@ai-sdk/provider");
30
- var import_provider_utils3 = require("@ai-sdk/provider-utils");
31
- var import_vertexai2 = require("@google-cloud/vertexai");
29
+ var import_provider_utils5 = require("@ai-sdk/provider-utils");
30
+ var import_vertexai3 = require("@google-cloud/vertexai");
32
31
 
33
32
  // src/google-vertex-language-model.ts
34
33
  var import_provider2 = require("@ai-sdk/provider");
35
34
  var import_provider_utils2 = require("@ai-sdk/provider-utils");
36
- var import_vertexai = require("@google-cloud/vertexai");
35
+ var import_vertexai2 = require("@google-cloud/vertexai");
37
36
 
38
37
  // src/convert-json-schema-to-openapi-schema.ts
39
38
  function convertJSONSchemaToOpenAPISchema(jsonSchema) {
@@ -107,7 +106,7 @@ function convertJSONSchemaToOpenAPISchema(jsonSchema) {
107
106
  var import_provider = require("@ai-sdk/provider");
108
107
  var import_provider_utils = require("@ai-sdk/provider-utils");
109
108
  function convertToGoogleVertexContentRequest(prompt) {
110
- var _a;
109
+ var _a, _b;
111
110
  const systemInstructionParts = [];
112
111
  const contents = [];
113
112
  let systemMessagesAllowed = true;
@@ -132,28 +131,35 @@ function convertToGoogleVertexContentRequest(prompt) {
132
131
  break;
133
132
  }
134
133
  case "image": {
135
- if (part.image instanceof URL) {
136
- throw new import_provider.UnsupportedFunctionalityError({
137
- functionality: "Image URLs in user messages"
138
- });
139
- }
140
- parts.push({
141
- inlineData: {
142
- mimeType: (_a = part.mimeType) != null ? _a : "image/jpeg",
143
- data: (0, import_provider_utils.convertUint8ArrayToBase64)(part.image)
134
+ parts.push(
135
+ part.image instanceof URL ? {
136
+ fileData: {
137
+ mimeType: (_a = part.mimeType) != null ? _a : "image/jpeg",
138
+ fileUri: part.image.toString()
139
+ }
140
+ } : {
141
+ inlineData: {
142
+ mimeType: (_b = part.mimeType) != null ? _b : "image/jpeg",
143
+ data: (0, import_provider_utils.convertUint8ArrayToBase64)(part.image)
144
+ }
144
145
  }
145
- });
146
+ );
146
147
  break;
147
148
  }
148
149
  case "file": {
149
- if (part.data instanceof URL) {
150
- throw new import_provider.UnsupportedFunctionalityError({
151
- functionality: "File URLs in user messages"
152
- });
153
- }
154
- parts.push({
155
- inlineData: { mimeType: part.mimeType, data: part.data }
156
- });
150
+ parts.push(
151
+ part.data instanceof URL ? {
152
+ fileData: {
153
+ mimeType: part.mimeType,
154
+ fileUri: part.data.toString()
155
+ }
156
+ } : {
157
+ inlineData: {
158
+ mimeType: part.mimeType,
159
+ data: part.data
160
+ }
161
+ }
162
+ );
157
163
  break;
158
164
  }
159
165
  default: {
@@ -222,6 +228,89 @@ function convertToGoogleVertexContentRequest(prompt) {
222
228
  };
223
229
  }
224
230
 
231
+ // src/google-vertex-prepare-tools.ts
232
+ var import_vertexai = require("@google-cloud/vertexai");
233
+ function prepareTools({
234
+ useSearchGrounding,
235
+ mode
236
+ }) {
237
+ var _a, _b;
238
+ const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
239
+ const toolWarnings = [];
240
+ const vertexTools = [];
241
+ if (tools != null) {
242
+ const functionDeclarations = [];
243
+ for (const tool of tools) {
244
+ if (tool.type === "provider-defined") {
245
+ toolWarnings.push({ type: "unsupported-tool", tool });
246
+ } else {
247
+ functionDeclarations.push({
248
+ name: tool.name,
249
+ description: (_b = tool.description) != null ? _b : "",
250
+ parameters: convertJSONSchemaToOpenAPISchema(
251
+ tool.parameters
252
+ )
253
+ });
254
+ }
255
+ }
256
+ vertexTools.push({ functionDeclarations });
257
+ }
258
+ if (useSearchGrounding) {
259
+ vertexTools.push({ googleSearchRetrieval: {} });
260
+ }
261
+ const finalTools = vertexTools.length > 0 ? vertexTools : void 0;
262
+ const toolChoice = mode.toolChoice;
263
+ if (toolChoice == null) {
264
+ return {
265
+ tools: finalTools,
266
+ toolConfig: void 0,
267
+ toolWarnings
268
+ };
269
+ }
270
+ const type = toolChoice.type;
271
+ switch (type) {
272
+ case "auto":
273
+ return {
274
+ tools: finalTools,
275
+ toolConfig: {
276
+ functionCallingConfig: { mode: import_vertexai.FunctionCallingMode.AUTO }
277
+ },
278
+ toolWarnings
279
+ };
280
+ case "none":
281
+ return {
282
+ tools: finalTools,
283
+ toolConfig: {
284
+ functionCallingConfig: { mode: import_vertexai.FunctionCallingMode.NONE }
285
+ },
286
+ toolWarnings
287
+ };
288
+ case "required":
289
+ return {
290
+ tools: finalTools,
291
+ toolConfig: {
292
+ functionCallingConfig: { mode: import_vertexai.FunctionCallingMode.ANY }
293
+ },
294
+ toolWarnings
295
+ };
296
+ case "tool":
297
+ return {
298
+ tools: finalTools,
299
+ toolConfig: {
300
+ functionCallingConfig: {
301
+ mode: import_vertexai.FunctionCallingMode.ANY,
302
+ allowedFunctionNames: [toolChoice.toolName]
303
+ }
304
+ },
305
+ toolWarnings
306
+ };
307
+ default: {
308
+ const _exhaustiveCheck = type;
309
+ throw new Error(`Unsupported tool choice type: ${_exhaustiveCheck}`);
310
+ }
311
+ }
312
+ }
313
+
225
314
  // src/map-google-vertex-finish-reason.ts
226
315
  function mapGoogleVertexFinishReason({
227
316
  finishReason,
@@ -314,19 +403,21 @@ var GoogleVertexLanguageModel = class {
314
403
  const type = mode.type;
315
404
  switch (type) {
316
405
  case "regular": {
406
+ const { tools, toolConfig, toolWarnings } = prepareTools({
407
+ mode,
408
+ useSearchGrounding: (_a = this.settings.useSearchGrounding) != null ? _a : false
409
+ });
317
410
  const configuration = {
318
411
  model: this.modelId,
319
412
  generationConfig,
320
- ...prepareToolsAndToolConfig({
321
- mode,
322
- useSearchGrounding: (_a = this.settings.useSearchGrounding) != null ? _a : false
323
- }),
413
+ tools,
414
+ toolConfig,
324
415
  safetySettings: this.settings.safetySettings
325
416
  };
326
417
  return {
327
418
  model: this.config.vertexAI.getGenerativeModel(configuration),
328
419
  contentRequest: convertToGoogleVertexContentRequest(prompt),
329
- warnings
420
+ warnings: [...warnings, ...toolWarnings]
330
421
  };
331
422
  }
332
423
  case "object-json": {
@@ -366,7 +457,7 @@ var GoogleVertexLanguageModel = class {
366
457
  }
367
458
  ],
368
459
  toolConfig: {
369
- functionCallingConfig: { mode: import_vertexai.FunctionCallingMode.ANY }
460
+ functionCallingConfig: { mode: import_vertexai2.FunctionCallingMode.ANY }
370
461
  },
371
462
  safetySettings: this.settings.safetySettings
372
463
  };
@@ -382,6 +473,9 @@ var GoogleVertexLanguageModel = class {
382
473
  }
383
474
  }
384
475
  }
476
+ supportsUrl(url) {
477
+ return url.protocol === "gs:";
478
+ }
385
479
  async doGenerate(options) {
386
480
  var _a, _b, _c;
387
481
  const { model, contentRequest, warnings } = await this.getArgs(options);
@@ -411,6 +505,11 @@ var GoogleVertexLanguageModel = class {
411
505
  rawPrompt: contentRequest,
412
506
  rawSettings: {}
413
507
  },
508
+ providerMetadata: this.settings.useSearchGrounding ? {
509
+ vertex: {
510
+ groundingMetadata: firstCandidate.groundingMetadata
511
+ }
512
+ } : void 0,
414
513
  warnings
415
514
  };
416
515
  }
@@ -424,6 +523,7 @@ var GoogleVertexLanguageModel = class {
424
523
  };
425
524
  const generateId2 = this.config.generateId;
426
525
  let hasToolCalls = false;
526
+ let providerMetadata;
427
527
  return {
428
528
  stream: (0, import_provider_utils2.convertAsyncGeneratorToReadableStream)(stream).pipeThrough(
429
529
  new TransformStream(
@@ -447,6 +547,13 @@ var GoogleVertexLanguageModel = class {
447
547
  hasToolCalls
448
548
  });
449
549
  }
550
+ if (candidate.groundingMetadata != null) {
551
+ providerMetadata = {
552
+ vertex: {
553
+ groundingMetadata: candidate.groundingMetadata
554
+ }
555
+ };
556
+ }
450
557
  const content = candidate.content;
451
558
  const deltaText = getTextFromParts(content.parts);
452
559
  if (deltaText != null) {
@@ -483,7 +590,8 @@ var GoogleVertexLanguageModel = class {
483
590
  controller.enqueue({
484
591
  type: "finish",
485
592
  finishReason,
486
- usage
593
+ usage,
594
+ providerMetadata
487
595
  });
488
596
  }
489
597
  }
@@ -497,76 +605,6 @@ var GoogleVertexLanguageModel = class {
497
605
  };
498
606
  }
499
607
  };
500
- function prepareToolsAndToolConfig({
501
- useSearchGrounding,
502
- mode
503
- }) {
504
- var _a;
505
- const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
506
- const mappedTools = tools == null ? [] : [
507
- {
508
- functionDeclarations: tools.map((tool) => {
509
- var _a2;
510
- return {
511
- name: tool.name,
512
- description: (_a2 = tool.description) != null ? _a2 : "",
513
- parameters: convertJSONSchemaToOpenAPISchema(
514
- tool.parameters
515
- )
516
- };
517
- })
518
- }
519
- ];
520
- if (useSearchGrounding) {
521
- mappedTools.push({ googleSearchRetrieval: {} });
522
- }
523
- const finalTools = mappedTools.length > 0 ? mappedTools : void 0;
524
- const toolChoice = mode.toolChoice;
525
- if (toolChoice == null) {
526
- return {
527
- tools: finalTools,
528
- toolConfig: void 0
529
- };
530
- }
531
- const type = toolChoice.type;
532
- switch (type) {
533
- case "auto":
534
- return {
535
- tools: finalTools,
536
- toolConfig: {
537
- functionCallingConfig: { mode: import_vertexai.FunctionCallingMode.AUTO }
538
- }
539
- };
540
- case "none":
541
- return {
542
- tools: finalTools,
543
- toolConfig: {
544
- functionCallingConfig: { mode: import_vertexai.FunctionCallingMode.NONE }
545
- }
546
- };
547
- case "required":
548
- return {
549
- tools: finalTools,
550
- toolConfig: {
551
- functionCallingConfig: { mode: import_vertexai.FunctionCallingMode.ANY }
552
- }
553
- };
554
- case "tool":
555
- return {
556
- tools: finalTools,
557
- toolConfig: {
558
- functionCallingConfig: {
559
- mode: import_vertexai.FunctionCallingMode.ANY,
560
- allowedFunctionNames: [toolChoice.toolName]
561
- }
562
- }
563
- };
564
- default: {
565
- const _exhaustiveCheck = type;
566
- throw new Error(`Unsupported tool choice type: ${_exhaustiveCheck}`);
567
- }
568
- }
569
- }
570
608
  function getToolCallsFromParts({
571
609
  parts,
572
610
  generateId: generateId2
@@ -591,32 +629,138 @@ function getTextFromParts(parts) {
591
629
  return textParts.length === 0 ? void 0 : textParts.map((part) => part.text).join("");
592
630
  }
593
631
 
632
+ // src/google-vertex-embedding-model.ts
633
+ var import_provider3 = require("@ai-sdk/provider");
634
+ var import_provider_utils4 = require("@ai-sdk/provider-utils");
635
+ var import_zod2 = require("zod");
636
+
637
+ // src/google-error.ts
638
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
639
+ var import_zod = require("zod");
640
+ var googleErrorDataSchema = import_zod.z.object({
641
+ error: import_zod.z.object({
642
+ code: import_zod.z.number().nullable(),
643
+ message: import_zod.z.string(),
644
+ status: import_zod.z.string()
645
+ })
646
+ });
647
+ var googleFailedResponseHandler = (0, import_provider_utils3.createJsonErrorResponseHandler)({
648
+ errorSchema: googleErrorDataSchema,
649
+ errorToMessage: (data) => data.error.message
650
+ });
651
+
652
+ // src/google-vertex-embedding-model.ts
653
+ var GoogleVertexEmbeddingModel = class {
654
+ constructor(modelId, settings, config) {
655
+ this.specificationVersion = "v1";
656
+ this.modelId = modelId;
657
+ this.settings = settings;
658
+ this.config = config;
659
+ }
660
+ get provider() {
661
+ return this.config.provider;
662
+ }
663
+ get maxEmbeddingsPerCall() {
664
+ return 2048;
665
+ }
666
+ get supportsParallelCalls() {
667
+ return true;
668
+ }
669
+ async doEmbed({
670
+ values,
671
+ headers,
672
+ abortSignal
673
+ }) {
674
+ if (values.length > this.maxEmbeddingsPerCall) {
675
+ throw new import_provider3.TooManyEmbeddingValuesForCallError({
676
+ provider: this.provider,
677
+ modelId: this.modelId,
678
+ maxEmbeddingsPerCall: this.maxEmbeddingsPerCall,
679
+ values
680
+ });
681
+ }
682
+ const { responseHeaders, value: response } = await (0, import_provider_utils4.postJsonToApi)({
683
+ url: `https://${this.config.region}-aiplatform.googleapis.com/v1/projects/${this.config.project}/locations/${this.config.region}/publishers/google/models/${this.modelId}:predict`,
684
+ headers: (0, import_provider_utils4.combineHeaders)(
685
+ { Authorization: `Bearer ${await this.config.generateAuthToken()}` },
686
+ headers
687
+ ),
688
+ body: {
689
+ instances: values.map((value) => ({ content: value })),
690
+ parameters: {
691
+ outputDimensionality: this.settings.outputDimensionality
692
+ }
693
+ },
694
+ failedResponseHandler: googleFailedResponseHandler,
695
+ successfulResponseHandler: (0, import_provider_utils4.createJsonResponseHandler)(
696
+ googleVertexTextEmbeddingResponseSchema
697
+ ),
698
+ abortSignal
699
+ });
700
+ return {
701
+ embeddings: response.predictions.map(
702
+ (prediction) => prediction.embeddings.values
703
+ ),
704
+ usage: {
705
+ tokens: response.predictions.reduce(
706
+ (tokenCount, prediction) => tokenCount + prediction.embeddings.statistics.token_count,
707
+ 0
708
+ )
709
+ },
710
+ rawResponse: { headers: responseHeaders }
711
+ };
712
+ }
713
+ };
714
+ var googleVertexTextEmbeddingResponseSchema = import_zod2.z.object({
715
+ predictions: import_zod2.z.array(
716
+ import_zod2.z.object({
717
+ embeddings: import_zod2.z.object({
718
+ values: import_zod2.z.array(import_zod2.z.number()),
719
+ statistics: import_zod2.z.object({
720
+ token_count: import_zod2.z.number()
721
+ })
722
+ })
723
+ })
724
+ )
725
+ });
726
+
594
727
  // src/google-vertex-provider.ts
595
728
  function createVertex(options = {}) {
729
+ const loadVertexProject = () => (0, import_provider_utils5.loadSetting)({
730
+ settingValue: options.project,
731
+ settingName: "project",
732
+ environmentVariableName: "GOOGLE_VERTEX_PROJECT",
733
+ description: "Google Vertex project"
734
+ });
735
+ const loadVertexLocation = () => (0, import_provider_utils5.loadSetting)({
736
+ settingValue: options.location,
737
+ settingName: "location",
738
+ environmentVariableName: "GOOGLE_VERTEX_LOCATION",
739
+ description: "Google Vertex location"
740
+ });
596
741
  const createVertexAI = () => {
597
742
  var _a, _b;
598
743
  const config = {
599
- project: (0, import_provider_utils3.loadSetting)({
600
- settingValue: options.project,
601
- settingName: "project",
602
- environmentVariableName: "GOOGLE_VERTEX_PROJECT",
603
- description: "Google Vertex project"
604
- }),
605
- location: (0, import_provider_utils3.loadSetting)({
606
- settingValue: options.location,
607
- settingName: "location",
608
- environmentVariableName: "GOOGLE_VERTEX_LOCATION",
609
- description: "Google Vertex location"
610
- }),
744
+ project: loadVertexProject(),
745
+ location: loadVertexLocation(),
611
746
  googleAuthOptions: options.googleAuthOptions
612
747
  };
613
- return (_b = (_a = options.createVertexAI) == null ? void 0 : _a.call(options, config)) != null ? _b : new import_vertexai2.VertexAI(config);
748
+ return (_b = (_a = options.createVertexAI) == null ? void 0 : _a.call(options, config)) != null ? _b : new import_vertexai3.VertexAI(config);
614
749
  };
615
750
  const createChatModel = (modelId, settings = {}) => {
616
751
  var _a;
617
752
  return new GoogleVertexLanguageModel(modelId, settings, {
618
753
  vertexAI: createVertexAI(),
619
- generateId: (_a = options.generateId) != null ? _a : import_provider_utils3.generateId
754
+ generateId: (_a = options.generateId) != null ? _a : import_provider_utils5.generateId
755
+ });
756
+ };
757
+ const createEmbeddingModel = (modelId, settings = {}) => {
758
+ const vertexAI = createVertexAI();
759
+ return new GoogleVertexEmbeddingModel(modelId, settings, {
760
+ provider: "google.vertex",
761
+ region: loadVertexLocation(),
762
+ project: loadVertexProject(),
763
+ generateAuthToken: () => vertexAI.googleAuth.getAccessToken()
620
764
  });
621
765
  };
622
766
  const provider = function(modelId, settings) {
@@ -628,9 +772,7 @@ function createVertex(options = {}) {
628
772
  return createChatModel(modelId, settings);
629
773
  };
630
774
  provider.languageModel = createChatModel;
631
- provider.textEmbeddingModel = (modelId) => {
632
- throw new import_provider3.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
633
- };
775
+ provider.textEmbeddingModel = createEmbeddingModel;
634
776
  return provider;
635
777
  }
636
778
  var vertex = createVertex();