@google/genai 1.32.0 → 1.34.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.
package/dist/index.mjs CHANGED
@@ -756,21 +756,29 @@ var PhishBlockThreshold;
756
756
  */
757
757
  PhishBlockThreshold["BLOCK_ONLY_EXTREMELY_HIGH"] = "BLOCK_ONLY_EXTREMELY_HIGH";
758
758
  })(PhishBlockThreshold || (PhishBlockThreshold = {}));
759
- /** The level of thoughts tokens that the model should generate. */
759
+ /** The number of thoughts tokens that the model should generate. */
760
760
  var ThinkingLevel;
761
761
  (function (ThinkingLevel) {
762
762
  /**
763
- * Default value.
763
+ * Unspecified thinking level.
764
764
  */
765
765
  ThinkingLevel["THINKING_LEVEL_UNSPECIFIED"] = "THINKING_LEVEL_UNSPECIFIED";
766
766
  /**
767
767
  * Low thinking level.
768
768
  */
769
769
  ThinkingLevel["LOW"] = "LOW";
770
+ /**
771
+ * Medium thinking level.
772
+ */
773
+ ThinkingLevel["MEDIUM"] = "MEDIUM";
770
774
  /**
771
775
  * High thinking level.
772
776
  */
773
777
  ThinkingLevel["HIGH"] = "HIGH";
778
+ /**
779
+ * MINIMAL thinking level.
780
+ */
781
+ ThinkingLevel["MINIMAL"] = "MINIMAL";
774
782
  })(ThinkingLevel || (ThinkingLevel = {}));
775
783
  /** Harm category. */
776
784
  var HarmCategory;
@@ -929,6 +937,14 @@ var FinishReason;
929
937
  * The model was expected to generate an image, but none was generated.
930
938
  */
931
939
  FinishReason["NO_IMAGE"] = "NO_IMAGE";
940
+ /**
941
+ * Image generation stopped because the generated image may be a recitation from a source.
942
+ */
943
+ FinishReason["IMAGE_RECITATION"] = "IMAGE_RECITATION";
944
+ /**
945
+ * Image generation stopped for a reason not otherwise specified.
946
+ */
947
+ FinishReason["IMAGE_OTHER"] = "IMAGE_OTHER";
932
948
  })(FinishReason || (FinishReason = {}));
933
949
  /** Output only. Harm probability levels in the content. */
934
950
  var HarmProbability;
@@ -1233,6 +1249,10 @@ var PartMediaResolutionLevel;
1233
1249
  * Media resolution set to high.
1234
1250
  */
1235
1251
  PartMediaResolutionLevel["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH";
1252
+ /**
1253
+ * Media resolution set to ultra high.
1254
+ */
1255
+ PartMediaResolutionLevel["MEDIA_RESOLUTION_ULTRA_HIGH"] = "MEDIA_RESOLUTION_ULTRA_HIGH";
1236
1256
  })(PartMediaResolutionLevel || (PartMediaResolutionLevel = {}));
1237
1257
  /** Options for feature selection preference. */
1238
1258
  var FeatureSelectionPreference;
@@ -1551,6 +1571,22 @@ var MediaModality;
1551
1571
  */
1552
1572
  MediaModality["DOCUMENT"] = "DOCUMENT";
1553
1573
  })(MediaModality || (MediaModality = {}));
1574
+ /** The type of the VAD signal. */
1575
+ var VadSignalType;
1576
+ (function (VadSignalType) {
1577
+ /**
1578
+ * The default is VAD_SIGNAL_TYPE_UNSPECIFIED.
1579
+ */
1580
+ VadSignalType["VAD_SIGNAL_TYPE_UNSPECIFIED"] = "VAD_SIGNAL_TYPE_UNSPECIFIED";
1581
+ /**
1582
+ * Start of sentence signal.
1583
+ */
1584
+ VadSignalType["VAD_SIGNAL_TYPE_SOS"] = "VAD_SIGNAL_TYPE_SOS";
1585
+ /**
1586
+ * End of sentence signal.
1587
+ */
1588
+ VadSignalType["VAD_SIGNAL_TYPE_EOS"] = "VAD_SIGNAL_TYPE_EOS";
1589
+ })(VadSignalType || (VadSignalType = {}));
1554
1590
  /** Start of speech sensitivity. */
1555
1591
  var StartSensitivity;
1556
1592
  (function (StartSensitivity) {
@@ -6221,6 +6257,18 @@ PERFORMANCE OF THIS SOFTWARE.
6221
6257
  /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
6222
6258
 
6223
6259
 
6260
+ function __rest(s, e) {
6261
+ var t = {};
6262
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
6263
+ t[p] = s[p];
6264
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
6265
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
6266
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
6267
+ t[p[i]] = s[p[i]];
6268
+ }
6269
+ return t;
6270
+ }
6271
+
6224
6272
  function __values(o) {
6225
6273
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
6226
6274
  if (m) return m.call(o);
@@ -6847,7 +6895,7 @@ const CONTENT_TYPE_HEADER = 'Content-Type';
6847
6895
  const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';
6848
6896
  const USER_AGENT_HEADER = 'User-Agent';
6849
6897
  const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';
6850
- const SDK_VERSION = '1.32.0'; // x-release-please-version
6898
+ const SDK_VERSION = '1.34.0'; // x-release-please-version
6851
6899
  const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;
6852
6900
  const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';
6853
6901
  const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';
@@ -6921,6 +6969,11 @@ class ApiClient {
6921
6969
  getLocation() {
6922
6970
  return this.clientOptions.location;
6923
6971
  }
6972
+ async getAuthHeaders() {
6973
+ const headers = new Headers();
6974
+ await this.clientOptions.auth.addAuthHeaders(headers);
6975
+ return headers;
6976
+ }
6924
6977
  getApiVersion() {
6925
6978
  if (this.clientOptions.httpOptions &&
6926
6979
  this.clientOptions.httpOptions.apiVersion !== undefined) {
@@ -7579,7 +7632,7 @@ async function uploadBlobInternal(file, uploadUrl, apiClient) {
7579
7632
  break;
7580
7633
  }
7581
7634
  retryCount++;
7582
- await sleep(currentDelayMs);
7635
+ await sleep$1(currentDelayMs);
7583
7636
  currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;
7584
7637
  }
7585
7638
  offset += chunkSize;
@@ -7600,7 +7653,7 @@ async function getBlobStat(file) {
7600
7653
  const fileStat = { size: file.size, type: file.type };
7601
7654
  return fileStat;
7602
7655
  }
7603
- function sleep(ms) {
7656
+ function sleep$1(ms) {
7604
7657
  return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
7605
7658
  }
7606
7659
 
@@ -8270,218 +8323,2210 @@ class FileSearchStores extends BaseModule {
8270
8323
  return this.apiClient.uploadFileToFileSearchStore(params.fileSearchStoreName, params.file, params.config);
8271
8324
  }
8272
8325
  /**
8273
- * Creates a File Search Store.
8274
- *
8275
- * @param params - The parameters for creating a File Search Store.
8276
- * @return FileSearchStore.
8326
+ * Creates a File Search Store.
8327
+ *
8328
+ * @param params - The parameters for creating a File Search Store.
8329
+ * @return FileSearchStore.
8330
+ */
8331
+ async create(params) {
8332
+ var _a, _b;
8333
+ let response;
8334
+ let path = '';
8335
+ let queryParams = {};
8336
+ if (this.apiClient.isVertexAI()) {
8337
+ throw new Error('This method is only supported by the Gemini Developer API.');
8338
+ }
8339
+ else {
8340
+ const body = createFileSearchStoreParametersToMldev(params);
8341
+ path = formatMap('fileSearchStores', body['_url']);
8342
+ queryParams = body['_query'];
8343
+ delete body['_url'];
8344
+ delete body['_query'];
8345
+ response = this.apiClient
8346
+ .request({
8347
+ path: path,
8348
+ queryParams: queryParams,
8349
+ body: JSON.stringify(body),
8350
+ httpMethod: 'POST',
8351
+ httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8352
+ abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8353
+ })
8354
+ .then((httpResponse) => {
8355
+ return httpResponse.json();
8356
+ });
8357
+ return response.then((resp) => {
8358
+ return resp;
8359
+ });
8360
+ }
8361
+ }
8362
+ /**
8363
+ * Gets a File Search Store.
8364
+ *
8365
+ * @param params - The parameters for getting a File Search Store.
8366
+ * @return FileSearchStore.
8367
+ */
8368
+ async get(params) {
8369
+ var _a, _b;
8370
+ let response;
8371
+ let path = '';
8372
+ let queryParams = {};
8373
+ if (this.apiClient.isVertexAI()) {
8374
+ throw new Error('This method is only supported by the Gemini Developer API.');
8375
+ }
8376
+ else {
8377
+ const body = getFileSearchStoreParametersToMldev(params);
8378
+ path = formatMap('{name}', body['_url']);
8379
+ queryParams = body['_query'];
8380
+ delete body['_url'];
8381
+ delete body['_query'];
8382
+ response = this.apiClient
8383
+ .request({
8384
+ path: path,
8385
+ queryParams: queryParams,
8386
+ body: JSON.stringify(body),
8387
+ httpMethod: 'GET',
8388
+ httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8389
+ abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8390
+ })
8391
+ .then((httpResponse) => {
8392
+ return httpResponse.json();
8393
+ });
8394
+ return response.then((resp) => {
8395
+ return resp;
8396
+ });
8397
+ }
8398
+ }
8399
+ /**
8400
+ * Deletes a File Search Store.
8401
+ *
8402
+ * @param params - The parameters for deleting a File Search Store.
8403
+ */
8404
+ async delete(params) {
8405
+ var _a, _b;
8406
+ let path = '';
8407
+ let queryParams = {};
8408
+ if (this.apiClient.isVertexAI()) {
8409
+ throw new Error('This method is only supported by the Gemini Developer API.');
8410
+ }
8411
+ else {
8412
+ const body = deleteFileSearchStoreParametersToMldev(params);
8413
+ path = formatMap('{name}', body['_url']);
8414
+ queryParams = body['_query'];
8415
+ delete body['_url'];
8416
+ delete body['_query'];
8417
+ await this.apiClient.request({
8418
+ path: path,
8419
+ queryParams: queryParams,
8420
+ body: JSON.stringify(body),
8421
+ httpMethod: 'DELETE',
8422
+ httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8423
+ abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8424
+ });
8425
+ }
8426
+ }
8427
+ async listInternal(params) {
8428
+ var _a, _b;
8429
+ let response;
8430
+ let path = '';
8431
+ let queryParams = {};
8432
+ if (this.apiClient.isVertexAI()) {
8433
+ throw new Error('This method is only supported by the Gemini Developer API.');
8434
+ }
8435
+ else {
8436
+ const body = listFileSearchStoresParametersToMldev(params);
8437
+ path = formatMap('fileSearchStores', body['_url']);
8438
+ queryParams = body['_query'];
8439
+ delete body['_url'];
8440
+ delete body['_query'];
8441
+ response = this.apiClient
8442
+ .request({
8443
+ path: path,
8444
+ queryParams: queryParams,
8445
+ body: JSON.stringify(body),
8446
+ httpMethod: 'GET',
8447
+ httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8448
+ abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8449
+ })
8450
+ .then((httpResponse) => {
8451
+ return httpResponse.json();
8452
+ });
8453
+ return response.then((apiResponse) => {
8454
+ const resp = listFileSearchStoresResponseFromMldev(apiResponse);
8455
+ const typedResp = new ListFileSearchStoresResponse();
8456
+ Object.assign(typedResp, resp);
8457
+ return typedResp;
8458
+ });
8459
+ }
8460
+ }
8461
+ async uploadToFileSearchStoreInternal(params) {
8462
+ var _a, _b;
8463
+ let response;
8464
+ let path = '';
8465
+ let queryParams = {};
8466
+ if (this.apiClient.isVertexAI()) {
8467
+ throw new Error('This method is only supported by the Gemini Developer API.');
8468
+ }
8469
+ else {
8470
+ const body = uploadToFileSearchStoreParametersToMldev(params);
8471
+ path = formatMap('upload/v1beta/{file_search_store_name}:uploadToFileSearchStore', body['_url']);
8472
+ queryParams = body['_query'];
8473
+ delete body['_url'];
8474
+ delete body['_query'];
8475
+ response = this.apiClient
8476
+ .request({
8477
+ path: path,
8478
+ queryParams: queryParams,
8479
+ body: JSON.stringify(body),
8480
+ httpMethod: 'POST',
8481
+ httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8482
+ abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8483
+ })
8484
+ .then((httpResponse) => {
8485
+ return httpResponse.json();
8486
+ });
8487
+ return response.then((apiResponse) => {
8488
+ const resp = uploadToFileSearchStoreResumableResponseFromMldev(apiResponse);
8489
+ const typedResp = new UploadToFileSearchStoreResumableResponse();
8490
+ Object.assign(typedResp, resp);
8491
+ return typedResp;
8492
+ });
8493
+ }
8494
+ }
8495
+ /**
8496
+ * Imports a File from File Service to a FileSearchStore.
8497
+ *
8498
+ * This is a long-running operation, see aip.dev/151
8499
+ *
8500
+ * @param params - The parameters for importing a file to a file search store.
8501
+ * @return ImportFileOperation.
8502
+ */
8503
+ async importFile(params) {
8504
+ var _a, _b;
8505
+ let response;
8506
+ let path = '';
8507
+ let queryParams = {};
8508
+ if (this.apiClient.isVertexAI()) {
8509
+ throw new Error('This method is only supported by the Gemini Developer API.');
8510
+ }
8511
+ else {
8512
+ const body = importFileParametersToMldev(params);
8513
+ path = formatMap('{file_search_store_name}:importFile', body['_url']);
8514
+ queryParams = body['_query'];
8515
+ delete body['_url'];
8516
+ delete body['_query'];
8517
+ response = this.apiClient
8518
+ .request({
8519
+ path: path,
8520
+ queryParams: queryParams,
8521
+ body: JSON.stringify(body),
8522
+ httpMethod: 'POST',
8523
+ httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8524
+ abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8525
+ })
8526
+ .then((httpResponse) => {
8527
+ return httpResponse.json();
8528
+ });
8529
+ return response.then((apiResponse) => {
8530
+ const resp = importFileOperationFromMldev(apiResponse);
8531
+ const typedResp = new ImportFileOperation();
8532
+ Object.assign(typedResp, resp);
8533
+ return typedResp;
8534
+ });
8535
+ }
8536
+ }
8537
+ }
8538
+
8539
+ /**
8540
+ * @license
8541
+ * Copyright 2025 Google LLC
8542
+ * SPDX-License-Identifier: Apache-2.0
8543
+ */
8544
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8545
+ /**
8546
+ * https://stackoverflow.com/a/2117523
8547
+ */
8548
+ let uuid4Internal = function () {
8549
+ const { crypto } = globalThis;
8550
+ if (crypto === null || crypto === void 0 ? void 0 : crypto.randomUUID) {
8551
+ uuid4Internal = crypto.randomUUID.bind(crypto);
8552
+ return crypto.randomUUID();
8553
+ }
8554
+ const u8 = new Uint8Array(1);
8555
+ const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff;
8556
+ return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16));
8557
+ };
8558
+ const uuid4 = () => uuid4Internal();
8559
+
8560
+ /**
8561
+ * @license
8562
+ * Copyright 2025 Google LLC
8563
+ * SPDX-License-Identifier: Apache-2.0
8564
+ */
8565
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8566
+ function isAbortError(err) {
8567
+ return (typeof err === 'object' &&
8568
+ err !== null &&
8569
+ // Spec-compliant fetch implementations
8570
+ (('name' in err && err.name === 'AbortError') ||
8571
+ // Expo fetch
8572
+ ('message' in err && String(err.message).includes('FetchRequestCanceledException'))));
8573
+ }
8574
+ const castToError = (err) => {
8575
+ if (err instanceof Error)
8576
+ return err;
8577
+ if (typeof err === 'object' && err !== null) {
8578
+ try {
8579
+ if (Object.prototype.toString.call(err) === '[object Error]') {
8580
+ // @ts-ignore - not all envs have native support for cause yet
8581
+ const error = new Error(err.message, err.cause ? { cause: err.cause } : {});
8582
+ if (err.stack)
8583
+ error.stack = err.stack;
8584
+ // @ts-ignore - not all envs have native support for cause yet
8585
+ if (err.cause && !error.cause)
8586
+ error.cause = err.cause;
8587
+ if (err.name)
8588
+ error.name = err.name;
8589
+ return error;
8590
+ }
8591
+ }
8592
+ catch (_a) { }
8593
+ try {
8594
+ return new Error(JSON.stringify(err));
8595
+ }
8596
+ catch (_b) { }
8597
+ }
8598
+ return new Error(err);
8599
+ };
8600
+
8601
+ /**
8602
+ * @license
8603
+ * Copyright 2025 Google LLC
8604
+ * SPDX-License-Identifier: Apache-2.0
8605
+ */
8606
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8607
+ class GeminiNextGenAPIClientError extends Error {
8608
+ }
8609
+ class APIError extends GeminiNextGenAPIClientError {
8610
+ constructor(status, error, message, headers) {
8611
+ super(`${APIError.makeMessage(status, error, message)}`);
8612
+ this.status = status;
8613
+ this.headers = headers;
8614
+ this.error = error;
8615
+ }
8616
+ static makeMessage(status, error, message) {
8617
+ const msg = (error === null || error === void 0 ? void 0 : error.message) ?
8618
+ typeof error.message === 'string' ?
8619
+ error.message
8620
+ : JSON.stringify(error.message)
8621
+ : error ? JSON.stringify(error)
8622
+ : message;
8623
+ if (status && msg) {
8624
+ return `${status} ${msg}`;
8625
+ }
8626
+ if (status) {
8627
+ return `${status} status code (no body)`;
8628
+ }
8629
+ if (msg) {
8630
+ return msg;
8631
+ }
8632
+ return '(no status code or body)';
8633
+ }
8634
+ static generate(status, errorResponse, message, headers) {
8635
+ if (!status || !headers) {
8636
+ return new APIConnectionError({ message, cause: castToError(errorResponse) });
8637
+ }
8638
+ const error = errorResponse;
8639
+ if (status === 400) {
8640
+ return new BadRequestError(status, error, message, headers);
8641
+ }
8642
+ if (status === 401) {
8643
+ return new AuthenticationError(status, error, message, headers);
8644
+ }
8645
+ if (status === 403) {
8646
+ return new PermissionDeniedError(status, error, message, headers);
8647
+ }
8648
+ if (status === 404) {
8649
+ return new NotFoundError(status, error, message, headers);
8650
+ }
8651
+ if (status === 409) {
8652
+ return new ConflictError(status, error, message, headers);
8653
+ }
8654
+ if (status === 422) {
8655
+ return new UnprocessableEntityError(status, error, message, headers);
8656
+ }
8657
+ if (status === 429) {
8658
+ return new RateLimitError(status, error, message, headers);
8659
+ }
8660
+ if (status >= 500) {
8661
+ return new InternalServerError(status, error, message, headers);
8662
+ }
8663
+ return new APIError(status, error, message, headers);
8664
+ }
8665
+ }
8666
+ class APIUserAbortError extends APIError {
8667
+ constructor({ message } = {}) {
8668
+ super(undefined, undefined, message || 'Request was aborted.', undefined);
8669
+ }
8670
+ }
8671
+ class APIConnectionError extends APIError {
8672
+ constructor({ message, cause }) {
8673
+ super(undefined, undefined, message || 'Connection error.', undefined);
8674
+ // in some environments the 'cause' property is already declared
8675
+ // @ts-ignore
8676
+ if (cause)
8677
+ this.cause = cause;
8678
+ }
8679
+ }
8680
+ class APIConnectionTimeoutError extends APIConnectionError {
8681
+ constructor({ message } = {}) {
8682
+ super({ message: message !== null && message !== void 0 ? message : 'Request timed out.' });
8683
+ }
8684
+ }
8685
+ class BadRequestError extends APIError {
8686
+ }
8687
+ class AuthenticationError extends APIError {
8688
+ }
8689
+ class PermissionDeniedError extends APIError {
8690
+ }
8691
+ class NotFoundError extends APIError {
8692
+ }
8693
+ class ConflictError extends APIError {
8694
+ }
8695
+ class UnprocessableEntityError extends APIError {
8696
+ }
8697
+ class RateLimitError extends APIError {
8698
+ }
8699
+ class InternalServerError extends APIError {
8700
+ }
8701
+
8702
+ /**
8703
+ * @license
8704
+ * Copyright 2025 Google LLC
8705
+ * SPDX-License-Identifier: Apache-2.0
8706
+ */
8707
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8708
+ // https://url.spec.whatwg.org/#url-scheme-string
8709
+ const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
8710
+ const isAbsoluteURL = (url) => {
8711
+ return startsWithSchemeRegexp.test(url);
8712
+ };
8713
+ let isArrayInternal = (val) => ((isArrayInternal = Array.isArray), isArrayInternal(val));
8714
+ const isArray = isArrayInternal;
8715
+ let isReadonlyArrayInternal = isArray;
8716
+ const isReadonlyArray = isReadonlyArrayInternal;
8717
+ // https://stackoverflow.com/a/34491287
8718
+ function isEmptyObj(obj) {
8719
+ if (!obj)
8720
+ return true;
8721
+ for (const _k in obj)
8722
+ return false;
8723
+ return true;
8724
+ }
8725
+ // https://eslint.org/docs/latest/rules/no-prototype-builtins
8726
+ function hasOwn(obj, key) {
8727
+ return Object.prototype.hasOwnProperty.call(obj, key);
8728
+ }
8729
+ const validatePositiveInteger = (name, n) => {
8730
+ if (typeof n !== 'number' || !Number.isInteger(n)) {
8731
+ throw new GeminiNextGenAPIClientError(`${name} must be an integer`);
8732
+ }
8733
+ if (n < 0) {
8734
+ throw new GeminiNextGenAPIClientError(`${name} must be a positive integer`);
8735
+ }
8736
+ return n;
8737
+ };
8738
+ const safeJSON = (text) => {
8739
+ try {
8740
+ return JSON.parse(text);
8741
+ }
8742
+ catch (err) {
8743
+ return undefined;
8744
+ }
8745
+ };
8746
+
8747
+ /**
8748
+ * @license
8749
+ * Copyright 2025 Google LLC
8750
+ * SPDX-License-Identifier: Apache-2.0
8751
+ */
8752
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8753
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
8754
+
8755
+ /**
8756
+ * @license
8757
+ * Copyright 2025 Google LLC
8758
+ * SPDX-License-Identifier: Apache-2.0
8759
+ */
8760
+ const VERSION = '0.0.1';
8761
+
8762
+ /**
8763
+ * @license
8764
+ * Copyright 2025 Google LLC
8765
+ * SPDX-License-Identifier: Apache-2.0
8766
+ */
8767
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
8768
+ /**
8769
+ * Note this does not detect 'browser'; for that, use getBrowserInfo().
8770
+ */
8771
+ function getDetectedPlatform() {
8772
+ if (typeof Deno !== 'undefined' && Deno.build != null) {
8773
+ return 'deno';
8774
+ }
8775
+ if (typeof EdgeRuntime !== 'undefined') {
8776
+ return 'edge';
8777
+ }
8778
+ if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') {
8779
+ return 'node';
8780
+ }
8781
+ return 'unknown';
8782
+ }
8783
+ const getPlatformProperties = () => {
8784
+ var _a, _b, _c, _d, _e;
8785
+ const detectedPlatform = getDetectedPlatform();
8786
+ if (detectedPlatform === 'deno') {
8787
+ return {
8788
+ 'X-Stainless-Lang': 'js',
8789
+ 'X-Stainless-Package-Version': VERSION,
8790
+ 'X-Stainless-OS': normalizePlatform(Deno.build.os),
8791
+ 'X-Stainless-Arch': normalizeArch(Deno.build.arch),
8792
+ 'X-Stainless-Runtime': 'deno',
8793
+ 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : (_b = (_a = Deno.version) === null || _a === void 0 ? void 0 : _a.deno) !== null && _b !== void 0 ? _b : 'unknown',
8794
+ };
8795
+ }
8796
+ if (typeof EdgeRuntime !== 'undefined') {
8797
+ return {
8798
+ 'X-Stainless-Lang': 'js',
8799
+ 'X-Stainless-Package-Version': VERSION,
8800
+ 'X-Stainless-OS': 'Unknown',
8801
+ 'X-Stainless-Arch': `other:${EdgeRuntime}`,
8802
+ 'X-Stainless-Runtime': 'edge',
8803
+ 'X-Stainless-Runtime-Version': globalThis.process.version,
8804
+ };
8805
+ }
8806
+ // Check if Node.js
8807
+ if (detectedPlatform === 'node') {
8808
+ return {
8809
+ 'X-Stainless-Lang': 'js',
8810
+ 'X-Stainless-Package-Version': VERSION,
8811
+ 'X-Stainless-OS': normalizePlatform((_c = globalThis.process.platform) !== null && _c !== void 0 ? _c : 'unknown'),
8812
+ 'X-Stainless-Arch': normalizeArch((_d = globalThis.process.arch) !== null && _d !== void 0 ? _d : 'unknown'),
8813
+ 'X-Stainless-Runtime': 'node',
8814
+ 'X-Stainless-Runtime-Version': (_e = globalThis.process.version) !== null && _e !== void 0 ? _e : 'unknown',
8815
+ };
8816
+ }
8817
+ const browserInfo = getBrowserInfo();
8818
+ if (browserInfo) {
8819
+ return {
8820
+ 'X-Stainless-Lang': 'js',
8821
+ 'X-Stainless-Package-Version': VERSION,
8822
+ 'X-Stainless-OS': 'Unknown',
8823
+ 'X-Stainless-Arch': 'unknown',
8824
+ 'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
8825
+ 'X-Stainless-Runtime-Version': browserInfo.version,
8826
+ };
8827
+ }
8828
+ // TODO add support for Cloudflare workers, etc.
8829
+ return {
8830
+ 'X-Stainless-Lang': 'js',
8831
+ 'X-Stainless-Package-Version': VERSION,
8832
+ 'X-Stainless-OS': 'Unknown',
8833
+ 'X-Stainless-Arch': 'unknown',
8834
+ 'X-Stainless-Runtime': 'unknown',
8835
+ 'X-Stainless-Runtime-Version': 'unknown',
8836
+ };
8837
+ };
8838
+ // Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
8839
+ function getBrowserInfo() {
8840
+ if (typeof navigator === 'undefined' || !navigator) {
8841
+ return null;
8842
+ }
8843
+ // NOTE: The order matters here!
8844
+ const browserPatterns = [
8845
+ { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
8846
+ { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
8847
+ { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
8848
+ { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
8849
+ { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
8850
+ { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
8851
+ ];
8852
+ // Find the FIRST matching browser
8853
+ for (const { key, pattern } of browserPatterns) {
8854
+ const match = pattern.exec(navigator.userAgent);
8855
+ if (match) {
8856
+ const major = match[1] || 0;
8857
+ const minor = match[2] || 0;
8858
+ const patch = match[3] || 0;
8859
+ return { browser: key, version: `${major}.${minor}.${patch}` };
8860
+ }
8861
+ }
8862
+ return null;
8863
+ }
8864
+ const normalizeArch = (arch) => {
8865
+ // Node docs:
8866
+ // - https://nodejs.org/api/process.html#processarch
8867
+ // Deno docs:
8868
+ // - https://doc.deno.land/deno/stable/~/Deno.build
8869
+ if (arch === 'x32')
8870
+ return 'x32';
8871
+ if (arch === 'x86_64' || arch === 'x64')
8872
+ return 'x64';
8873
+ if (arch === 'arm')
8874
+ return 'arm';
8875
+ if (arch === 'aarch64' || arch === 'arm64')
8876
+ return 'arm64';
8877
+ if (arch)
8878
+ return `other:${arch}`;
8879
+ return 'unknown';
8880
+ };
8881
+ const normalizePlatform = (platform) => {
8882
+ // Node platforms:
8883
+ // - https://nodejs.org/api/process.html#processplatform
8884
+ // Deno platforms:
8885
+ // - https://doc.deno.land/deno/stable/~/Deno.build
8886
+ // - https://github.com/denoland/deno/issues/14799
8887
+ platform = platform.toLowerCase();
8888
+ // NOTE: this iOS check is untested and may not work
8889
+ // Node does not work natively on IOS, there is a fork at
8890
+ // https://github.com/nodejs-mobile/nodejs-mobile
8891
+ // however it is unknown at the time of writing how to detect if it is running
8892
+ if (platform.includes('ios'))
8893
+ return 'iOS';
8894
+ if (platform === 'android')
8895
+ return 'Android';
8896
+ if (platform === 'darwin')
8897
+ return 'MacOS';
8898
+ if (platform === 'win32')
8899
+ return 'Windows';
8900
+ if (platform === 'freebsd')
8901
+ return 'FreeBSD';
8902
+ if (platform === 'openbsd')
8903
+ return 'OpenBSD';
8904
+ if (platform === 'linux')
8905
+ return 'Linux';
8906
+ if (platform)
8907
+ return `Other:${platform}`;
8908
+ return 'Unknown';
8909
+ };
8910
+ let _platformHeaders;
8911
+ const getPlatformHeaders = () => {
8912
+ return (_platformHeaders !== null && _platformHeaders !== void 0 ? _platformHeaders : (_platformHeaders = getPlatformProperties()));
8913
+ };
8914
+
8915
+ /**
8916
+ * @license
8917
+ * Copyright 2025 Google LLC
8918
+ * SPDX-License-Identifier: Apache-2.0
8919
+ */
8920
+ function getDefaultFetch() {
8921
+ if (typeof fetch !== 'undefined') {
8922
+ return fetch;
8923
+ }
8924
+ throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`');
8925
+ }
8926
+ function makeReadableStream(...args) {
8927
+ const ReadableStream = globalThis.ReadableStream;
8928
+ if (typeof ReadableStream === 'undefined') {
8929
+ // Note: All of the platforms / runtimes we officially support already define
8930
+ // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes.
8931
+ throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`');
8932
+ }
8933
+ return new ReadableStream(...args);
8934
+ }
8935
+ function ReadableStreamFrom(iterable) {
8936
+ let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
8937
+ return makeReadableStream({
8938
+ start() { },
8939
+ async pull(controller) {
8940
+ const { done, value } = await iter.next();
8941
+ if (done) {
8942
+ controller.close();
8943
+ }
8944
+ else {
8945
+ controller.enqueue(value);
8946
+ }
8947
+ },
8948
+ async cancel() {
8949
+ var _a;
8950
+ await ((_a = iter.return) === null || _a === void 0 ? void 0 : _a.call(iter));
8951
+ },
8952
+ });
8953
+ }
8954
+ /**
8955
+ * Most browsers don't yet have async iterable support for ReadableStream,
8956
+ * and Node has a very different way of reading bytes from its "ReadableStream".
8957
+ *
8958
+ * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
8959
+ */
8960
+ function ReadableStreamToAsyncIterable(stream) {
8961
+ if (stream[Symbol.asyncIterator])
8962
+ return stream;
8963
+ const reader = stream.getReader();
8964
+ return {
8965
+ async next() {
8966
+ try {
8967
+ const result = await reader.read();
8968
+ if (result === null || result === void 0 ? void 0 : result.done)
8969
+ reader.releaseLock(); // release lock when stream becomes closed
8970
+ return result;
8971
+ }
8972
+ catch (e) {
8973
+ reader.releaseLock(); // release lock when stream becomes errored
8974
+ throw e;
8975
+ }
8976
+ },
8977
+ async return() {
8978
+ const cancelPromise = reader.cancel();
8979
+ reader.releaseLock();
8980
+ await cancelPromise;
8981
+ return { done: true, value: undefined };
8982
+ },
8983
+ [Symbol.asyncIterator]() {
8984
+ return this;
8985
+ },
8986
+ };
8987
+ }
8988
+ /**
8989
+ * Cancels a ReadableStream we don't need to consume.
8990
+ * See https://undici.nodejs.org/#/?id=garbage-collection
8991
+ */
8992
+ async function CancelReadableStream(stream) {
8993
+ var _a, _b;
8994
+ if (stream === null || typeof stream !== 'object')
8995
+ return;
8996
+ if (stream[Symbol.asyncIterator]) {
8997
+ await ((_b = (_a = stream[Symbol.asyncIterator]()).return) === null || _b === void 0 ? void 0 : _b.call(_a));
8998
+ return;
8999
+ }
9000
+ const reader = stream.getReader();
9001
+ const cancelPromise = reader.cancel();
9002
+ reader.releaseLock();
9003
+ await cancelPromise;
9004
+ }
9005
+
9006
+ /**
9007
+ * @license
9008
+ * Copyright 2025 Google LLC
9009
+ * SPDX-License-Identifier: Apache-2.0
9010
+ */
9011
+ const FallbackEncoder = ({ headers, body }) => {
9012
+ return {
9013
+ bodyHeaders: {
9014
+ 'content-type': 'application/json',
9015
+ },
9016
+ body: JSON.stringify(body),
9017
+ };
9018
+ };
9019
+
9020
+ /**
9021
+ * @license
9022
+ * Copyright 2025 Google LLC
9023
+ * SPDX-License-Identifier: Apache-2.0
9024
+ */
9025
+ const checkFileSupport = () => {
9026
+ var _a;
9027
+ if (typeof File === 'undefined') {
9028
+ const { process } = globalThis;
9029
+ const isOldNode = typeof ((_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) === 'string' && parseInt(process.versions.node.split('.')) < 20;
9030
+ throw new Error('`File` is not defined as a global, which is required for file uploads.' +
9031
+ (isOldNode ?
9032
+ " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`."
9033
+ : ''));
9034
+ }
9035
+ };
9036
+ /**
9037
+ * Construct a `File` instance. This is used to ensure a helpful error is thrown
9038
+ * for environments that don't define a global `File` yet.
9039
+ */
9040
+ function makeFile(fileBits, fileName, options) {
9041
+ checkFileSupport();
9042
+ return new File(fileBits, fileName !== null && fileName !== void 0 ? fileName : 'unknown_file', options);
9043
+ }
9044
+ function getName(value) {
9045
+ return (((typeof value === 'object' &&
9046
+ value !== null &&
9047
+ (('name' in value && value.name && String(value.name)) ||
9048
+ ('url' in value && value.url && String(value.url)) ||
9049
+ ('filename' in value && value.filename && String(value.filename)) ||
9050
+ ('path' in value && value.path && String(value.path)))) ||
9051
+ '')
9052
+ .split(/[\\/]/)
9053
+ .pop() || undefined);
9054
+ }
9055
+ const isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';
9056
+
9057
+ /**
9058
+ * @license
9059
+ * Copyright 2025 Google LLC
9060
+ * SPDX-License-Identifier: Apache-2.0
9061
+ */
9062
+ /**
9063
+ * This check adds the arrayBuffer() method type because it is available and used at runtime
9064
+ */
9065
+ const isBlobLike = (value) => value != null &&
9066
+ typeof value === 'object' &&
9067
+ typeof value.size === 'number' &&
9068
+ typeof value.type === 'string' &&
9069
+ typeof value.text === 'function' &&
9070
+ typeof value.slice === 'function' &&
9071
+ typeof value.arrayBuffer === 'function';
9072
+ /**
9073
+ * This check adds the arrayBuffer() method type because it is available and used at runtime
9074
+ */
9075
+ const isFileLike = (value) => value != null &&
9076
+ typeof value === 'object' &&
9077
+ typeof value.name === 'string' &&
9078
+ typeof value.lastModified === 'number' &&
9079
+ isBlobLike(value);
9080
+ const isResponseLike = (value) => value != null &&
9081
+ typeof value === 'object' &&
9082
+ typeof value.url === 'string' &&
9083
+ typeof value.blob === 'function';
9084
+ /**
9085
+ * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats
9086
+ * @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts
9087
+ * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible
9088
+ * @param {Object=} options additional properties
9089
+ * @param {string=} options.type the MIME type of the content
9090
+ * @param {number=} options.lastModified the last modified timestamp
9091
+ * @returns a {@link File} with the given properties
9092
+ */
9093
+ async function toFile(value, name, options) {
9094
+ checkFileSupport();
9095
+ // If it's a promise, resolve it.
9096
+ value = await value;
9097
+ // If we've been given a `File` we don't need to do anything
9098
+ if (isFileLike(value)) {
9099
+ if (value instanceof File) {
9100
+ return value;
9101
+ }
9102
+ return makeFile([await value.arrayBuffer()], value.name);
9103
+ }
9104
+ if (isResponseLike(value)) {
9105
+ const blob = await value.blob();
9106
+ name || (name = new URL(value.url).pathname.split(/[\\/]/).pop());
9107
+ return makeFile(await getBytes(blob), name, options);
9108
+ }
9109
+ const parts = await getBytes(value);
9110
+ name || (name = getName(value));
9111
+ if (!(options === null || options === void 0 ? void 0 : options.type)) {
9112
+ const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type);
9113
+ if (typeof type === 'string') {
9114
+ options = Object.assign(Object.assign({}, options), { type });
9115
+ }
9116
+ }
9117
+ return makeFile(parts, name, options);
9118
+ }
9119
+ async function getBytes(value) {
9120
+ var _a, e_1, _b, _c;
9121
+ var _d;
9122
+ let parts = [];
9123
+ if (typeof value === 'string' ||
9124
+ ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
9125
+ value instanceof ArrayBuffer) {
9126
+ parts.push(value);
9127
+ }
9128
+ else if (isBlobLike(value)) {
9129
+ parts.push(value instanceof Blob ? value : await value.arrayBuffer());
9130
+ }
9131
+ else if (isAsyncIterable(value) // includes Readable, ReadableStream, etc.
9132
+ ) {
9133
+ try {
9134
+ for (var _e = true, value_1 = __asyncValues(value), value_1_1; value_1_1 = await value_1.next(), _a = value_1_1.done, !_a; _e = true) {
9135
+ _c = value_1_1.value;
9136
+ _e = false;
9137
+ const chunk = _c;
9138
+ parts.push(...(await getBytes(chunk))); // TODO, consider validating?
9139
+ }
9140
+ }
9141
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
9142
+ finally {
9143
+ try {
9144
+ if (!_e && !_a && (_b = value_1.return)) await _b.call(value_1);
9145
+ }
9146
+ finally { if (e_1) throw e_1.error; }
9147
+ }
9148
+ }
9149
+ else {
9150
+ const constructor = (_d = value === null || value === void 0 ? void 0 : value.constructor) === null || _d === void 0 ? void 0 : _d.name;
9151
+ throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${propsForError(value)}`);
9152
+ }
9153
+ return parts;
9154
+ }
9155
+ function propsForError(value) {
9156
+ if (typeof value !== 'object' || value === null)
9157
+ return '';
9158
+ const props = Object.getOwnPropertyNames(value);
9159
+ return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`;
9160
+ }
9161
+
9162
+ /**
9163
+ * @license
9164
+ * Copyright 2025 Google LLC
9165
+ * SPDX-License-Identifier: Apache-2.0
9166
+ */
9167
+ class APIResource {
9168
+ constructor(client) {
9169
+ this._client = client;
9170
+ }
9171
+ }
9172
+ /**
9173
+ * The key path from the client. For example, a resource accessible as `client.resource.subresource` would
9174
+ * have a property `static override readonly _key = Object.freeze(['resource', 'subresource'] as const);`.
9175
+ */
9176
+ APIResource._key = [];
9177
+
9178
+ /**
9179
+ * @license
9180
+ * Copyright 2025 Google LLC
9181
+ * SPDX-License-Identifier: Apache-2.0
9182
+ */
9183
+ /**
9184
+ * Percent-encode everything that isn't safe to have in a path without encoding safe chars.
9185
+ *
9186
+ * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3:
9187
+ * > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
9188
+ * > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
9189
+ * > pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
9190
+ */
9191
+ function encodeURIPath(str) {
9192
+ return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
9193
+ }
9194
+ const EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
9195
+ const createPathTagFunction = (pathEncoder = encodeURIPath) => (function path(statics, ...params) {
9196
+ // If there are no params, no processing is needed.
9197
+ if (statics.length === 1)
9198
+ return statics[0];
9199
+ let postPath = false;
9200
+ const invalidSegments = [];
9201
+ const path = statics.reduce((previousValue, currentValue, index) => {
9202
+ var _a, _b, _c;
9203
+ if (/[?#]/.test(currentValue)) {
9204
+ postPath = true;
9205
+ }
9206
+ const value = params[index];
9207
+ let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value);
9208
+ if (index !== params.length &&
9209
+ (value == null ||
9210
+ (typeof value === 'object' &&
9211
+ // handle values from other realms
9212
+ value.toString ===
9213
+ ((_c = Object.getPrototypeOf((_b = Object.getPrototypeOf((_a = value.hasOwnProperty) !== null && _a !== void 0 ? _a : EMPTY)) !== null && _b !== void 0 ? _b : EMPTY)) === null || _c === void 0 ? void 0 : _c.toString)))) {
9214
+ encoded = value + '';
9215
+ invalidSegments.push({
9216
+ start: previousValue.length + currentValue.length,
9217
+ length: encoded.length,
9218
+ error: `Value of type ${Object.prototype.toString
9219
+ .call(value)
9220
+ .slice(8, -1)} is not a valid path parameter`,
9221
+ });
9222
+ }
9223
+ return previousValue + currentValue + (index === params.length ? '' : encoded);
9224
+ }, '');
9225
+ const pathOnly = path.split(/[?#]/, 1)[0];
9226
+ const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
9227
+ let match;
9228
+ // Find all invalid segments
9229
+ while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
9230
+ invalidSegments.push({
9231
+ start: match.index,
9232
+ length: match[0].length,
9233
+ error: `Value "${match[0]}" can\'t be safely passed as a path parameter`,
9234
+ });
9235
+ }
9236
+ invalidSegments.sort((a, b) => a.start - b.start);
9237
+ if (invalidSegments.length > 0) {
9238
+ let lastEnd = 0;
9239
+ const underline = invalidSegments.reduce((acc, segment) => {
9240
+ const spaces = ' '.repeat(segment.start - lastEnd);
9241
+ const arrows = '^'.repeat(segment.length);
9242
+ lastEnd = segment.start + segment.length;
9243
+ return acc + spaces + arrows;
9244
+ }, '');
9245
+ throw new GeminiNextGenAPIClientError(`Path parameters result in path with invalid segments:\n${invalidSegments
9246
+ .map((e) => e.error)
9247
+ .join('\n')}\n${path}\n${underline}`);
9248
+ }
9249
+ return path;
9250
+ });
9251
+ /**
9252
+ * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced.
9253
+ */
9254
+ const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath);
9255
+
9256
+ /**
9257
+ * @license
9258
+ * Copyright 2025 Google LLC
9259
+ * SPDX-License-Identifier: Apache-2.0
9260
+ */
9261
+ class BaseInteractions extends APIResource {
9262
+ create(params, options) {
9263
+ var _a;
9264
+ const { api_version = this._client.apiVersion } = params, body = __rest(params, ["api_version"]);
9265
+ if ('model' in body && 'agent_config' in body) {
9266
+ throw new GeminiNextGenAPIClientError(`Invalid request: specified \`model\` and \`agent_config\`. If specifying \`model\`, use \`generation_config\`.`);
9267
+ }
9268
+ if ('agent' in body && 'generation_config' in body) {
9269
+ throw new GeminiNextGenAPIClientError(`Invalid request: specified \`agent\` and \`generation_config\`. If specifying \`agent\`, use \`agent_config\`.`);
9270
+ }
9271
+ return this._client.post(path `/${api_version}/interactions`, Object.assign(Object.assign({ body }, options), { stream: (_a = params.stream) !== null && _a !== void 0 ? _a : false }));
9272
+ }
9273
+ /**
9274
+ * Deletes the interaction by id.
9275
+ *
9276
+ * @example
9277
+ * ```ts
9278
+ * const interaction = await client.interactions.delete('id');
9279
+ * ```
9280
+ */
9281
+ delete(id, params = {}, options) {
9282
+ const { api_version = this._client.apiVersion } = params !== null && params !== void 0 ? params : {};
9283
+ return this._client.delete(path `/${api_version}/interactions/${id}`, options);
9284
+ }
9285
+ /**
9286
+ * Cancels an interaction by id. This only applies to background interactions that are still running.
9287
+ *
9288
+ * @example
9289
+ * ```ts
9290
+ * const interaction = await client.interactions.cancel('id');
9291
+ * ```
9292
+ */
9293
+ cancel(id, params = {}, options) {
9294
+ const { api_version = this._client.apiVersion } = params !== null && params !== void 0 ? params : {};
9295
+ return this._client.post(path `/${api_version}/interactions/${id}/cancel`, options);
9296
+ }
9297
+ get(id, params = {}, options) {
9298
+ var _a;
9299
+ const _b = params !== null && params !== void 0 ? params : {}, { api_version = this._client.apiVersion } = _b, query = __rest(_b, ["api_version"]);
9300
+ return this._client.get(path `/${api_version}/interactions/${id}`, Object.assign(Object.assign({ query }, options), { stream: (_a = params === null || params === void 0 ? void 0 : params.stream) !== null && _a !== void 0 ? _a : false }));
9301
+ }
9302
+ }
9303
+ BaseInteractions._key = Object.freeze(['interactions']);
9304
+ class Interactions extends BaseInteractions {
9305
+ }
9306
+
9307
+ /**
9308
+ * @license
9309
+ * Copyright 2025 Google LLC
9310
+ * SPDX-License-Identifier: Apache-2.0
9311
+ */
9312
+ function concatBytes(buffers) {
9313
+ let length = 0;
9314
+ for (const buffer of buffers) {
9315
+ length += buffer.length;
9316
+ }
9317
+ const output = new Uint8Array(length);
9318
+ let index = 0;
9319
+ for (const buffer of buffers) {
9320
+ output.set(buffer, index);
9321
+ index += buffer.length;
9322
+ }
9323
+ return output;
9324
+ }
9325
+ let encodeUTF8_;
9326
+ function encodeUTF8(str) {
9327
+ let encoder;
9328
+ return (encodeUTF8_ !== null && encodeUTF8_ !== void 0 ? encodeUTF8_ : ((encoder = new globalThis.TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))))(str);
9329
+ }
9330
+ let decodeUTF8_;
9331
+ function decodeUTF8(bytes) {
9332
+ let decoder;
9333
+ return (decodeUTF8_ !== null && decodeUTF8_ !== void 0 ? decodeUTF8_ : ((decoder = new globalThis.TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))))(bytes);
9334
+ }
9335
+
9336
+ /**
9337
+ * @license
9338
+ * Copyright 2025 Google LLC
9339
+ * SPDX-License-Identifier: Apache-2.0
9340
+ */
9341
+ /**
9342
+ * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally
9343
+ * reading lines from text.
9344
+ *
9345
+ * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258
9346
+ */
9347
+ class LineDecoder {
9348
+ constructor() {
9349
+ this.buffer = new Uint8Array();
9350
+ this.carriageReturnIndex = null;
9351
+ }
9352
+ decode(chunk) {
9353
+ if (chunk == null) {
9354
+ return [];
9355
+ }
9356
+ const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
9357
+ : typeof chunk === 'string' ? encodeUTF8(chunk)
9358
+ : chunk;
9359
+ this.buffer = concatBytes([this.buffer, binaryChunk]);
9360
+ const lines = [];
9361
+ let patternIndex;
9362
+ while ((patternIndex = findNewlineIndex(this.buffer, this.carriageReturnIndex)) != null) {
9363
+ if (patternIndex.carriage && this.carriageReturnIndex == null) {
9364
+ // skip until we either get a corresponding `\n`, a new `\r` or nothing
9365
+ this.carriageReturnIndex = patternIndex.index;
9366
+ continue;
9367
+ }
9368
+ // we got double \r or \rtext\n
9369
+ if (this.carriageReturnIndex != null &&
9370
+ (patternIndex.index !== this.carriageReturnIndex + 1 || patternIndex.carriage)) {
9371
+ lines.push(decodeUTF8(this.buffer.subarray(0, this.carriageReturnIndex - 1)));
9372
+ this.buffer = this.buffer.subarray(this.carriageReturnIndex);
9373
+ this.carriageReturnIndex = null;
9374
+ continue;
9375
+ }
9376
+ const endIndex = this.carriageReturnIndex !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
9377
+ const line = decodeUTF8(this.buffer.subarray(0, endIndex));
9378
+ lines.push(line);
9379
+ this.buffer = this.buffer.subarray(patternIndex.index);
9380
+ this.carriageReturnIndex = null;
9381
+ }
9382
+ return lines;
9383
+ }
9384
+ flush() {
9385
+ if (!this.buffer.length) {
9386
+ return [];
9387
+ }
9388
+ return this.decode('\n');
9389
+ }
9390
+ }
9391
+ // prettier-ignore
9392
+ LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']);
9393
+ LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
9394
+ /**
9395
+ * This function searches the buffer for the end patterns, (\r or \n)
9396
+ * and returns an object with the index preceding the matched newline and the
9397
+ * index after the newline char. `null` is returned if no new line is found.
9398
+ *
9399
+ * ```ts
9400
+ * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 }
9401
+ * ```
9402
+ */
9403
+ function findNewlineIndex(buffer, startIndex) {
9404
+ const newline = 0x0a; // \n
9405
+ const carriage = 0x0d; // \r
9406
+ for (let i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < buffer.length; i++) {
9407
+ if (buffer[i] === newline) {
9408
+ return { preceding: i, index: i + 1, carriage: false };
9409
+ }
9410
+ if (buffer[i] === carriage) {
9411
+ return { preceding: i, index: i + 1, carriage: true };
9412
+ }
9413
+ }
9414
+ return null;
9415
+ }
9416
+ function findDoubleNewlineIndex(buffer) {
9417
+ // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n)
9418
+ // and returns the index right after the first occurrence of any pattern,
9419
+ // or -1 if none of the patterns are found.
9420
+ const newline = 0x0a; // \n
9421
+ const carriage = 0x0d; // \r
9422
+ for (let i = 0; i < buffer.length - 1; i++) {
9423
+ if (buffer[i] === newline && buffer[i + 1] === newline) {
9424
+ // \n\n
9425
+ return i + 2;
9426
+ }
9427
+ if (buffer[i] === carriage && buffer[i + 1] === carriage) {
9428
+ // \r\r
9429
+ return i + 2;
9430
+ }
9431
+ if (buffer[i] === carriage &&
9432
+ buffer[i + 1] === newline &&
9433
+ i + 3 < buffer.length &&
9434
+ buffer[i + 2] === carriage &&
9435
+ buffer[i + 3] === newline) {
9436
+ // \r\n\r\n
9437
+ return i + 4;
9438
+ }
9439
+ }
9440
+ return -1;
9441
+ }
9442
+
9443
+ /**
9444
+ * @license
9445
+ * Copyright 2025 Google LLC
9446
+ * SPDX-License-Identifier: Apache-2.0
9447
+ */
9448
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
9449
+ const levelNumbers = {
9450
+ off: 0,
9451
+ error: 200,
9452
+ warn: 300,
9453
+ info: 400,
9454
+ debug: 500,
9455
+ };
9456
+ const parseLogLevel = (maybeLevel, sourceName, client) => {
9457
+ if (!maybeLevel) {
9458
+ return undefined;
9459
+ }
9460
+ if (hasOwn(levelNumbers, maybeLevel)) {
9461
+ return maybeLevel;
9462
+ }
9463
+ loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);
9464
+ return undefined;
9465
+ };
9466
+ function noop() { }
9467
+ function makeLogFn(fnLevel, logger, logLevel) {
9468
+ if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) {
9469
+ return noop;
9470
+ }
9471
+ else {
9472
+ // Don't wrap logger functions, we want the stacktrace intact!
9473
+ return logger[fnLevel].bind(logger);
9474
+ }
9475
+ }
9476
+ const noopLogger = {
9477
+ error: noop,
9478
+ warn: noop,
9479
+ info: noop,
9480
+ debug: noop,
9481
+ };
9482
+ let cachedLoggers = /* @__PURE__ */ new WeakMap();
9483
+ function loggerFor(client) {
9484
+ var _a;
9485
+ const logger = client.logger;
9486
+ const logLevel = (_a = client.logLevel) !== null && _a !== void 0 ? _a : 'off';
9487
+ if (!logger) {
9488
+ return noopLogger;
9489
+ }
9490
+ const cachedLogger = cachedLoggers.get(logger);
9491
+ if (cachedLogger && cachedLogger[0] === logLevel) {
9492
+ return cachedLogger[1];
9493
+ }
9494
+ const levelLogger = {
9495
+ error: makeLogFn('error', logger, logLevel),
9496
+ warn: makeLogFn('warn', logger, logLevel),
9497
+ info: makeLogFn('info', logger, logLevel),
9498
+ debug: makeLogFn('debug', logger, logLevel),
9499
+ };
9500
+ cachedLoggers.set(logger, [logLevel, levelLogger]);
9501
+ return levelLogger;
9502
+ }
9503
+ const formatRequestDetails = (details) => {
9504
+ if (details.options) {
9505
+ details.options = Object.assign({}, details.options);
9506
+ delete details.options['headers']; // redundant + leaks internals
9507
+ }
9508
+ if (details.headers) {
9509
+ details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [
9510
+ name,
9511
+ (name.toLowerCase() === 'x-goog-api-key' ||
9512
+ name.toLowerCase() === 'authorization' ||
9513
+ name.toLowerCase() === 'cookie' ||
9514
+ name.toLowerCase() === 'set-cookie') ?
9515
+ '***'
9516
+ : value,
9517
+ ]));
9518
+ }
9519
+ if ('retryOfRequestLogID' in details) {
9520
+ if (details.retryOfRequestLogID) {
9521
+ details.retryOf = details.retryOfRequestLogID;
9522
+ }
9523
+ delete details.retryOfRequestLogID;
9524
+ }
9525
+ return details;
9526
+ };
9527
+
9528
+ /**
9529
+ * @license
9530
+ * Copyright 2025 Google LLC
9531
+ * SPDX-License-Identifier: Apache-2.0
9532
+ */
9533
+ class Stream {
9534
+ constructor(iterator, controller, client) {
9535
+ this.iterator = iterator;
9536
+ this.controller = controller;
9537
+ this.client = client;
9538
+ }
9539
+ static fromSSEResponse(response, controller, client) {
9540
+ let consumed = false;
9541
+ const logger = client ? loggerFor(client) : console;
9542
+ function iterator() {
9543
+ return __asyncGenerator(this, arguments, function* iterator_1() {
9544
+ var _a, e_1, _b, _c;
9545
+ if (consumed) {
9546
+ throw new GeminiNextGenAPIClientError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
9547
+ }
9548
+ consumed = true;
9549
+ let done = false;
9550
+ try {
9551
+ try {
9552
+ for (var _d = true, _e = __asyncValues(_iterSSEMessages(response, controller)), _f; _f = yield __await(_e.next()), _a = _f.done, !_a; _d = true) {
9553
+ _c = _f.value;
9554
+ _d = false;
9555
+ const sse = _c;
9556
+ if (done)
9557
+ continue;
9558
+ if (sse.data.startsWith('[DONE]')) {
9559
+ done = true;
9560
+ continue;
9561
+ }
9562
+ else {
9563
+ try {
9564
+ // @ts-ignore
9565
+ yield yield __await(JSON.parse(sse.data));
9566
+ }
9567
+ catch (e) {
9568
+ logger.error(`Could not parse message into JSON:`, sse.data);
9569
+ logger.error(`From chunk:`, sse.raw);
9570
+ throw e;
9571
+ }
9572
+ }
9573
+ }
9574
+ }
9575
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
9576
+ finally {
9577
+ try {
9578
+ if (!_d && !_a && (_b = _e.return)) yield __await(_b.call(_e));
9579
+ }
9580
+ finally { if (e_1) throw e_1.error; }
9581
+ }
9582
+ done = true;
9583
+ }
9584
+ catch (e) {
9585
+ // If the user calls `stream.controller.abort()`, we should exit without throwing.
9586
+ if (isAbortError(e))
9587
+ return yield __await(void 0);
9588
+ throw e;
9589
+ }
9590
+ finally {
9591
+ // If the user `break`s, abort the ongoing request.
9592
+ if (!done)
9593
+ controller.abort();
9594
+ }
9595
+ });
9596
+ }
9597
+ return new Stream(iterator, controller, client);
9598
+ }
9599
+ /**
9600
+ * Generates a Stream from a newline-separated ReadableStream
9601
+ * where each item is a JSON value.
9602
+ */
9603
+ static fromReadableStream(readableStream, controller, client) {
9604
+ let consumed = false;
9605
+ function iterLines() {
9606
+ return __asyncGenerator(this, arguments, function* iterLines_1() {
9607
+ var _a, e_2, _b, _c;
9608
+ const lineDecoder = new LineDecoder();
9609
+ const iter = ReadableStreamToAsyncIterable(readableStream);
9610
+ try {
9611
+ for (var _d = true, iter_1 = __asyncValues(iter), iter_1_1; iter_1_1 = yield __await(iter_1.next()), _a = iter_1_1.done, !_a; _d = true) {
9612
+ _c = iter_1_1.value;
9613
+ _d = false;
9614
+ const chunk = _c;
9615
+ for (const line of lineDecoder.decode(chunk)) {
9616
+ yield yield __await(line);
9617
+ }
9618
+ }
9619
+ }
9620
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
9621
+ finally {
9622
+ try {
9623
+ if (!_d && !_a && (_b = iter_1.return)) yield __await(_b.call(iter_1));
9624
+ }
9625
+ finally { if (e_2) throw e_2.error; }
9626
+ }
9627
+ for (const line of lineDecoder.flush()) {
9628
+ yield yield __await(line);
9629
+ }
9630
+ });
9631
+ }
9632
+ function iterator() {
9633
+ return __asyncGenerator(this, arguments, function* iterator_2() {
9634
+ var _a, e_3, _b, _c;
9635
+ if (consumed) {
9636
+ throw new GeminiNextGenAPIClientError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
9637
+ }
9638
+ consumed = true;
9639
+ let done = false;
9640
+ try {
9641
+ try {
9642
+ for (var _d = true, _e = __asyncValues(iterLines()), _f; _f = yield __await(_e.next()), _a = _f.done, !_a; _d = true) {
9643
+ _c = _f.value;
9644
+ _d = false;
9645
+ const line = _c;
9646
+ if (done)
9647
+ continue;
9648
+ // @ts-ignore
9649
+ if (line)
9650
+ yield yield __await(JSON.parse(line));
9651
+ }
9652
+ }
9653
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
9654
+ finally {
9655
+ try {
9656
+ if (!_d && !_a && (_b = _e.return)) yield __await(_b.call(_e));
9657
+ }
9658
+ finally { if (e_3) throw e_3.error; }
9659
+ }
9660
+ done = true;
9661
+ }
9662
+ catch (e) {
9663
+ // If the user calls `stream.controller.abort()`, we should exit without throwing.
9664
+ if (isAbortError(e))
9665
+ return yield __await(void 0);
9666
+ throw e;
9667
+ }
9668
+ finally {
9669
+ // If the user `break`s, abort the ongoing request.
9670
+ if (!done)
9671
+ controller.abort();
9672
+ }
9673
+ });
9674
+ }
9675
+ return new Stream(iterator, controller, client);
9676
+ }
9677
+ [Symbol.asyncIterator]() {
9678
+ return this.iterator();
9679
+ }
9680
+ /**
9681
+ * Splits the stream into two streams which can be
9682
+ * independently read from at different speeds.
9683
+ */
9684
+ tee() {
9685
+ const left = [];
9686
+ const right = [];
9687
+ const iterator = this.iterator();
9688
+ const teeIterator = (queue) => {
9689
+ return {
9690
+ next: () => {
9691
+ if (queue.length === 0) {
9692
+ const result = iterator.next();
9693
+ left.push(result);
9694
+ right.push(result);
9695
+ }
9696
+ return queue.shift();
9697
+ },
9698
+ };
9699
+ };
9700
+ return [
9701
+ new Stream(() => teeIterator(left), this.controller, this.client),
9702
+ new Stream(() => teeIterator(right), this.controller, this.client),
9703
+ ];
9704
+ }
9705
+ /**
9706
+ * Converts this stream to a newline-separated ReadableStream of
9707
+ * JSON stringified values in the stream
9708
+ * which can be turned back into a Stream with `Stream.fromReadableStream()`.
9709
+ */
9710
+ toReadableStream() {
9711
+ const self = this;
9712
+ let iter;
9713
+ return makeReadableStream({
9714
+ async start() {
9715
+ iter = self[Symbol.asyncIterator]();
9716
+ },
9717
+ async pull(ctrl) {
9718
+ try {
9719
+ const { value, done } = await iter.next();
9720
+ if (done)
9721
+ return ctrl.close();
9722
+ const bytes = encodeUTF8(JSON.stringify(value) + '\n');
9723
+ ctrl.enqueue(bytes);
9724
+ }
9725
+ catch (err) {
9726
+ ctrl.error(err);
9727
+ }
9728
+ },
9729
+ async cancel() {
9730
+ var _a;
9731
+ await ((_a = iter.return) === null || _a === void 0 ? void 0 : _a.call(iter));
9732
+ },
9733
+ });
9734
+ }
9735
+ }
9736
+ function _iterSSEMessages(response, controller) {
9737
+ return __asyncGenerator(this, arguments, function* _iterSSEMessages_1() {
9738
+ var _a, e_4, _b, _c;
9739
+ if (!response.body) {
9740
+ controller.abort();
9741
+ if (typeof globalThis.navigator !== 'undefined' &&
9742
+ globalThis.navigator.product === 'ReactNative') {
9743
+ throw new GeminiNextGenAPIClientError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
9744
+ }
9745
+ throw new GeminiNextGenAPIClientError(`Attempted to iterate over a response with no body`);
9746
+ }
9747
+ const sseDecoder = new SSEDecoder();
9748
+ const lineDecoder = new LineDecoder();
9749
+ const iter = ReadableStreamToAsyncIterable(response.body);
9750
+ try {
9751
+ for (var _d = true, _e = __asyncValues(iterSSEChunks(iter)), _f; _f = yield __await(_e.next()), _a = _f.done, !_a; _d = true) {
9752
+ _c = _f.value;
9753
+ _d = false;
9754
+ const sseChunk = _c;
9755
+ for (const line of lineDecoder.decode(sseChunk)) {
9756
+ const sse = sseDecoder.decode(line);
9757
+ if (sse)
9758
+ yield yield __await(sse);
9759
+ }
9760
+ }
9761
+ }
9762
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
9763
+ finally {
9764
+ try {
9765
+ if (!_d && !_a && (_b = _e.return)) yield __await(_b.call(_e));
9766
+ }
9767
+ finally { if (e_4) throw e_4.error; }
9768
+ }
9769
+ for (const line of lineDecoder.flush()) {
9770
+ const sse = sseDecoder.decode(line);
9771
+ if (sse)
9772
+ yield yield __await(sse);
9773
+ }
9774
+ });
9775
+ }
9776
+ /**
9777
+ * Given an async iterable iterator, iterates over it and yields full
9778
+ * SSE chunks, i.e. yields when a double new-line is encountered.
9779
+ */
9780
+ function iterSSEChunks(iterator) {
9781
+ return __asyncGenerator(this, arguments, function* iterSSEChunks_1() {
9782
+ var _a, e_5, _b, _c;
9783
+ let data = new Uint8Array();
9784
+ try {
9785
+ for (var _d = true, iterator_3 = __asyncValues(iterator), iterator_3_1; iterator_3_1 = yield __await(iterator_3.next()), _a = iterator_3_1.done, !_a; _d = true) {
9786
+ _c = iterator_3_1.value;
9787
+ _d = false;
9788
+ const chunk = _c;
9789
+ if (chunk == null) {
9790
+ continue;
9791
+ }
9792
+ const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
9793
+ : typeof chunk === 'string' ? encodeUTF8(chunk)
9794
+ : chunk;
9795
+ let newData = new Uint8Array(data.length + binaryChunk.length);
9796
+ newData.set(data);
9797
+ newData.set(binaryChunk, data.length);
9798
+ data = newData;
9799
+ let patternIndex;
9800
+ while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
9801
+ yield yield __await(data.slice(0, patternIndex));
9802
+ data = data.slice(patternIndex);
9803
+ }
9804
+ }
9805
+ }
9806
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
9807
+ finally {
9808
+ try {
9809
+ if (!_d && !_a && (_b = iterator_3.return)) yield __await(_b.call(iterator_3));
9810
+ }
9811
+ finally { if (e_5) throw e_5.error; }
9812
+ }
9813
+ if (data.length > 0) {
9814
+ yield yield __await(data);
9815
+ }
9816
+ });
9817
+ }
9818
+ class SSEDecoder {
9819
+ constructor() {
9820
+ this.event = null;
9821
+ this.data = [];
9822
+ this.chunks = [];
9823
+ }
9824
+ decode(line) {
9825
+ if (line.endsWith('\r')) {
9826
+ line = line.substring(0, line.length - 1);
9827
+ }
9828
+ if (!line) {
9829
+ // empty line and we didn't previously encounter any messages
9830
+ if (!this.event && !this.data.length)
9831
+ return null;
9832
+ const sse = {
9833
+ event: this.event,
9834
+ data: this.data.join('\n'),
9835
+ raw: this.chunks,
9836
+ };
9837
+ this.event = null;
9838
+ this.data = [];
9839
+ this.chunks = [];
9840
+ return sse;
9841
+ }
9842
+ this.chunks.push(line);
9843
+ if (line.startsWith(':')) {
9844
+ return null;
9845
+ }
9846
+ let [fieldname, _, value] = partition(line, ':');
9847
+ if (value.startsWith(' ')) {
9848
+ value = value.substring(1);
9849
+ }
9850
+ if (fieldname === 'event') {
9851
+ this.event = value;
9852
+ }
9853
+ else if (fieldname === 'data') {
9854
+ this.data.push(value);
9855
+ }
9856
+ return null;
9857
+ }
9858
+ }
9859
+ function partition(str, delimiter) {
9860
+ const index = str.indexOf(delimiter);
9861
+ if (index !== -1) {
9862
+ return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
9863
+ }
9864
+ return [str, '', ''];
9865
+ }
9866
+
9867
+ /**
9868
+ * @license
9869
+ * Copyright 2025 Google LLC
9870
+ * SPDX-License-Identifier: Apache-2.0
9871
+ */
9872
+ async function defaultParseResponse(client, props) {
9873
+ const { response, requestLogID, retryOfRequestLogID, startTime } = props;
9874
+ const body = await (async () => {
9875
+ var _a;
9876
+ if (props.options.stream) {
9877
+ loggerFor(client).debug('response', response.status, response.url, response.headers, response.body);
9878
+ // Note: there is an invariant here that isn't represented in the type system
9879
+ // that if you set `stream: true` the response type must also be `Stream<T>`
9880
+ if (props.options.__streamClass) {
9881
+ return props.options.__streamClass.fromSSEResponse(response, props.controller, client);
9882
+ }
9883
+ return Stream.fromSSEResponse(response, props.controller, client);
9884
+ }
9885
+ // fetch refuses to read the body when the status code is 204.
9886
+ if (response.status === 204) {
9887
+ return null;
9888
+ }
9889
+ if (props.options.__binaryResponse) {
9890
+ return response;
9891
+ }
9892
+ const contentType = response.headers.get('content-type');
9893
+ const mediaType = (_a = contentType === null || contentType === void 0 ? void 0 : contentType.split(';')[0]) === null || _a === void 0 ? void 0 : _a.trim();
9894
+ const isJSON = (mediaType === null || mediaType === void 0 ? void 0 : mediaType.includes('application/json')) || (mediaType === null || mediaType === void 0 ? void 0 : mediaType.endsWith('+json'));
9895
+ if (isJSON) {
9896
+ const json = await response.json();
9897
+ return json;
9898
+ }
9899
+ const text = await response.text();
9900
+ return text;
9901
+ })();
9902
+ loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({
9903
+ retryOfRequestLogID,
9904
+ url: response.url,
9905
+ status: response.status,
9906
+ body,
9907
+ durationMs: Date.now() - startTime,
9908
+ }));
9909
+ return body;
9910
+ }
9911
+
9912
+ /**
9913
+ * @license
9914
+ * Copyright 2025 Google LLC
9915
+ * SPDX-License-Identifier: Apache-2.0
9916
+ */
9917
+ /**
9918
+ * A subclass of `Promise` providing additional helper methods
9919
+ * for interacting with the SDK.
9920
+ */
9921
+ class APIPromise extends Promise {
9922
+ constructor(client, responsePromise, parseResponse = defaultParseResponse) {
9923
+ super((resolve) => {
9924
+ // this is maybe a bit weird but this has to be a no-op to not implicitly
9925
+ // parse the response body; instead .then, .catch, .finally are overridden
9926
+ // to parse the response
9927
+ resolve(null);
9928
+ });
9929
+ this.responsePromise = responsePromise;
9930
+ this.parseResponse = parseResponse;
9931
+ this.client = client;
9932
+ }
9933
+ _thenUnwrap(transform) {
9934
+ return new APIPromise(this.client, this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props));
9935
+ }
9936
+ /**
9937
+ * Gets the raw `Response` instance instead of parsing the response
9938
+ * data.
9939
+ *
9940
+ * If you want to parse the response body but still get the `Response`
9941
+ * instance, you can use {@link withResponse()}.
9942
+ *
9943
+ * 👋 Getting the wrong TypeScript type for `Response`?
9944
+ * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
9945
+ * to your `tsconfig.json`.
9946
+ */
9947
+ asResponse() {
9948
+ return this.responsePromise.then((p) => p.response);
9949
+ }
9950
+ /**
9951
+ * Gets the parsed response data and the raw `Response` instance.
9952
+ *
9953
+ * If you just want to get the raw `Response` instance without parsing it,
9954
+ * you can use {@link asResponse()}.
9955
+ *
9956
+ * 👋 Getting the wrong TypeScript type for `Response`?
9957
+ * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
9958
+ * to your `tsconfig.json`.
9959
+ */
9960
+ async withResponse() {
9961
+ const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
9962
+ return { data, response };
9963
+ }
9964
+ parse() {
9965
+ if (!this.parsedPromise) {
9966
+ this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(this.client, data));
9967
+ }
9968
+ return this.parsedPromise;
9969
+ }
9970
+ then(onfulfilled, onrejected) {
9971
+ return this.parse().then(onfulfilled, onrejected);
9972
+ }
9973
+ catch(onrejected) {
9974
+ return this.parse().catch(onrejected);
9975
+ }
9976
+ finally(onfinally) {
9977
+ return this.parse().finally(onfinally);
9978
+ }
9979
+ }
9980
+
9981
+ /**
9982
+ * @license
9983
+ * Copyright 2025 Google LLC
9984
+ * SPDX-License-Identifier: Apache-2.0
9985
+ */
9986
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
9987
+ const brand_privateNullableHeaders = /* @__PURE__ */ Symbol('brand.privateNullableHeaders');
9988
+ function* iterateHeaders(headers) {
9989
+ if (!headers)
9990
+ return;
9991
+ if (brand_privateNullableHeaders in headers) {
9992
+ const { values, nulls } = headers;
9993
+ yield* values.entries();
9994
+ for (const name of nulls) {
9995
+ yield [name, null];
9996
+ }
9997
+ return;
9998
+ }
9999
+ let shouldClear = false;
10000
+ let iter;
10001
+ if (headers instanceof Headers) {
10002
+ iter = headers.entries();
10003
+ }
10004
+ else if (isReadonlyArray(headers)) {
10005
+ iter = headers;
10006
+ }
10007
+ else {
10008
+ shouldClear = true;
10009
+ iter = Object.entries(headers !== null && headers !== void 0 ? headers : {});
10010
+ }
10011
+ for (let row of iter) {
10012
+ const name = row[0];
10013
+ if (typeof name !== 'string')
10014
+ throw new TypeError('expected header name to be a string');
10015
+ const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];
10016
+ let didClear = false;
10017
+ for (const value of values) {
10018
+ if (value === undefined)
10019
+ continue;
10020
+ // Objects keys always overwrite older headers, they never append.
10021
+ // Yield a null to clear the header before adding the new values.
10022
+ if (shouldClear && !didClear) {
10023
+ didClear = true;
10024
+ yield [name, null];
10025
+ }
10026
+ yield [name, value];
10027
+ }
10028
+ }
10029
+ }
10030
+ const buildHeaders = (newHeaders) => {
10031
+ const targetHeaders = new Headers();
10032
+ const nullHeaders = new Set();
10033
+ for (const headers of newHeaders) {
10034
+ const seenHeaders = new Set();
10035
+ for (const [name, value] of iterateHeaders(headers)) {
10036
+ const lowerName = name.toLowerCase();
10037
+ if (!seenHeaders.has(lowerName)) {
10038
+ targetHeaders.delete(name);
10039
+ seenHeaders.add(lowerName);
10040
+ }
10041
+ if (value === null) {
10042
+ targetHeaders.delete(name);
10043
+ nullHeaders.add(lowerName);
10044
+ }
10045
+ else {
10046
+ targetHeaders.append(name, value);
10047
+ nullHeaders.delete(lowerName);
10048
+ }
10049
+ }
10050
+ }
10051
+ return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };
10052
+ };
10053
+
10054
+ /**
10055
+ * @license
10056
+ * Copyright 2025 Google LLC
10057
+ * SPDX-License-Identifier: Apache-2.0
10058
+ */
10059
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
10060
+ /**
10061
+ * Read an environment variable.
10062
+ *
10063
+ * Trims beginning and trailing whitespace.
10064
+ *
10065
+ * Will return undefined if the environment variable doesn't exist or cannot be accessed.
10066
+ */
10067
+ const readEnv = (env) => {
10068
+ var _a, _b, _c, _d, _e, _f;
10069
+ if (typeof globalThis.process !== 'undefined') {
10070
+ return (_c = (_b = (_a = globalThis.process.env) === null || _a === void 0 ? void 0 : _a[env]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : undefined;
10071
+ }
10072
+ if (typeof globalThis.Deno !== 'undefined') {
10073
+ return (_f = (_e = (_d = globalThis.Deno.env) === null || _d === void 0 ? void 0 : _d.get) === null || _e === void 0 ? void 0 : _e.call(_d, env)) === null || _f === void 0 ? void 0 : _f.trim();
10074
+ }
10075
+ return undefined;
10076
+ };
10077
+
10078
+ /**
10079
+ * @license
10080
+ * Copyright 2025 Google LLC
10081
+ * SPDX-License-Identifier: Apache-2.0
10082
+ */
10083
+ var _a;
10084
+ /**
10085
+ * Base class for Gemini Next Gen API API clients.
10086
+ */
10087
+ class BaseGeminiNextGenAPIClient {
10088
+ /**
10089
+ * API Client for interfacing with the Gemini Next Gen API API.
10090
+ *
10091
+ * @param {string | null | undefined} [opts.apiKey=process.env['GEMINI_API_KEY'] ?? null]
10092
+ * @param {string | undefined} [opts.apiVersion=v1beta]
10093
+ * @param {string} [opts.baseURL=process.env['GEMINI_NEXT_GEN_API_BASE_URL'] ?? https://generativelanguage.googleapis.com] - Override the default base URL for the API.
10094
+ * @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
10095
+ * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
10096
+ * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
10097
+ * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
10098
+ * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
10099
+ * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
10100
+ */
10101
+ constructor(_b) {
10102
+ var _c, _d, _e, _f, _g, _h, _j;
10103
+ var { baseURL = readEnv('GEMINI_NEXT_GEN_API_BASE_URL'), apiKey = (_c = readEnv('GEMINI_API_KEY')) !== null && _c !== void 0 ? _c : null, apiVersion = 'v1beta' } = _b, opts = __rest(_b, ["baseURL", "apiKey", "apiVersion"]);
10104
+ const options = Object.assign(Object.assign({ apiKey,
10105
+ apiVersion }, opts), { baseURL: baseURL || `https://generativelanguage.googleapis.com` });
10106
+ this.baseURL = options.baseURL;
10107
+ this.timeout = (_d = options.timeout) !== null && _d !== void 0 ? _d : BaseGeminiNextGenAPIClient.DEFAULT_TIMEOUT /* 1 minute */;
10108
+ this.logger = (_e = options.logger) !== null && _e !== void 0 ? _e : console;
10109
+ const defaultLogLevel = 'warn';
10110
+ // Set default logLevel early so that we can log a warning in parseLogLevel.
10111
+ this.logLevel = defaultLogLevel;
10112
+ this.logLevel =
10113
+ (_g = (_f = parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this)) !== null && _f !== void 0 ? _f : parseLogLevel(readEnv('GEMINI_NEXT_GEN_API_LOG'), "process.env['GEMINI_NEXT_GEN_API_LOG']", this)) !== null && _g !== void 0 ? _g : defaultLogLevel;
10114
+ this.fetchOptions = options.fetchOptions;
10115
+ this.maxRetries = (_h = options.maxRetries) !== null && _h !== void 0 ? _h : 2;
10116
+ this.fetch = (_j = options.fetch) !== null && _j !== void 0 ? _j : getDefaultFetch();
10117
+ this.encoder = FallbackEncoder;
10118
+ this._options = options;
10119
+ this.apiKey = apiKey;
10120
+ this.apiVersion = apiVersion;
10121
+ this.clientAdapter = options.clientAdapter;
10122
+ }
10123
+ /**
10124
+ * Create a new client instance re-using the same options given to the current client with optional overriding.
10125
+ */
10126
+ withOptions(options) {
10127
+ const client = new this.constructor(Object.assign(Object.assign(Object.assign({}, this._options), { baseURL: this.baseURL, maxRetries: this.maxRetries, timeout: this.timeout, logger: this.logger, logLevel: this.logLevel, fetch: this.fetch, fetchOptions: this.fetchOptions, apiKey: this.apiKey, apiVersion: this.apiVersion }), options));
10128
+ return client;
10129
+ }
10130
+ /**
10131
+ * Check whether the base URL is set to its default.
10132
+ */
10133
+ baseURLOverridden() {
10134
+ return this.baseURL !== 'https://generativelanguage.googleapis.com';
10135
+ }
10136
+ defaultQuery() {
10137
+ return this._options.defaultQuery;
10138
+ }
10139
+ validateHeaders({ values, nulls }) {
10140
+ // The headers object handles case insensitivity.
10141
+ if (values.has('authorization') || values.has('x-goog-api-key')) {
10142
+ return;
10143
+ }
10144
+ if (this.apiKey && values.get('x-goog-api-key')) {
10145
+ return;
10146
+ }
10147
+ if (nulls.has('x-goog-api-key')) {
10148
+ return;
10149
+ }
10150
+ throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted');
10151
+ }
10152
+ async authHeaders(opts) {
10153
+ const existingHeaders = buildHeaders([opts.headers]);
10154
+ if (existingHeaders.values.has('authorization') || existingHeaders.values.has('x-goog-api-key')) {
10155
+ return undefined;
10156
+ }
10157
+ if (this.apiKey) {
10158
+ return buildHeaders([{ 'x-goog-api-key': this.apiKey }]);
10159
+ }
10160
+ if (this.clientAdapter.isVertexAI()) {
10161
+ return buildHeaders([await this.clientAdapter.getAuthHeaders()]);
10162
+ }
10163
+ return undefined;
10164
+ }
10165
+ /**
10166
+ * Basic re-implementation of `qs.stringify` for primitive types.
8277
10167
  */
8278
- async create(params) {
8279
- var _a, _b;
8280
- let response;
8281
- let path = '';
8282
- let queryParams = {};
8283
- if (this.apiClient.isVertexAI()) {
8284
- throw new Error('This method is only supported by the Gemini Developer API.');
10168
+ stringifyQuery(query) {
10169
+ return Object.entries(query)
10170
+ .filter(([_, value]) => typeof value !== 'undefined')
10171
+ .map(([key, value]) => {
10172
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
10173
+ return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
10174
+ }
10175
+ if (value === null) {
10176
+ return `${encodeURIComponent(key)}=`;
10177
+ }
10178
+ throw new GeminiNextGenAPIClientError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
10179
+ })
10180
+ .join('&');
10181
+ }
10182
+ getUserAgent() {
10183
+ return `${this.constructor.name}/JS ${VERSION}`;
10184
+ }
10185
+ defaultIdempotencyKey() {
10186
+ return `stainless-node-retry-${uuid4()}`;
10187
+ }
10188
+ makeStatusError(status, error, message, headers) {
10189
+ return APIError.generate(status, error, message, headers);
10190
+ }
10191
+ buildURL(path, query, defaultBaseURL) {
10192
+ const baseURL = (!this.baseURLOverridden() && defaultBaseURL) || this.baseURL;
10193
+ const url = isAbsoluteURL(path) ?
10194
+ new URL(path)
10195
+ : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
10196
+ const defaultQuery = this.defaultQuery();
10197
+ if (!isEmptyObj(defaultQuery)) {
10198
+ query = Object.assign(Object.assign({}, defaultQuery), query);
8285
10199
  }
8286
- else {
8287
- const body = createFileSearchStoreParametersToMldev(params);
8288
- path = formatMap('fileSearchStores', body['_url']);
8289
- queryParams = body['_query'];
8290
- delete body['_url'];
8291
- delete body['_query'];
8292
- response = this.apiClient
8293
- .request({
8294
- path: path,
8295
- queryParams: queryParams,
8296
- body: JSON.stringify(body),
8297
- httpMethod: 'POST',
8298
- httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8299
- abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8300
- })
8301
- .then((httpResponse) => {
8302
- return httpResponse.json();
8303
- });
8304
- return response.then((resp) => {
8305
- return resp;
8306
- });
10200
+ if (typeof query === 'object' && query && !Array.isArray(query)) {
10201
+ url.search = this.stringifyQuery(query);
8307
10202
  }
10203
+ return url.toString();
8308
10204
  }
8309
10205
  /**
8310
- * Gets a File Search Store.
8311
- *
8312
- * @param params - The parameters for getting a File Search Store.
8313
- * @return FileSearchStore.
10206
+ * Used as a callback for mutating the given `FinalRequestOptions` object.
10207
+
8314
10208
  */
8315
- async get(params) {
8316
- var _a, _b;
8317
- let response;
8318
- let path = '';
8319
- let queryParams = {};
8320
- if (this.apiClient.isVertexAI()) {
8321
- throw new Error('This method is only supported by the Gemini Developer API.');
8322
- }
8323
- else {
8324
- const body = getFileSearchStoreParametersToMldev(params);
8325
- path = formatMap('{name}', body['_url']);
8326
- queryParams = body['_query'];
8327
- delete body['_url'];
8328
- delete body['_query'];
8329
- response = this.apiClient
8330
- .request({
8331
- path: path,
8332
- queryParams: queryParams,
8333
- body: JSON.stringify(body),
8334
- httpMethod: 'GET',
8335
- httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8336
- abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8337
- })
8338
- .then((httpResponse) => {
8339
- return httpResponse.json();
8340
- });
8341
- return response.then((resp) => {
8342
- return resp;
8343
- });
10209
+ async prepareOptions(options) {
10210
+ if (this.clientAdapter &&
10211
+ this.clientAdapter.isVertexAI() &&
10212
+ !options.path.startsWith(`/${this.apiVersion}/projects/`)) {
10213
+ const oldPath = options.path.slice(this.apiVersion.length + 1);
10214
+ options.path = `/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${oldPath}`;
8344
10215
  }
8345
10216
  }
8346
10217
  /**
8347
- * Deletes a File Search Store.
10218
+ * Used as a callback for mutating the given `RequestInit` object.
8348
10219
  *
8349
- * @param params - The parameters for deleting a File Search Store.
10220
+ * This is useful for cases where you want to add certain headers based off of
10221
+ * the request properties, e.g. `method` or `url`.
8350
10222
  */
8351
- async delete(params) {
8352
- var _a, _b;
8353
- let path = '';
8354
- let queryParams = {};
8355
- if (this.apiClient.isVertexAI()) {
8356
- throw new Error('This method is only supported by the Gemini Developer API.');
10223
+ async prepareRequest(request, { url, options }) { }
10224
+ get(path, opts) {
10225
+ return this.methodRequest('get', path, opts);
10226
+ }
10227
+ post(path, opts) {
10228
+ return this.methodRequest('post', path, opts);
10229
+ }
10230
+ patch(path, opts) {
10231
+ return this.methodRequest('patch', path, opts);
10232
+ }
10233
+ put(path, opts) {
10234
+ return this.methodRequest('put', path, opts);
10235
+ }
10236
+ delete(path, opts) {
10237
+ return this.methodRequest('delete', path, opts);
10238
+ }
10239
+ methodRequest(method, path, opts) {
10240
+ return this.request(Promise.resolve(opts).then((opts) => {
10241
+ return Object.assign({ method, path }, opts);
10242
+ }));
10243
+ }
10244
+ request(options, remainingRetries = null) {
10245
+ return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
10246
+ }
10247
+ async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
10248
+ var _b, _c, _d;
10249
+ const options = await optionsInput;
10250
+ const maxRetries = (_b = options.maxRetries) !== null && _b !== void 0 ? _b : this.maxRetries;
10251
+ if (retriesRemaining == null) {
10252
+ retriesRemaining = maxRetries;
8357
10253
  }
8358
- else {
8359
- const body = deleteFileSearchStoreParametersToMldev(params);
8360
- path = formatMap('{name}', body['_url']);
8361
- queryParams = body['_query'];
8362
- delete body['_url'];
8363
- delete body['_query'];
8364
- await this.apiClient.request({
8365
- path: path,
8366
- queryParams: queryParams,
8367
- body: JSON.stringify(body),
8368
- httpMethod: 'DELETE',
8369
- httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8370
- abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8371
- });
10254
+ await this.prepareOptions(options);
10255
+ const { req, url, timeout } = await this.buildRequest(options, {
10256
+ retryCount: maxRetries - retriesRemaining,
10257
+ });
10258
+ await this.prepareRequest(req, { url, options });
10259
+ /** Not an API request ID, just for correlating local log entries. */
10260
+ const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
10261
+ const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
10262
+ const startTime = Date.now();
10263
+ loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
10264
+ retryOfRequestLogID,
10265
+ method: options.method,
10266
+ url,
10267
+ options,
10268
+ headers: req.headers,
10269
+ }));
10270
+ if ((_c = options.signal) === null || _c === void 0 ? void 0 : _c.aborted) {
10271
+ throw new APIUserAbortError();
10272
+ }
10273
+ const controller = new AbortController();
10274
+ const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
10275
+ const headersTime = Date.now();
10276
+ if (response instanceof globalThis.Error) {
10277
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
10278
+ if ((_d = options.signal) === null || _d === void 0 ? void 0 : _d.aborted) {
10279
+ throw new APIUserAbortError();
10280
+ }
10281
+ // detect native connection timeout errors
10282
+ // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
10283
+ // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
10284
+ // others do not provide enough information to distinguish timeouts from other connection errors
10285
+ const isTimeout = isAbortError(response) ||
10286
+ /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
10287
+ if (retriesRemaining) {
10288
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
10289
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
10290
+ retryOfRequestLogID,
10291
+ url,
10292
+ durationMs: headersTime - startTime,
10293
+ message: response.message,
10294
+ }));
10295
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID !== null && retryOfRequestLogID !== void 0 ? retryOfRequestLogID : requestLogID);
10296
+ }
10297
+ loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
10298
+ loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
10299
+ retryOfRequestLogID,
10300
+ url,
10301
+ durationMs: headersTime - startTime,
10302
+ message: response.message,
10303
+ }));
10304
+ if (isTimeout) {
10305
+ throw new APIConnectionTimeoutError();
10306
+ }
10307
+ throw new APIConnectionError({ cause: response });
10308
+ }
10309
+ const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
10310
+ if (!response.ok) {
10311
+ const shouldRetry = await this.shouldRetry(response);
10312
+ if (retriesRemaining && shouldRetry) {
10313
+ const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
10314
+ // We don't need the body of this response.
10315
+ await CancelReadableStream(response.body);
10316
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
10317
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
10318
+ retryOfRequestLogID,
10319
+ url: response.url,
10320
+ status: response.status,
10321
+ headers: response.headers,
10322
+ durationMs: headersTime - startTime,
10323
+ }));
10324
+ return this.retryRequest(options, retriesRemaining, retryOfRequestLogID !== null && retryOfRequestLogID !== void 0 ? retryOfRequestLogID : requestLogID, response.headers);
10325
+ }
10326
+ const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
10327
+ loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
10328
+ const errText = await response.text().catch((err) => castToError(err).message);
10329
+ const errJSON = safeJSON(errText);
10330
+ const errMessage = errJSON ? undefined : errText;
10331
+ loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
10332
+ retryOfRequestLogID,
10333
+ url: response.url,
10334
+ status: response.status,
10335
+ headers: response.headers,
10336
+ message: errMessage,
10337
+ durationMs: Date.now() - startTime,
10338
+ }));
10339
+ // @ts-ignore
10340
+ const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
10341
+ throw err;
10342
+ }
10343
+ loggerFor(this).info(responseInfo);
10344
+ loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
10345
+ retryOfRequestLogID,
10346
+ url: response.url,
10347
+ status: response.status,
10348
+ headers: response.headers,
10349
+ durationMs: headersTime - startTime,
10350
+ }));
10351
+ return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
10352
+ }
10353
+ async fetchWithTimeout(url, init, ms, controller) {
10354
+ const _b = init || {}, { signal, method } = _b, options = __rest(_b, ["signal", "method"]);
10355
+ if (signal)
10356
+ signal.addEventListener('abort', () => controller.abort());
10357
+ const timeout = setTimeout(() => controller.abort(), ms);
10358
+ const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
10359
+ (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
10360
+ const fetchOptions = Object.assign(Object.assign(Object.assign({ signal: controller.signal }, (isReadableBody ? { duplex: 'half' } : {})), { method: 'GET' }), options);
10361
+ if (method) {
10362
+ // Custom methods like 'patch' need to be uppercased
10363
+ // See https://github.com/nodejs/undici/issues/2294
10364
+ fetchOptions.method = method.toUpperCase();
8372
10365
  }
8373
- }
8374
- async listInternal(params) {
8375
- var _a, _b;
8376
- let response;
8377
- let path = '';
8378
- let queryParams = {};
8379
- if (this.apiClient.isVertexAI()) {
8380
- throw new Error('This method is only supported by the Gemini Developer API.');
10366
+ try {
10367
+ // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
10368
+ return await this.fetch.call(undefined, url, fetchOptions);
8381
10369
  }
8382
- else {
8383
- const body = listFileSearchStoresParametersToMldev(params);
8384
- path = formatMap('fileSearchStores', body['_url']);
8385
- queryParams = body['_query'];
8386
- delete body['_url'];
8387
- delete body['_query'];
8388
- response = this.apiClient
8389
- .request({
8390
- path: path,
8391
- queryParams: queryParams,
8392
- body: JSON.stringify(body),
8393
- httpMethod: 'GET',
8394
- httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8395
- abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8396
- })
8397
- .then((httpResponse) => {
8398
- return httpResponse.json();
8399
- });
8400
- return response.then((apiResponse) => {
8401
- const resp = listFileSearchStoresResponseFromMldev(apiResponse);
8402
- const typedResp = new ListFileSearchStoresResponse();
8403
- Object.assign(typedResp, resp);
8404
- return typedResp;
8405
- });
10370
+ finally {
10371
+ clearTimeout(timeout);
8406
10372
  }
8407
10373
  }
8408
- async uploadToFileSearchStoreInternal(params) {
8409
- var _a, _b;
8410
- let response;
8411
- let path = '';
8412
- let queryParams = {};
8413
- if (this.apiClient.isVertexAI()) {
8414
- throw new Error('This method is only supported by the Gemini Developer API.');
10374
+ async shouldRetry(response) {
10375
+ // Note this is not a standard header.
10376
+ const shouldRetryHeader = response.headers.get('x-should-retry');
10377
+ // If the server explicitly says whether or not to retry, obey.
10378
+ if (shouldRetryHeader === 'true')
10379
+ return true;
10380
+ if (shouldRetryHeader === 'false')
10381
+ return false;
10382
+ // Retry on request timeouts.
10383
+ if (response.status === 408)
10384
+ return true;
10385
+ // Retry on lock timeouts.
10386
+ if (response.status === 409)
10387
+ return true;
10388
+ // Retry on rate limits.
10389
+ if (response.status === 429)
10390
+ return true;
10391
+ // Retry internal errors.
10392
+ if (response.status >= 500)
10393
+ return true;
10394
+ return false;
10395
+ }
10396
+ async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
10397
+ var _b;
10398
+ let timeoutMillis;
10399
+ // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
10400
+ const retryAfterMillisHeader = responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders.get('retry-after-ms');
10401
+ if (retryAfterMillisHeader) {
10402
+ const timeoutMs = parseFloat(retryAfterMillisHeader);
10403
+ if (!Number.isNaN(timeoutMs)) {
10404
+ timeoutMillis = timeoutMs;
10405
+ }
8415
10406
  }
8416
- else {
8417
- const body = uploadToFileSearchStoreParametersToMldev(params);
8418
- path = formatMap('upload/v1beta/{file_search_store_name}:uploadToFileSearchStore', body['_url']);
8419
- queryParams = body['_query'];
8420
- delete body['_url'];
8421
- delete body['_query'];
8422
- response = this.apiClient
8423
- .request({
8424
- path: path,
8425
- queryParams: queryParams,
8426
- body: JSON.stringify(body),
8427
- httpMethod: 'POST',
8428
- httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8429
- abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8430
- })
8431
- .then((httpResponse) => {
8432
- return httpResponse.json();
8433
- });
8434
- return response.then((apiResponse) => {
8435
- const resp = uploadToFileSearchStoreResumableResponseFromMldev(apiResponse);
8436
- const typedResp = new UploadToFileSearchStoreResumableResponse();
8437
- Object.assign(typedResp, resp);
8438
- return typedResp;
8439
- });
10407
+ // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
10408
+ const retryAfterHeader = responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders.get('retry-after');
10409
+ if (retryAfterHeader && !timeoutMillis) {
10410
+ const timeoutSeconds = parseFloat(retryAfterHeader);
10411
+ if (!Number.isNaN(timeoutSeconds)) {
10412
+ timeoutMillis = timeoutSeconds * 1000;
10413
+ }
10414
+ else {
10415
+ timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
10416
+ }
8440
10417
  }
8441
- }
8442
- /**
8443
- * Imports a File from File Service to a FileSearchStore.
8444
- *
8445
- * This is a long-running operation, see aip.dev/151
8446
- *
8447
- * @param params - The parameters for importing a file to a file search store.
8448
- * @return ImportFileOperation.
8449
- */
8450
- async importFile(params) {
8451
- var _a, _b;
8452
- let response;
8453
- let path = '';
8454
- let queryParams = {};
8455
- if (this.apiClient.isVertexAI()) {
8456
- throw new Error('This method is only supported by the Gemini Developer API.');
10418
+ // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
10419
+ // just do what it says, but otherwise calculate a default
10420
+ if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
10421
+ const maxRetries = (_b = options.maxRetries) !== null && _b !== void 0 ? _b : this.maxRetries;
10422
+ timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
10423
+ }
10424
+ await sleep(timeoutMillis);
10425
+ return this.makeRequest(options, retriesRemaining - 1, requestLogID);
10426
+ }
10427
+ calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
10428
+ const initialRetryDelay = 0.5;
10429
+ const maxRetryDelay = 8.0;
10430
+ const numRetries = maxRetries - retriesRemaining;
10431
+ // Apply exponential backoff, but not more than the max.
10432
+ const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
10433
+ // Apply some jitter, take up to at most 25 percent of the retry time.
10434
+ const jitter = 1 - Math.random() * 0.25;
10435
+ return sleepSeconds * jitter * 1000;
10436
+ }
10437
+ async buildRequest(inputOptions, { retryCount = 0 } = {}) {
10438
+ var _b, _c, _d;
10439
+ const options = Object.assign({}, inputOptions);
10440
+ const { method, path, query, defaultBaseURL } = options;
10441
+ const url = this.buildURL(path, query, defaultBaseURL);
10442
+ if ('timeout' in options)
10443
+ validatePositiveInteger('timeout', options.timeout);
10444
+ options.timeout = (_b = options.timeout) !== null && _b !== void 0 ? _b : this.timeout;
10445
+ const { bodyHeaders, body } = this.buildBody({ options });
10446
+ const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
10447
+ const req = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ method, headers: reqHeaders }, (options.signal && { signal: options.signal })), (globalThis.ReadableStream &&
10448
+ body instanceof globalThis.ReadableStream && { duplex: 'half' })), (body && { body })), ((_c = this.fetchOptions) !== null && _c !== void 0 ? _c : {})), ((_d = options.fetchOptions) !== null && _d !== void 0 ? _d : {}));
10449
+ return { req, url, timeout: options.timeout };
10450
+ }
10451
+ async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
10452
+ let idempotencyHeaders = {};
10453
+ if (this.idempotencyHeader && method !== 'get') {
10454
+ if (!options.idempotencyKey)
10455
+ options.idempotencyKey = this.defaultIdempotencyKey();
10456
+ idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
10457
+ }
10458
+ const authHeaders = await this.authHeaders(options);
10459
+ let headers = buildHeaders([
10460
+ idempotencyHeaders,
10461
+ Object.assign(Object.assign({ Accept: 'application/json', 'User-Agent': this.getUserAgent(), 'X-Stainless-Retry-Count': String(retryCount) }, (options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {})), getPlatformHeaders()),
10462
+ this._options.defaultHeaders,
10463
+ bodyHeaders,
10464
+ options.headers,
10465
+ authHeaders,
10466
+ ]);
10467
+ this.validateHeaders(headers);
10468
+ return headers.values;
10469
+ }
10470
+ buildBody({ options: { body, headers: rawHeaders } }) {
10471
+ if (!body) {
10472
+ return { bodyHeaders: undefined, body: undefined };
10473
+ }
10474
+ const headers = buildHeaders([rawHeaders]);
10475
+ if (
10476
+ // Pass raw type verbatim
10477
+ ArrayBuffer.isView(body) ||
10478
+ body instanceof ArrayBuffer ||
10479
+ body instanceof DataView ||
10480
+ (typeof body === 'string' &&
10481
+ // Preserve legacy string encoding behavior for now
10482
+ headers.values.has('content-type')) ||
10483
+ // `Blob` is superset of `File`
10484
+ (globalThis.Blob && body instanceof globalThis.Blob) ||
10485
+ // `FormData` -> `multipart/form-data`
10486
+ body instanceof FormData ||
10487
+ // `URLSearchParams` -> `application/x-www-form-urlencoded`
10488
+ body instanceof URLSearchParams ||
10489
+ // Send chunked stream (each chunk has own `length`)
10490
+ (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
10491
+ return { bodyHeaders: undefined, body: body };
10492
+ }
10493
+ else if (typeof body === 'object' &&
10494
+ (Symbol.asyncIterator in body ||
10495
+ (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
10496
+ return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
8457
10497
  }
8458
10498
  else {
8459
- const body = importFileParametersToMldev(params);
8460
- path = formatMap('{file_search_store_name}:importFile', body['_url']);
8461
- queryParams = body['_query'];
8462
- delete body['_url'];
8463
- delete body['_query'];
8464
- response = this.apiClient
8465
- .request({
8466
- path: path,
8467
- queryParams: queryParams,
8468
- body: JSON.stringify(body),
8469
- httpMethod: 'POST',
8470
- httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
8471
- abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
8472
- })
8473
- .then((httpResponse) => {
8474
- return httpResponse.json();
8475
- });
8476
- return response.then((apiResponse) => {
8477
- const resp = importFileOperationFromMldev(apiResponse);
8478
- const typedResp = new ImportFileOperation();
8479
- Object.assign(typedResp, resp);
8480
- return typedResp;
8481
- });
10499
+ return this.encoder({ body, headers });
8482
10500
  }
8483
10501
  }
8484
10502
  }
10503
+ BaseGeminiNextGenAPIClient.DEFAULT_TIMEOUT = 60000; // 1 minute
10504
+ /**
10505
+ * API Client for interfacing with the Gemini Next Gen API API.
10506
+ */
10507
+ class GeminiNextGenAPIClient extends BaseGeminiNextGenAPIClient {
10508
+ constructor() {
10509
+ super(...arguments);
10510
+ this.interactions = new Interactions(this);
10511
+ }
10512
+ }
10513
+ _a = GeminiNextGenAPIClient;
10514
+ GeminiNextGenAPIClient.GeminiNextGenAPIClient = _a;
10515
+ GeminiNextGenAPIClient.GeminiNextGenAPIClientError = GeminiNextGenAPIClientError;
10516
+ GeminiNextGenAPIClient.APIError = APIError;
10517
+ GeminiNextGenAPIClient.APIConnectionError = APIConnectionError;
10518
+ GeminiNextGenAPIClient.APIConnectionTimeoutError = APIConnectionTimeoutError;
10519
+ GeminiNextGenAPIClient.APIUserAbortError = APIUserAbortError;
10520
+ GeminiNextGenAPIClient.NotFoundError = NotFoundError;
10521
+ GeminiNextGenAPIClient.ConflictError = ConflictError;
10522
+ GeminiNextGenAPIClient.RateLimitError = RateLimitError;
10523
+ GeminiNextGenAPIClient.BadRequestError = BadRequestError;
10524
+ GeminiNextGenAPIClient.AuthenticationError = AuthenticationError;
10525
+ GeminiNextGenAPIClient.InternalServerError = InternalServerError;
10526
+ GeminiNextGenAPIClient.PermissionDeniedError = PermissionDeniedError;
10527
+ GeminiNextGenAPIClient.UnprocessableEntityError = UnprocessableEntityError;
10528
+ GeminiNextGenAPIClient.toFile = toFile;
10529
+ GeminiNextGenAPIClient.Interactions = Interactions;
8485
10530
 
8486
10531
  /**
8487
10532
  * @license
@@ -8689,7 +10734,7 @@ function generationConfigToVertex$1(fromObject) {
8689
10734
  }
8690
10735
  const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']);
8691
10736
  if (fromSpeechConfig != null) {
8692
- setValueByPath(toObject, ['speechConfig'], speechConfigToVertex$1(fromSpeechConfig));
10737
+ setValueByPath(toObject, ['speechConfig'], fromSpeechConfig);
8693
10738
  }
8694
10739
  const fromStopSequences = getValueByPath(fromObject, [
8695
10740
  'stopSequences',
@@ -8856,6 +10901,9 @@ function liveConnectConfigToMldev$1(fromObject, parentObject) {
8856
10901
  if (parentObject !== undefined && fromProactivity != null) {
8857
10902
  setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity);
8858
10903
  }
10904
+ if (getValueByPath(fromObject, ['explicitVadSignal']) !== undefined) {
10905
+ throw new Error('explicitVadSignal parameter is not supported in Gemini API.');
10906
+ }
8859
10907
  return toObject;
8860
10908
  }
8861
10909
  function liveConnectConfigToVertex(fromObject, parentObject) {
@@ -8902,7 +10950,7 @@ function liveConnectConfigToVertex(fromObject, parentObject) {
8902
10950
  }
8903
10951
  const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']);
8904
10952
  if (parentObject !== undefined && fromSpeechConfig != null) {
8905
- setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig)));
10953
+ setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], tLiveSpeechConfig(fromSpeechConfig));
8906
10954
  }
8907
10955
  const fromThinkingConfig = getValueByPath(fromObject, [
8908
10956
  'thinkingConfig',
@@ -8966,6 +11014,12 @@ function liveConnectConfigToVertex(fromObject, parentObject) {
8966
11014
  if (parentObject !== undefined && fromProactivity != null) {
8967
11015
  setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity);
8968
11016
  }
11017
+ const fromExplicitVadSignal = getValueByPath(fromObject, [
11018
+ 'explicitVadSignal',
11019
+ ]);
11020
+ if (parentObject !== undefined && fromExplicitVadSignal != null) {
11021
+ setValueByPath(parentObject, ['setup', 'explicitVadSignal'], fromExplicitVadSignal);
11022
+ }
8969
11023
  return toObject;
8970
11024
  }
8971
11025
  function liveConnectParametersToMldev(apiClient, fromObject) {
@@ -9142,6 +11196,12 @@ function liveServerMessageFromVertex(fromObject) {
9142
11196
  if (fromSessionResumptionUpdate != null) {
9143
11197
  setValueByPath(toObject, ['sessionResumptionUpdate'], fromSessionResumptionUpdate);
9144
11198
  }
11199
+ const fromVoiceActivityDetectionSignal = getValueByPath(fromObject, [
11200
+ 'voiceActivityDetectionSignal',
11201
+ ]);
11202
+ if (fromVoiceActivityDetectionSignal != null) {
11203
+ setValueByPath(toObject, ['voiceActivityDetectionSignal'], fromVoiceActivityDetectionSignal);
11204
+ }
9145
11205
  return toObject;
9146
11206
  }
9147
11207
  function partToMldev$2(fromObject) {
@@ -9215,21 +11275,6 @@ function sessionResumptionConfigToMldev$1(fromObject) {
9215
11275
  }
9216
11276
  return toObject;
9217
11277
  }
9218
- function speechConfigToVertex$1(fromObject) {
9219
- const toObject = {};
9220
- const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']);
9221
- if (fromVoiceConfig != null) {
9222
- setValueByPath(toObject, ['voiceConfig'], fromVoiceConfig);
9223
- }
9224
- const fromLanguageCode = getValueByPath(fromObject, ['languageCode']);
9225
- if (fromLanguageCode != null) {
9226
- setValueByPath(toObject, ['languageCode'], fromLanguageCode);
9227
- }
9228
- if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) {
9229
- throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.');
9230
- }
9231
- return toObject;
9232
- }
9233
11278
  function toolToMldev$2(fromObject) {
9234
11279
  const toObject = {};
9235
11280
  const fromFunctionDeclarations = getValueByPath(fromObject, [
@@ -10472,7 +12517,7 @@ function generateContentConfigToVertex(apiClient, fromObject, parentObject) {
10472
12517
  }
10473
12518
  const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']);
10474
12519
  if (fromSpeechConfig != null) {
10475
- setValueByPath(toObject, ['speechConfig'], speechConfigToVertex(tSpeechConfig(fromSpeechConfig)));
12520
+ setValueByPath(toObject, ['speechConfig'], tSpeechConfig(fromSpeechConfig));
10476
12521
  }
10477
12522
  const fromAudioTimestamp = getValueByPath(fromObject, [
10478
12523
  'audioTimestamp',
@@ -11418,7 +13463,7 @@ function generationConfigToVertex(fromObject) {
11418
13463
  }
11419
13464
  const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']);
11420
13465
  if (fromSpeechConfig != null) {
11421
- setValueByPath(toObject, ['speechConfig'], speechConfigToVertex(fromSpeechConfig));
13466
+ setValueByPath(toObject, ['speechConfig'], fromSpeechConfig);
11422
13467
  }
11423
13468
  const fromStopSequences = getValueByPath(fromObject, [
11424
13469
  'stopSequences',
@@ -12220,21 +14265,6 @@ function segmentImageSourceToVertex(fromObject, parentObject) {
12220
14265
  }
12221
14266
  return toObject;
12222
14267
  }
12223
- function speechConfigToVertex(fromObject) {
12224
- const toObject = {};
12225
- const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']);
12226
- if (fromVoiceConfig != null) {
12227
- setValueByPath(toObject, ['voiceConfig'], fromVoiceConfig);
12228
- }
12229
- const fromLanguageCode = getValueByPath(fromObject, ['languageCode']);
12230
- if (fromLanguageCode != null) {
12231
- setValueByPath(toObject, ['languageCode'], fromLanguageCode);
12232
- }
12233
- if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) {
12234
- throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.');
12235
- }
12236
- return toObject;
12237
- }
12238
14268
  function toolConfigToMldev(fromObject) {
12239
14269
  const toObject = {};
12240
14270
  const fromFunctionCallingConfig = getValueByPath(fromObject, [
@@ -15524,6 +17554,9 @@ function liveConnectConfigToMldev(fromObject, parentObject) {
15524
17554
  if (parentObject !== undefined && fromProactivity != null) {
15525
17555
  setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity);
15526
17556
  }
17557
+ if (getValueByPath(fromObject, ['explicitVadSignal']) !== undefined) {
17558
+ throw new Error('explicitVadSignal parameter is not supported in Gemini API.');
17559
+ }
15527
17560
  return toObject;
15528
17561
  }
15529
17562
  function liveConnectConstraintsToMldev(apiClient, fromObject) {
@@ -17067,6 +19100,30 @@ const LANGUAGE_LABEL_PREFIX = 'gl-node/';
17067
19100
  *
17068
19101
  */
17069
19102
  class GoogleGenAI {
19103
+ get interactions() {
19104
+ if (this._interactions !== undefined) {
19105
+ return this._interactions;
19106
+ }
19107
+ console.warn('GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions.');
19108
+ if (this.vertexai) {
19109
+ throw new Error('This version of the GenAI SDK does not support Vertex AI API for interactions.');
19110
+ }
19111
+ const httpOpts = this.httpOptions;
19112
+ // Unsupported Options Warnings
19113
+ if (httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.extraBody) {
19114
+ console.warn('GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.');
19115
+ }
19116
+ const nextGenClient = new GeminiNextGenAPIClient({
19117
+ baseURL: this.apiClient.getBaseUrl(),
19118
+ apiKey: this.apiKey,
19119
+ apiVersion: this.apiClient.getApiVersion(),
19120
+ clientAdapter: this.apiClient,
19121
+ defaultHeaders: this.apiClient.getDefaultHeaders(),
19122
+ timeout: httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.timeout,
19123
+ });
19124
+ this._interactions = nextGenClient.interactions;
19125
+ return this._interactions;
19126
+ }
17070
19127
  constructor(options) {
17071
19128
  var _a;
17072
19129
  if (options.apiKey == null) {
@@ -17100,5 +19157,5 @@ class GoogleGenAI {
17100
19157
  }
17101
19158
  }
17102
19159
 
17103
- export { ActivityHandling, AdapterSize, ApiError, ApiSpec, AuthType, Batches, Behavior, BlockedReason, Caches, CancelTuningJobResponse, Chat, Chats, ComputeTokensResponse, ContentReferenceImage, ControlReferenceImage, ControlReferenceType, CountTokensResponse, CreateFileResponse, DeleteCachedContentResponse, DeleteFileResponse, DeleteModelResponse, DocumentState, DynamicRetrievalConfigMode, EditImageResponse, EditMode, EmbedContentResponse, EndSensitivity, Environment, FeatureSelectionPreference, FileSource, FileState, Files, FinishReason, FunctionCallingConfigMode, FunctionResponse, FunctionResponseBlob, FunctionResponseFileData, FunctionResponsePart, FunctionResponseScheduling, GenerateContentResponse, GenerateContentResponsePromptFeedback, GenerateContentResponseUsageMetadata, GenerateImagesResponse, GenerateVideosOperation, GenerateVideosResponse, GoogleGenAI, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, HttpElementLocation, HttpResponse, ImagePromptLanguage, ImportFileOperation, ImportFileResponse, InlinedEmbedContentResponse, InlinedResponse, JobState, Language, ListBatchJobsResponse, ListCachedContentsResponse, ListDocumentsResponse, ListFileSearchStoresResponse, ListFilesResponse, ListModelsResponse, ListTuningJobsResponse, Live, LiveClientToolResponse, LiveMusicPlaybackControl, LiveMusicServerMessage, LiveSendToolResponseParameters, LiveServerMessage, MaskReferenceImage, MaskReferenceMode, MediaModality, MediaResolution, Modality, Mode, Models, MusicGenerationMode, Operations, Outcome, PagedItem, Pager, PartMediaResolutionLevel, PersonGeneration, PhishBlockThreshold, RawReferenceImage, RecontextImageResponse, ReplayResponse, SafetyFilterLevel, Scale, SegmentImageResponse, SegmentMode, Session, SingleEmbedContentResponse, StartSensitivity, StyleReferenceImage, SubjectReferenceImage, SubjectReferenceType, ThinkingLevel, Tokens, TrafficType, TuningMethod, TuningMode, TuningTask, TurnCompleteReason, TurnCoverage, Type, UploadToFileSearchStoreOperation, UploadToFileSearchStoreResponse, UploadToFileSearchStoreResumableResponse, UpscaleImageResponse, UrlRetrievalStatus, VideoCompressionQuality, VideoGenerationMaskMode, VideoGenerationReferenceType, createFunctionResponsePartFromBase64, createFunctionResponsePartFromUri, createModelContent, createPartFromBase64, createPartFromCodeExecutionResult, createPartFromExecutableCode, createPartFromFunctionCall, createPartFromFunctionResponse, createPartFromText, createPartFromUri, createUserContent, mcpToTool, setDefaultBaseUrls };
19160
+ export { ActivityHandling, AdapterSize, ApiError, ApiSpec, AuthType, Batches, Behavior, BlockedReason, Caches, CancelTuningJobResponse, Chat, Chats, ComputeTokensResponse, ContentReferenceImage, ControlReferenceImage, ControlReferenceType, CountTokensResponse, CreateFileResponse, DeleteCachedContentResponse, DeleteFileResponse, DeleteModelResponse, DocumentState, DynamicRetrievalConfigMode, EditImageResponse, EditMode, EmbedContentResponse, EndSensitivity, Environment, FeatureSelectionPreference, FileSource, FileState, Files, FinishReason, FunctionCallingConfigMode, FunctionResponse, FunctionResponseBlob, FunctionResponseFileData, FunctionResponsePart, FunctionResponseScheduling, GenerateContentResponse, GenerateContentResponsePromptFeedback, GenerateContentResponseUsageMetadata, GenerateImagesResponse, GenerateVideosOperation, GenerateVideosResponse, GoogleGenAI, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, HttpElementLocation, HttpResponse, ImagePromptLanguage, ImportFileOperation, ImportFileResponse, InlinedEmbedContentResponse, InlinedResponse, JobState, Language, ListBatchJobsResponse, ListCachedContentsResponse, ListDocumentsResponse, ListFileSearchStoresResponse, ListFilesResponse, ListModelsResponse, ListTuningJobsResponse, Live, LiveClientToolResponse, LiveMusicPlaybackControl, LiveMusicServerMessage, LiveSendToolResponseParameters, LiveServerMessage, MaskReferenceImage, MaskReferenceMode, MediaModality, MediaResolution, Modality, Mode, Models, MusicGenerationMode, Operations, Outcome, PagedItem, Pager, PartMediaResolutionLevel, PersonGeneration, PhishBlockThreshold, RawReferenceImage, RecontextImageResponse, ReplayResponse, SafetyFilterLevel, Scale, SegmentImageResponse, SegmentMode, Session, SingleEmbedContentResponse, StartSensitivity, StyleReferenceImage, SubjectReferenceImage, SubjectReferenceType, ThinkingLevel, Tokens, TrafficType, TuningMethod, TuningMode, TuningTask, TurnCompleteReason, TurnCoverage, Type, UploadToFileSearchStoreOperation, UploadToFileSearchStoreResponse, UploadToFileSearchStoreResumableResponse, UpscaleImageResponse, UrlRetrievalStatus, VadSignalType, VideoCompressionQuality, VideoGenerationMaskMode, VideoGenerationReferenceType, createFunctionResponsePartFromBase64, createFunctionResponsePartFromUri, createModelContent, createPartFromBase64, createPartFromCodeExecutionResult, createPartFromExecutableCode, createPartFromFunctionCall, createPartFromFunctionResponse, createPartFromText, createPartFromUri, createUserContent, mcpToTool, setDefaultBaseUrls };
17104
19161
  //# sourceMappingURL=index.mjs.map