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