@google/genai 1.40.0 → 1.42.0

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.
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ var pRetry = require('p-retry');
3
4
  var googleAuthLibrary = require('google-auth-library');
4
5
  var fs = require('fs');
5
6
  var fs$1 = require('fs/promises');
@@ -1387,6 +1388,18 @@ exports.Environment = void 0;
1387
1388
  */
1388
1389
  Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER";
1389
1390
  })(exports.Environment || (exports.Environment = {}));
1391
+ /** Enum representing the Vertex embedding API to use. */
1392
+ exports.EmbeddingApiType = void 0;
1393
+ (function (EmbeddingApiType) {
1394
+ /**
1395
+ * predict API endpoint (default)
1396
+ */
1397
+ EmbeddingApiType["PREDICT"] = "PREDICT";
1398
+ /**
1399
+ * embedContent API Endpoint
1400
+ */
1401
+ EmbeddingApiType["EMBED_CONTENT"] = "EMBED_CONTENT";
1402
+ })(exports.EmbeddingApiType || (exports.EmbeddingApiType = {}));
1390
1403
  /** Enum that controls the safety filter level for objectionable content. */
1391
1404
  exports.SafetyFilterLevel = void 0;
1392
1405
  (function (SafetyFilterLevel) {
@@ -3418,6 +3431,10 @@ function tJobState(state) {
3418
3431
  return stateString;
3419
3432
  }
3420
3433
  }
3434
+ function tIsVertexEmbedContentModel(model) {
3435
+ return ((model.includes('gemini') && model !== 'gemini-embedding-001') ||
3436
+ model.includes('maas'));
3437
+ }
3421
3438
 
3422
3439
  /**
3423
3440
  * @license
@@ -8659,33 +8676,103 @@ function embedContentConfigToMldev(fromObject, parentObject, _rootObject) {
8659
8676
  }
8660
8677
  return toObject;
8661
8678
  }
8662
- function embedContentConfigToVertex(fromObject, parentObject, _rootObject) {
8679
+ function embedContentConfigToVertex(fromObject, parentObject, rootObject) {
8663
8680
  const toObject = {};
8664
- const fromTaskType = getValueByPath(fromObject, ['taskType']);
8665
- if (parentObject !== undefined && fromTaskType != null) {
8666
- setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType);
8681
+ let discriminatorTaskType = getValueByPath(rootObject, [
8682
+ 'embeddingApiType',
8683
+ ]);
8684
+ if (discriminatorTaskType === undefined) {
8685
+ discriminatorTaskType = 'PREDICT';
8667
8686
  }
8668
- const fromTitle = getValueByPath(fromObject, ['title']);
8669
- if (parentObject !== undefined && fromTitle != null) {
8670
- setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);
8687
+ if (discriminatorTaskType === 'PREDICT') {
8688
+ const fromTaskType = getValueByPath(fromObject, ['taskType']);
8689
+ if (parentObject !== undefined && fromTaskType != null) {
8690
+ setValueByPath(parentObject, ['instances[]', 'task_type'], fromTaskType);
8691
+ }
8671
8692
  }
8672
- const fromOutputDimensionality = getValueByPath(fromObject, [
8673
- 'outputDimensionality',
8693
+ else if (discriminatorTaskType === 'EMBED_CONTENT') {
8694
+ const fromTaskType = getValueByPath(fromObject, ['taskType']);
8695
+ if (parentObject !== undefined && fromTaskType != null) {
8696
+ setValueByPath(parentObject, ['taskType'], fromTaskType);
8697
+ }
8698
+ }
8699
+ let discriminatorTitle = getValueByPath(rootObject, [
8700
+ 'embeddingApiType',
8674
8701
  ]);
8675
- if (parentObject !== undefined && fromOutputDimensionality != null) {
8676
- setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality);
8702
+ if (discriminatorTitle === undefined) {
8703
+ discriminatorTitle = 'PREDICT';
8677
8704
  }
8678
- const fromMimeType = getValueByPath(fromObject, ['mimeType']);
8679
- if (parentObject !== undefined && fromMimeType != null) {
8680
- setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType);
8705
+ if (discriminatorTitle === 'PREDICT') {
8706
+ const fromTitle = getValueByPath(fromObject, ['title']);
8707
+ if (parentObject !== undefined && fromTitle != null) {
8708
+ setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);
8709
+ }
8681
8710
  }
8682
- const fromAutoTruncate = getValueByPath(fromObject, ['autoTruncate']);
8683
- if (parentObject !== undefined && fromAutoTruncate != null) {
8684
- setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate);
8711
+ else if (discriminatorTitle === 'EMBED_CONTENT') {
8712
+ const fromTitle = getValueByPath(fromObject, ['title']);
8713
+ if (parentObject !== undefined && fromTitle != null) {
8714
+ setValueByPath(parentObject, ['title'], fromTitle);
8715
+ }
8716
+ }
8717
+ let discriminatorOutputDimensionality = getValueByPath(rootObject, [
8718
+ 'embeddingApiType',
8719
+ ]);
8720
+ if (discriminatorOutputDimensionality === undefined) {
8721
+ discriminatorOutputDimensionality = 'PREDICT';
8722
+ }
8723
+ if (discriminatorOutputDimensionality === 'PREDICT') {
8724
+ const fromOutputDimensionality = getValueByPath(fromObject, [
8725
+ 'outputDimensionality',
8726
+ ]);
8727
+ if (parentObject !== undefined && fromOutputDimensionality != null) {
8728
+ setValueByPath(parentObject, ['parameters', 'outputDimensionality'], fromOutputDimensionality);
8729
+ }
8730
+ }
8731
+ else if (discriminatorOutputDimensionality === 'EMBED_CONTENT') {
8732
+ const fromOutputDimensionality = getValueByPath(fromObject, [
8733
+ 'outputDimensionality',
8734
+ ]);
8735
+ if (parentObject !== undefined && fromOutputDimensionality != null) {
8736
+ setValueByPath(parentObject, ['outputDimensionality'], fromOutputDimensionality);
8737
+ }
8738
+ }
8739
+ let discriminatorMimeType = getValueByPath(rootObject, [
8740
+ 'embeddingApiType',
8741
+ ]);
8742
+ if (discriminatorMimeType === undefined) {
8743
+ discriminatorMimeType = 'PREDICT';
8744
+ }
8745
+ if (discriminatorMimeType === 'PREDICT') {
8746
+ const fromMimeType = getValueByPath(fromObject, ['mimeType']);
8747
+ if (parentObject !== undefined && fromMimeType != null) {
8748
+ setValueByPath(parentObject, ['instances[]', 'mimeType'], fromMimeType);
8749
+ }
8750
+ }
8751
+ let discriminatorAutoTruncate = getValueByPath(rootObject, [
8752
+ 'embeddingApiType',
8753
+ ]);
8754
+ if (discriminatorAutoTruncate === undefined) {
8755
+ discriminatorAutoTruncate = 'PREDICT';
8756
+ }
8757
+ if (discriminatorAutoTruncate === 'PREDICT') {
8758
+ const fromAutoTruncate = getValueByPath(fromObject, [
8759
+ 'autoTruncate',
8760
+ ]);
8761
+ if (parentObject !== undefined && fromAutoTruncate != null) {
8762
+ setValueByPath(parentObject, ['parameters', 'autoTruncate'], fromAutoTruncate);
8763
+ }
8764
+ }
8765
+ else if (discriminatorAutoTruncate === 'EMBED_CONTENT') {
8766
+ const fromAutoTruncate = getValueByPath(fromObject, [
8767
+ 'autoTruncate',
8768
+ ]);
8769
+ if (parentObject !== undefined && fromAutoTruncate != null) {
8770
+ setValueByPath(parentObject, ['autoTruncate'], fromAutoTruncate);
8771
+ }
8685
8772
  }
8686
8773
  return toObject;
8687
8774
  }
8688
- function embedContentParametersToMldev(apiClient, fromObject, rootObject) {
8775
+ function embedContentParametersPrivateToMldev(apiClient, fromObject, rootObject) {
8689
8776
  const toObject = {};
8690
8777
  const fromModel = getValueByPath(fromObject, ['model']);
8691
8778
  if (fromModel != null) {
@@ -8701,6 +8788,10 @@ function embedContentParametersToMldev(apiClient, fromObject, rootObject) {
8701
8788
  }
8702
8789
  setValueByPath(toObject, ['requests[]', 'content'], transformedList);
8703
8790
  }
8791
+ const fromContent = getValueByPath(fromObject, ['content']);
8792
+ if (fromContent != null) {
8793
+ contentToMldev$1(tContent(fromContent));
8794
+ }
8704
8795
  const fromConfig = getValueByPath(fromObject, ['config']);
8705
8796
  if (fromConfig != null) {
8706
8797
  embedContentConfigToMldev(fromConfig, toObject);
@@ -8711,25 +8802,45 @@ function embedContentParametersToMldev(apiClient, fromObject, rootObject) {
8711
8802
  }
8712
8803
  return toObject;
8713
8804
  }
8714
- function embedContentParametersToVertex(apiClient, fromObject, rootObject) {
8805
+ function embedContentParametersPrivateToVertex(apiClient, fromObject, rootObject) {
8715
8806
  const toObject = {};
8716
8807
  const fromModel = getValueByPath(fromObject, ['model']);
8717
8808
  if (fromModel != null) {
8718
8809
  setValueByPath(toObject, ['_url', 'model'], tModel(apiClient, fromModel));
8719
8810
  }
8720
- const fromContents = getValueByPath(fromObject, ['contents']);
8721
- if (fromContents != null) {
8722
- let transformedList = tContentsForEmbed(apiClient, fromContents);
8723
- if (Array.isArray(transformedList)) {
8724
- transformedList = transformedList.map((item) => {
8725
- return item;
8726
- });
8811
+ let discriminatorContents = getValueByPath(rootObject, [
8812
+ 'embeddingApiType',
8813
+ ]);
8814
+ if (discriminatorContents === undefined) {
8815
+ discriminatorContents = 'PREDICT';
8816
+ }
8817
+ if (discriminatorContents === 'PREDICT') {
8818
+ const fromContents = getValueByPath(fromObject, ['contents']);
8819
+ if (fromContents != null) {
8820
+ let transformedList = tContentsForEmbed(apiClient, fromContents);
8821
+ if (Array.isArray(transformedList)) {
8822
+ transformedList = transformedList.map((item) => {
8823
+ return item;
8824
+ });
8825
+ }
8826
+ setValueByPath(toObject, ['instances[]', 'content'], transformedList);
8827
+ }
8828
+ }
8829
+ let discriminatorContent = getValueByPath(rootObject, [
8830
+ 'embeddingApiType',
8831
+ ]);
8832
+ if (discriminatorContent === undefined) {
8833
+ discriminatorContent = 'PREDICT';
8834
+ }
8835
+ if (discriminatorContent === 'EMBED_CONTENT') {
8836
+ const fromContent = getValueByPath(fromObject, ['content']);
8837
+ if (fromContent != null) {
8838
+ setValueByPath(toObject, ['content'], tContent(fromContent));
8727
8839
  }
8728
- setValueByPath(toObject, ['instances[]', 'content'], transformedList);
8729
8840
  }
8730
8841
  const fromConfig = getValueByPath(fromObject, ['config']);
8731
8842
  if (fromConfig != null) {
8732
- embedContentConfigToVertex(fromConfig, toObject);
8843
+ embedContentConfigToVertex(fromConfig, toObject, rootObject);
8733
8844
  }
8734
8845
  return toObject;
8735
8846
  }
@@ -8782,6 +8893,24 @@ function embedContentResponseFromVertex(fromObject, rootObject) {
8782
8893
  if (fromMetadata != null) {
8783
8894
  setValueByPath(toObject, ['metadata'], fromMetadata);
8784
8895
  }
8896
+ if (rootObject &&
8897
+ getValueByPath(rootObject, ['embeddingApiType']) === 'EMBED_CONTENT') {
8898
+ const embedding = getValueByPath(fromObject, ['embedding']);
8899
+ const usageMetadata = getValueByPath(fromObject, ['usageMetadata']);
8900
+ const truncated = getValueByPath(fromObject, ['truncated']);
8901
+ if (embedding) {
8902
+ const stats = {};
8903
+ if (usageMetadata &&
8904
+ usageMetadata['promptTokenCount']) {
8905
+ stats.tokenCount = usageMetadata['promptTokenCount'];
8906
+ }
8907
+ if (truncated) {
8908
+ stats.truncated = truncated;
8909
+ }
8910
+ embedding.statistics = stats;
8911
+ setValueByPath(toObject, ['embeddings'], [embedding]);
8912
+ }
8913
+ }
8785
8914
  return toObject;
8786
8915
  }
8787
8916
  function endpointFromVertex(fromObject, _rootObject) {
@@ -11639,10 +11768,22 @@ const CONTENT_TYPE_HEADER = 'Content-Type';
11639
11768
  const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';
11640
11769
  const USER_AGENT_HEADER = 'User-Agent';
11641
11770
  const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';
11642
- const SDK_VERSION = '1.40.0'; // x-release-please-version
11771
+ const SDK_VERSION = '1.42.0'; // x-release-please-version
11643
11772
  const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;
11644
11773
  const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';
11645
11774
  const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';
11775
+ // Default retry options.
11776
+ // The config is based on https://cloud.google.com/storage/docs/retry-strategy.
11777
+ const DEFAULT_RETRY_ATTEMPTS = 5; // Including the initial call
11778
+ // LINT.IfChange
11779
+ const DEFAULT_RETRY_HTTP_STATUS_CODES = [
11780
+ 408, // Request timeout
11781
+ 429, // Too many requests
11782
+ 500, // Internal server error
11783
+ 502, // Bad gateway
11784
+ 503, // Service unavailable
11785
+ 504, // Gateway timeout
11786
+ ];
11646
11787
  /**
11647
11788
  * The ApiClient class is used to send requests to the Gemini API or Vertex AI
11648
11789
  * endpoints.
@@ -12027,8 +12168,25 @@ class ApiClient {
12027
12168
  });
12028
12169
  }
12029
12170
  async apiCall(url, requestInit) {
12030
- return fetch(url, requestInit).catch((e) => {
12031
- throw new Error(`exception ${e} sending request`);
12171
+ var _a;
12172
+ if (!this.clientOptions.httpOptions ||
12173
+ !this.clientOptions.httpOptions.retryOptions) {
12174
+ return fetch(url, requestInit);
12175
+ }
12176
+ const retryOptions = this.clientOptions.httpOptions.retryOptions;
12177
+ const runFetch = async () => {
12178
+ const response = await fetch(url, requestInit);
12179
+ if (response.ok) {
12180
+ return response;
12181
+ }
12182
+ if (DEFAULT_RETRY_HTTP_STATUS_CODES.includes(response.status)) {
12183
+ throw new Error(`Retryable HTTP Error: ${response.statusText}`);
12184
+ }
12185
+ throw new pRetry.AbortError(`Non-retryable exception ${response.statusText} sending request`);
12186
+ };
12187
+ return pRetry(runFetch, {
12188
+ // Retry attempts is one less than the number of total attempts.
12189
+ retries: ((_a = retryOptions.attempts) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_ATTEMPTS) - 1,
12032
12190
  });
12033
12191
  }
12034
12192
  getDefaultHeaders() {
@@ -13211,6 +13369,47 @@ class Models extends BaseModule {
13211
13369
  constructor(apiClient) {
13212
13370
  super();
13213
13371
  this.apiClient = apiClient;
13372
+ /**
13373
+ * Calculates embeddings for the given contents.
13374
+ *
13375
+ * @param params - The parameters for embedding contents.
13376
+ * @return The response from the API.
13377
+ *
13378
+ * @example
13379
+ * ```ts
13380
+ * const response = await ai.models.embedContent({
13381
+ * model: 'text-embedding-004',
13382
+ * contents: [
13383
+ * 'What is your name?',
13384
+ * 'What is your favorite color?',
13385
+ * ],
13386
+ * config: {
13387
+ * outputDimensionality: 64,
13388
+ * },
13389
+ * });
13390
+ * console.log(response);
13391
+ * ```
13392
+ */
13393
+ this.embedContent = async (params) => {
13394
+ if (!this.apiClient.isVertexAI()) {
13395
+ return await this.embedContentInternal(params);
13396
+ }
13397
+ const isVertexEmbedContentModel = (params.model.includes('gemini') &&
13398
+ params.model !== 'gemini-embedding-001') ||
13399
+ params.model.includes('maas');
13400
+ if (isVertexEmbedContentModel) {
13401
+ const contents = tContents(params.contents);
13402
+ if (contents.length > 1) {
13403
+ throw new Error('The embedContent API for this model only supports one content at a time.');
13404
+ }
13405
+ const paramsPrivate = Object.assign(Object.assign({}, params), { content: contents[0], embeddingApiType: exports.EmbeddingApiType.EMBED_CONTENT });
13406
+ return await this.embedContentInternal(paramsPrivate);
13407
+ }
13408
+ else {
13409
+ const paramsPrivate = Object.assign(Object.assign({}, params), { embeddingApiType: exports.EmbeddingApiType.PREDICT });
13410
+ return await this.embedContentInternal(paramsPrivate);
13411
+ }
13412
+ };
13214
13413
  /**
13215
13414
  * Makes an API request to generate content with a given model.
13216
13415
  *
@@ -13898,14 +14097,17 @@ class Models extends BaseModule {
13898
14097
  * console.log(response);
13899
14098
  * ```
13900
14099
  */
13901
- async embedContent(params) {
14100
+ async embedContentInternal(params) {
13902
14101
  var _a, _b, _c, _d;
13903
14102
  let response;
13904
14103
  let path = '';
13905
14104
  let queryParams = {};
13906
14105
  if (this.apiClient.isVertexAI()) {
13907
- const body = embedContentParametersToVertex(this.apiClient, params);
13908
- path = formatMap('{model}:predict', body['_url']);
14106
+ const body = embedContentParametersPrivateToVertex(this.apiClient, params, params);
14107
+ const endpointUrl = tIsVertexEmbedContentModel(params.model)
14108
+ ? '{model}:embedContent'
14109
+ : '{model}:predict';
14110
+ path = formatMap(endpointUrl, body['_url']);
13909
14111
  queryParams = body['_query'];
13910
14112
  delete body['_url'];
13911
14113
  delete body['_query'];
@@ -13928,14 +14130,14 @@ class Models extends BaseModule {
13928
14130
  });
13929
14131
  });
13930
14132
  return response.then((apiResponse) => {
13931
- const resp = embedContentResponseFromVertex(apiResponse);
14133
+ const resp = embedContentResponseFromVertex(apiResponse, params);
13932
14134
  const typedResp = new EmbedContentResponse();
13933
14135
  Object.assign(typedResp, resp);
13934
14136
  return typedResp;
13935
14137
  });
13936
14138
  }
13937
14139
  else {
13938
- const body = embedContentParametersToMldev(this.apiClient, params);
14140
+ const body = embedContentParametersPrivateToMldev(this.apiClient, params);
13939
14141
  path = formatMap('{model}:batchEmbedContents', body['_url']);
13940
14142
  queryParams = body['_query'];
13941
14143
  delete body['_url'];
@@ -17876,7 +18078,7 @@ class BaseGeminiNextGenAPIClient {
17876
18078
  }
17877
18079
  async fetchWithTimeout(url, init, ms, controller) {
17878
18080
  const _b = init || {}, { signal, method } = _b, options = __rest(_b, ["signal", "method"]);
17879
- const abort = controller.abort.bind(controller);
18081
+ const abort = this._makeAbort(controller);
17880
18082
  if (signal)
17881
18083
  signal.addEventListener('abort', abort, { once: true });
17882
18084
  const timeout = setTimeout(abort, ms);
@@ -17992,6 +18194,11 @@ class BaseGeminiNextGenAPIClient {
17992
18194
  this.validateHeaders(headers);
17993
18195
  return headers.values;
17994
18196
  }
18197
+ _makeAbort(controller) {
18198
+ // note: we can't just inline this method inside `fetchWithTimeout()` because then the closure
18199
+ // would capture all request options, and cause a memory leak.
18200
+ return () => controller.abort();
18201
+ }
17995
18202
  buildBody({ options: { body, headers: rawHeaders } }) {
17996
18203
  if (!body) {
17997
18204
  return { bodyHeaders: undefined, body: undefined };
@@ -18020,6 +18227,13 @@ class BaseGeminiNextGenAPIClient {
18020
18227
  (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
18021
18228
  return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
18022
18229
  }
18230
+ else if (typeof body === 'object' &&
18231
+ headers.values.get('content-type') === 'application/x-www-form-urlencoded') {
18232
+ return {
18233
+ bodyHeaders: { 'content-type': 'application/x-www-form-urlencoded' },
18234
+ body: this.stringifyQuery(body),
18235
+ };
18236
+ }
18023
18237
  else {
18024
18238
  return this.encoder({ body, headers });
18025
18239
  }
@@ -18341,6 +18555,9 @@ function createTuningJobConfigToMldev(fromObject, parentObject, _rootObject) {
18341
18555
  if (getValueByPath(fromObject, ['outputUri']) !== undefined) {
18342
18556
  throw new Error('outputUri parameter is not supported in Gemini API.');
18343
18557
  }
18558
+ if (getValueByPath(fromObject, ['encryptionSpec']) !== undefined) {
18559
+ throw new Error('encryptionSpec parameter is not supported in Gemini API.');
18560
+ }
18344
18561
  return toObject;
18345
18562
  }
18346
18563
  function createTuningJobConfigToVertex(fromObject, parentObject, rootObject) {
@@ -18576,6 +18793,12 @@ function createTuningJobConfigToVertex(fromObject, parentObject, rootObject) {
18576
18793
  if (parentObject !== undefined && fromOutputUri != null) {
18577
18794
  setValueByPath(parentObject, ['outputUri'], fromOutputUri);
18578
18795
  }
18796
+ const fromEncryptionSpec = getValueByPath(fromObject, [
18797
+ 'encryptionSpec',
18798
+ ]);
18799
+ if (parentObject !== undefined && fromEncryptionSpec != null) {
18800
+ setValueByPath(parentObject, ['encryptionSpec'], fromEncryptionSpec);
18801
+ }
18579
18802
  return toObject;
18580
18803
  }
18581
18804
  function createTuningJobParametersPrivateToMldev(fromObject, rootObject) {
@@ -19828,6 +20051,7 @@ const LANGUAGE_LABEL_PREFIX = 'gl-node/';
19828
20051
  */
19829
20052
  class GoogleGenAI {
19830
20053
  get interactions() {
20054
+ var _a;
19831
20055
  if (this._interactions !== undefined) {
19832
20056
  return this._interactions;
19833
20057
  }
@@ -19844,6 +20068,7 @@ class GoogleGenAI {
19844
20068
  clientAdapter: this.apiClient,
19845
20069
  defaultHeaders: this.apiClient.getDefaultHeaders(),
19846
20070
  timeout: httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.timeout,
20071
+ maxRetries: (_a = httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.retryOptions) === null || _a === void 0 ? void 0 : _a.attempts,
19847
20072
  });
19848
20073
  this._interactions = nextGenClient.interactions;
19849
20074
  return this._interactions;