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