@google/genai 1.30.0 → 1.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -2194,6 +2194,9 @@ class GenerateVideosOperation {
2194
2194
  /** Response for the list tuning jobs method. */
2195
2195
  class ListTuningJobsResponse {
2196
2196
  }
2197
+ /** Empty response for tunings.cancel method. */
2198
+ class CancelTuningJobResponse {
2199
+ }
2197
2200
  /** Empty response for caches.delete method. */
2198
2201
  class DeleteCachedContentResponse {
2199
2202
  }
@@ -4080,6 +4083,12 @@ function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) {
4080
4083
  if (fromImageConfig != null) {
4081
4084
  setValueByPath(toObject, ['imageConfig'], imageConfigToMldev$1(fromImageConfig));
4082
4085
  }
4086
+ const fromEnableEnhancedCivicAnswers = getValueByPath(fromObject, [
4087
+ 'enableEnhancedCivicAnswers',
4088
+ ]);
4089
+ if (fromEnableEnhancedCivicAnswers != null) {
4090
+ setValueByPath(toObject, ['enableEnhancedCivicAnswers'], fromEnableEnhancedCivicAnswers);
4091
+ }
4083
4092
  return toObject;
4084
4093
  }
4085
4094
  function generateContentResponseFromMldev$1(fromObject) {
@@ -4661,6 +4670,23 @@ class Batches extends BaseModule {
4661
4670
  constructor(apiClient) {
4662
4671
  super();
4663
4672
  this.apiClient = apiClient;
4673
+ /**
4674
+ * Lists batch jobs.
4675
+ *
4676
+ * @param params - The parameters for the list request.
4677
+ * @return - A pager of batch jobs.
4678
+ *
4679
+ * @example
4680
+ * ```ts
4681
+ * const batchJobs = await ai.batches.list({config: {'pageSize': 2}});
4682
+ * for await (const batchJob of batchJobs) {
4683
+ * console.log(batchJob);
4684
+ * }
4685
+ * ```
4686
+ */
4687
+ this.list = async (params = {}) => {
4688
+ return new Pager(PagedItem.PAGED_ITEM_BATCH_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params);
4689
+ };
4664
4690
  /**
4665
4691
  * Create batch job.
4666
4692
  *
@@ -4709,23 +4735,6 @@ class Batches extends BaseModule {
4709
4735
  }
4710
4736
  return this.createEmbeddingsInternal(params);
4711
4737
  };
4712
- /**
4713
- * Lists batch job configurations.
4714
- *
4715
- * @param params - The parameters for the list request.
4716
- * @return The paginated results of the list of batch jobs.
4717
- *
4718
- * @example
4719
- * ```ts
4720
- * const batchJobs = await ai.batches.list({config: {'pageSize': 2}});
4721
- * for await (const batchJob of batchJobs) {
4722
- * console.log(batchJob);
4723
- * }
4724
- * ```
4725
- */
4726
- this.list = async (params = {}) => {
4727
- return new Pager(PagedItem.PAGED_ITEM_BATCH_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params);
4728
- };
4729
4738
  }
4730
4739
  // Helper function to handle inlined generate content requests
4731
4740
  createInlinedGenerateContentRequest(params) {
@@ -5828,10 +5837,10 @@ class Caches extends BaseModule {
5828
5837
  super();
5829
5838
  this.apiClient = apiClient;
5830
5839
  /**
5831
- * Lists cached content configurations.
5840
+ * Lists cached contents.
5832
5841
  *
5833
5842
  * @param params - The parameters for the list request.
5834
- * @return The paginated results of the list of cached contents.
5843
+ * @return - A pager of cached contents.
5835
5844
  *
5836
5845
  * @example
5837
5846
  * ```ts
@@ -6524,17 +6533,17 @@ class Chat {
6524
6533
  return structuredClone(history);
6525
6534
  }
6526
6535
  processStreamResponse(streamResponse, inputContent) {
6527
- var _a, _b;
6528
6536
  return __asyncGenerator(this, arguments, function* processStreamResponse_1() {
6529
- var _c, e_1, _d, _e;
6537
+ var _a, e_1, _b, _c;
6538
+ var _d, _e;
6530
6539
  const outputContent = [];
6531
6540
  try {
6532
- 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) {
6533
- _e = streamResponse_1_1.value;
6541
+ 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) {
6542
+ _c = streamResponse_1_1.value;
6534
6543
  _f = false;
6535
- const chunk = _e;
6544
+ const chunk = _c;
6536
6545
  if (isValidResponse(chunk)) {
6537
- const content = (_b = (_a = chunk.candidates) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.content;
6546
+ const content = (_e = (_d = chunk.candidates) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.content;
6538
6547
  if (content !== undefined) {
6539
6548
  outputContent.push(content);
6540
6549
  }
@@ -6545,7 +6554,7 @@ class Chat {
6545
6554
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
6546
6555
  finally {
6547
6556
  try {
6548
- if (!_f && !_c && (_d = streamResponse_1.return)) yield __await(_d.call(streamResponse_1));
6557
+ if (!_f && !_a && (_b = streamResponse_1.return)) yield __await(_b.call(streamResponse_1));
6549
6558
  }
6550
6559
  finally { if (e_1) throw e_1.error; }
6551
6560
  }
@@ -6582,1150 +6591,880 @@ class Chat {
6582
6591
  * Copyright 2025 Google LLC
6583
6592
  * SPDX-License-Identifier: Apache-2.0
6584
6593
  */
6585
- /**
6586
- * API errors raised by the GenAI API.
6587
- */
6588
- class ApiError extends Error {
6589
- constructor(options) {
6590
- super(options.message);
6591
- this.name = 'ApiError';
6592
- this.status = options.status;
6593
- Object.setPrototypeOf(this, ApiError.prototype);
6594
+ // Code generated by the Google Gen AI SDK generator DO NOT EDIT.
6595
+ function createFileSearchStoreConfigToMldev(fromObject, parentObject) {
6596
+ const toObject = {};
6597
+ const fromDisplayName = getValueByPath(fromObject, ['displayName']);
6598
+ if (parentObject !== undefined && fromDisplayName != null) {
6599
+ setValueByPath(parentObject, ['displayName'], fromDisplayName);
6594
6600
  }
6601
+ return toObject;
6595
6602
  }
6596
-
6597
- /**
6598
- * @license
6599
- * Copyright 2025 Google LLC
6600
- * SPDX-License-Identifier: Apache-2.0
6601
- */
6602
- const CONTENT_TYPE_HEADER = 'Content-Type';
6603
- const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';
6604
- const USER_AGENT_HEADER = 'User-Agent';
6605
- const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';
6606
- const SDK_VERSION = '1.30.0'; // x-release-please-version
6607
- const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;
6608
- const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';
6609
- const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';
6610
- const responseLineRE = /^\s*data: (.*)(?:\n\n|\r\r|\r\n\r\n)/;
6611
- /**
6612
- * The ApiClient class is used to send requests to the Gemini API or Vertex AI
6613
- * endpoints.
6614
- */
6615
- class ApiClient {
6616
- constructor(opts) {
6617
- var _a, _b;
6618
- this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai });
6619
- const initHttpOptions = {};
6620
- if (this.clientOptions.vertexai) {
6621
- initHttpOptions.apiVersion =
6622
- (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 ? _a : VERTEX_AI_API_DEFAULT_VERSION;
6623
- initHttpOptions.baseUrl = this.baseUrlFromProjectLocation();
6624
- this.normalizeAuthParameters();
6625
- }
6626
- else {
6627
- // Gemini API
6628
- initHttpOptions.apiVersion =
6629
- (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : GOOGLE_AI_API_DEFAULT_VERSION;
6630
- initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;
6631
- }
6632
- initHttpOptions.headers = this.getDefaultHeaders();
6633
- this.clientOptions.httpOptions = initHttpOptions;
6634
- if (opts.httpOptions) {
6635
- this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions);
6636
- }
6637
- }
6638
- /**
6639
- * Determines the base URL for Vertex AI based on project and location.
6640
- * Uses the global endpoint if location is 'global' or if project/location
6641
- * are not specified (implying API key usage).
6642
- * @private
6643
- */
6644
- baseUrlFromProjectLocation() {
6645
- if (this.clientOptions.project &&
6646
- this.clientOptions.location &&
6647
- this.clientOptions.location !== 'global') {
6648
- // Regional endpoint
6649
- return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;
6650
- }
6651
- // Global endpoint (covers 'global' location and API key usage)
6652
- return `https://aiplatform.googleapis.com/`;
6653
- }
6654
- /**
6655
- * Normalizes authentication parameters for Vertex AI.
6656
- * If project and location are provided, API key is cleared.
6657
- * If project and location are not provided (implying API key usage),
6658
- * project and location are cleared.
6659
- * @private
6660
- */
6661
- normalizeAuthParameters() {
6662
- if (this.clientOptions.project && this.clientOptions.location) {
6663
- // Using project/location for auth, clear potential API key
6664
- this.clientOptions.apiKey = undefined;
6665
- return;
6666
- }
6667
- // Using API key for auth (or no auth provided yet), clear project/location
6668
- this.clientOptions.project = undefined;
6669
- this.clientOptions.location = undefined;
6603
+ function createFileSearchStoreParametersToMldev(fromObject) {
6604
+ const toObject = {};
6605
+ const fromConfig = getValueByPath(fromObject, ['config']);
6606
+ if (fromConfig != null) {
6607
+ createFileSearchStoreConfigToMldev(fromConfig, toObject);
6670
6608
  }
6671
- isVertexAI() {
6672
- var _a;
6673
- return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 ? _a : false;
6609
+ return toObject;
6610
+ }
6611
+ function deleteFileSearchStoreConfigToMldev(fromObject, parentObject) {
6612
+ const toObject = {};
6613
+ const fromForce = getValueByPath(fromObject, ['force']);
6614
+ if (parentObject !== undefined && fromForce != null) {
6615
+ setValueByPath(parentObject, ['_query', 'force'], fromForce);
6674
6616
  }
6675
- getProject() {
6676
- return this.clientOptions.project;
6617
+ return toObject;
6618
+ }
6619
+ function deleteFileSearchStoreParametersToMldev(fromObject) {
6620
+ const toObject = {};
6621
+ const fromName = getValueByPath(fromObject, ['name']);
6622
+ if (fromName != null) {
6623
+ setValueByPath(toObject, ['_url', 'name'], fromName);
6677
6624
  }
6678
- getLocation() {
6679
- return this.clientOptions.location;
6625
+ const fromConfig = getValueByPath(fromObject, ['config']);
6626
+ if (fromConfig != null) {
6627
+ deleteFileSearchStoreConfigToMldev(fromConfig, toObject);
6680
6628
  }
6681
- getApiVersion() {
6682
- if (this.clientOptions.httpOptions &&
6683
- this.clientOptions.httpOptions.apiVersion !== undefined) {
6684
- return this.clientOptions.httpOptions.apiVersion;
6685
- }
6686
- throw new Error('API version is not set.');
6629
+ return toObject;
6630
+ }
6631
+ function getFileSearchStoreParametersToMldev(fromObject) {
6632
+ const toObject = {};
6633
+ const fromName = getValueByPath(fromObject, ['name']);
6634
+ if (fromName != null) {
6635
+ setValueByPath(toObject, ['_url', 'name'], fromName);
6687
6636
  }
6688
- getBaseUrl() {
6689
- if (this.clientOptions.httpOptions &&
6690
- this.clientOptions.httpOptions.baseUrl !== undefined) {
6691
- return this.clientOptions.httpOptions.baseUrl;
6637
+ return toObject;
6638
+ }
6639
+ function importFileConfigToMldev(fromObject, parentObject) {
6640
+ const toObject = {};
6641
+ const fromCustomMetadata = getValueByPath(fromObject, [
6642
+ 'customMetadata',
6643
+ ]);
6644
+ if (parentObject !== undefined && fromCustomMetadata != null) {
6645
+ let transformedList = fromCustomMetadata;
6646
+ if (Array.isArray(transformedList)) {
6647
+ transformedList = transformedList.map((item) => {
6648
+ return item;
6649
+ });
6692
6650
  }
6693
- throw new Error('Base URL is not set.');
6651
+ setValueByPath(parentObject, ['customMetadata'], transformedList);
6694
6652
  }
6695
- getRequestUrl() {
6696
- return this.getRequestUrlInternal(this.clientOptions.httpOptions);
6653
+ const fromChunkingConfig = getValueByPath(fromObject, [
6654
+ 'chunkingConfig',
6655
+ ]);
6656
+ if (parentObject !== undefined && fromChunkingConfig != null) {
6657
+ setValueByPath(parentObject, ['chunkingConfig'], fromChunkingConfig);
6697
6658
  }
6698
- getHeaders() {
6699
- if (this.clientOptions.httpOptions &&
6700
- this.clientOptions.httpOptions.headers !== undefined) {
6701
- return this.clientOptions.httpOptions.headers;
6702
- }
6703
- else {
6704
- throw new Error('Headers are not set.');
6705
- }
6659
+ return toObject;
6660
+ }
6661
+ function importFileOperationFromMldev(fromObject) {
6662
+ const toObject = {};
6663
+ const fromName = getValueByPath(fromObject, ['name']);
6664
+ if (fromName != null) {
6665
+ setValueByPath(toObject, ['name'], fromName);
6706
6666
  }
6707
- getRequestUrlInternal(httpOptions) {
6708
- if (!httpOptions ||
6709
- httpOptions.baseUrl === undefined ||
6710
- httpOptions.apiVersion === undefined) {
6711
- throw new Error('HTTP options are not correctly set.');
6712
- }
6713
- const baseUrl = httpOptions.baseUrl.endsWith('/')
6714
- ? httpOptions.baseUrl.slice(0, -1)
6715
- : httpOptions.baseUrl;
6716
- const urlElement = [baseUrl];
6717
- if (httpOptions.apiVersion && httpOptions.apiVersion !== '') {
6718
- urlElement.push(httpOptions.apiVersion);
6719
- }
6720
- return urlElement.join('/');
6667
+ const fromMetadata = getValueByPath(fromObject, ['metadata']);
6668
+ if (fromMetadata != null) {
6669
+ setValueByPath(toObject, ['metadata'], fromMetadata);
6721
6670
  }
6722
- getBaseResourcePath() {
6723
- return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`;
6671
+ const fromDone = getValueByPath(fromObject, ['done']);
6672
+ if (fromDone != null) {
6673
+ setValueByPath(toObject, ['done'], fromDone);
6724
6674
  }
6725
- getApiKey() {
6726
- return this.clientOptions.apiKey;
6675
+ const fromError = getValueByPath(fromObject, ['error']);
6676
+ if (fromError != null) {
6677
+ setValueByPath(toObject, ['error'], fromError);
6727
6678
  }
6728
- getWebsocketBaseUrl() {
6729
- const baseUrl = this.getBaseUrl();
6730
- const urlParts = new URL(baseUrl);
6731
- urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss';
6732
- return urlParts.toString();
6679
+ const fromResponse = getValueByPath(fromObject, ['response']);
6680
+ if (fromResponse != null) {
6681
+ setValueByPath(toObject, ['response'], importFileResponseFromMldev(fromResponse));
6733
6682
  }
6734
- setBaseUrl(url) {
6735
- if (this.clientOptions.httpOptions) {
6736
- this.clientOptions.httpOptions.baseUrl = url;
6737
- }
6738
- else {
6739
- throw new Error('HTTP options are not correctly set.');
6740
- }
6683
+ return toObject;
6684
+ }
6685
+ function importFileParametersToMldev(fromObject) {
6686
+ const toObject = {};
6687
+ const fromFileSearchStoreName = getValueByPath(fromObject, [
6688
+ 'fileSearchStoreName',
6689
+ ]);
6690
+ if (fromFileSearchStoreName != null) {
6691
+ setValueByPath(toObject, ['_url', 'file_search_store_name'], fromFileSearchStoreName);
6741
6692
  }
6742
- constructUrl(path, httpOptions, prependProjectLocation) {
6743
- const urlElement = [this.getRequestUrlInternal(httpOptions)];
6744
- if (prependProjectLocation) {
6745
- urlElement.push(this.getBaseResourcePath());
6746
- }
6747
- if (path !== '') {
6748
- urlElement.push(path);
6749
- }
6750
- const url = new URL(`${urlElement.join('/')}`);
6751
- return url;
6752
- }
6753
- shouldPrependVertexProjectPath(request) {
6754
- if (this.clientOptions.apiKey) {
6755
- return false;
6756
- }
6757
- if (!this.clientOptions.vertexai) {
6758
- return false;
6759
- }
6760
- if (request.path.startsWith('projects/')) {
6761
- // Assume the path already starts with
6762
- // `projects/<project>/location/<location>`.
6763
- return false;
6764
- }
6765
- if (request.httpMethod === 'GET' &&
6766
- request.path.startsWith('publishers/google/models')) {
6767
- // These paths are used by Vertex's models.get and models.list
6768
- // calls. For base models Vertex does not accept a project/location
6769
- // prefix (for tuned model the prefix is required).
6770
- return false;
6771
- }
6772
- return true;
6693
+ const fromFileName = getValueByPath(fromObject, ['fileName']);
6694
+ if (fromFileName != null) {
6695
+ setValueByPath(toObject, ['fileName'], fromFileName);
6773
6696
  }
6774
- async request(request) {
6775
- let patchedHttpOptions = this.clientOptions.httpOptions;
6776
- if (request.httpOptions) {
6777
- patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions);
6778
- }
6779
- const prependProjectLocation = this.shouldPrependVertexProjectPath(request);
6780
- const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation);
6781
- if (request.queryParams) {
6782
- for (const [key, value] of Object.entries(request.queryParams)) {
6783
- url.searchParams.append(key, String(value));
6784
- }
6785
- }
6786
- let requestInit = {};
6787
- if (request.httpMethod === 'GET') {
6788
- if (request.body && request.body !== '{}') {
6789
- throw new Error('Request body should be empty for GET request, but got non empty request body');
6790
- }
6791
- }
6792
- else {
6793
- requestInit.body = request.body;
6794
- }
6795
- requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, url.toString(), request.abortSignal);
6796
- return this.unaryApiCall(url, requestInit, request.httpMethod);
6697
+ const fromConfig = getValueByPath(fromObject, ['config']);
6698
+ if (fromConfig != null) {
6699
+ importFileConfigToMldev(fromConfig, toObject);
6797
6700
  }
6798
- patchHttpOptions(baseHttpOptions, requestHttpOptions) {
6799
- const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions));
6800
- for (const [key, value] of Object.entries(requestHttpOptions)) {
6801
- // Records compile to objects.
6802
- if (typeof value === 'object') {
6803
- // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type
6804
- // because expression of type 'string' can't be used to index type
6805
- // 'HttpOptions'.
6806
- patchedHttpOptions[key] = Object.assign(Object.assign({}, patchedHttpOptions[key]), value);
6807
- }
6808
- else if (value !== undefined) {
6809
- // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type
6810
- // because expression of type 'string' can't be used to index type
6811
- // 'HttpOptions'.
6812
- patchedHttpOptions[key] = value;
6813
- }
6814
- }
6815
- return patchedHttpOptions;
6701
+ return toObject;
6702
+ }
6703
+ function importFileResponseFromMldev(fromObject) {
6704
+ const toObject = {};
6705
+ const fromSdkHttpResponse = getValueByPath(fromObject, [
6706
+ 'sdkHttpResponse',
6707
+ ]);
6708
+ if (fromSdkHttpResponse != null) {
6709
+ setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);
6816
6710
  }
6817
- async requestStream(request) {
6818
- let patchedHttpOptions = this.clientOptions.httpOptions;
6819
- if (request.httpOptions) {
6820
- patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions);
6821
- }
6822
- const prependProjectLocation = this.shouldPrependVertexProjectPath(request);
6823
- const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation);
6824
- if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') {
6825
- url.searchParams.set('alt', 'sse');
6826
- }
6827
- let requestInit = {};
6828
- requestInit.body = request.body;
6829
- requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, url.toString(), request.abortSignal);
6830
- return this.streamApiCall(url, requestInit, request.httpMethod);
6711
+ const fromParent = getValueByPath(fromObject, ['parent']);
6712
+ if (fromParent != null) {
6713
+ setValueByPath(toObject, ['parent'], fromParent);
6831
6714
  }
6832
- async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, url, abortSignal) {
6833
- if ((httpOptions && httpOptions.timeout) || abortSignal) {
6834
- const abortController = new AbortController();
6835
- const signal = abortController.signal;
6836
- if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) {
6837
- const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout);
6838
- if (timeoutHandle &&
6839
- typeof timeoutHandle.unref ===
6840
- 'function') {
6841
- // call unref to prevent nodejs process from hanging, see
6842
- // https://nodejs.org/api/timers.html#timeoutunref
6843
- timeoutHandle.unref();
6844
- }
6845
- }
6846
- if (abortSignal) {
6847
- abortSignal.addEventListener('abort', () => {
6848
- abortController.abort();
6849
- });
6850
- }
6851
- requestInit.signal = signal;
6852
- }
6853
- if (httpOptions && httpOptions.extraBody !== null) {
6854
- includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody);
6855
- }
6856
- requestInit.headers = await this.getHeadersInternal(httpOptions, url);
6857
- return requestInit;
6715
+ const fromDocumentName = getValueByPath(fromObject, ['documentName']);
6716
+ if (fromDocumentName != null) {
6717
+ setValueByPath(toObject, ['documentName'], fromDocumentName);
6858
6718
  }
6859
- async unaryApiCall(url, requestInit, httpMethod) {
6860
- return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod }))
6861
- .then(async (response) => {
6862
- await throwErrorIfNotOK(response);
6863
- return new HttpResponse(response);
6864
- })
6865
- .catch((e) => {
6866
- if (e instanceof Error) {
6867
- throw e;
6868
- }
6869
- else {
6870
- throw new Error(JSON.stringify(e));
6871
- }
6872
- });
6719
+ return toObject;
6720
+ }
6721
+ function listFileSearchStoresConfigToMldev(fromObject, parentObject) {
6722
+ const toObject = {};
6723
+ const fromPageSize = getValueByPath(fromObject, ['pageSize']);
6724
+ if (parentObject !== undefined && fromPageSize != null) {
6725
+ setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);
6873
6726
  }
6874
- async streamApiCall(url, requestInit, httpMethod) {
6875
- return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod }))
6876
- .then(async (response) => {
6877
- await throwErrorIfNotOK(response);
6878
- return this.processStreamResponse(response);
6879
- })
6880
- .catch((e) => {
6881
- if (e instanceof Error) {
6882
- throw e;
6883
- }
6884
- else {
6885
- throw new Error(JSON.stringify(e));
6886
- }
6887
- });
6727
+ const fromPageToken = getValueByPath(fromObject, ['pageToken']);
6728
+ if (parentObject !== undefined && fromPageToken != null) {
6729
+ setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);
6888
6730
  }
6889
- processStreamResponse(response) {
6890
- var _a;
6891
- return __asyncGenerator(this, arguments, function* processStreamResponse_1() {
6892
- const reader = (_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.getReader();
6893
- const decoder = new TextDecoder('utf-8');
6894
- if (!reader) {
6895
- throw new Error('Response body is empty');
6896
- }
6897
- try {
6898
- let buffer = '';
6899
- while (true) {
6900
- const { done, value } = yield __await(reader.read());
6901
- if (done) {
6902
- if (buffer.trim().length > 0) {
6903
- throw new Error('Incomplete JSON segment at the end');
6904
- }
6905
- break;
6906
- }
6907
- const chunkString = decoder.decode(value, { stream: true });
6908
- // Parse and throw an error if the chunk contains an error.
6909
- try {
6910
- const chunkJson = JSON.parse(chunkString);
6911
- if ('error' in chunkJson) {
6912
- const errorJson = JSON.parse(JSON.stringify(chunkJson['error']));
6913
- const status = errorJson['status'];
6914
- const code = errorJson['code'];
6915
- const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`;
6916
- if (code >= 400 && code < 600) {
6917
- const apiError = new ApiError({
6918
- message: errorMessage,
6919
- status: code,
6920
- });
6921
- throw apiError;
6922
- }
6923
- }
6924
- }
6925
- catch (e) {
6926
- const error = e;
6927
- if (error.name === 'ApiError') {
6928
- throw e;
6929
- }
6930
- }
6931
- buffer += chunkString;
6932
- let match = buffer.match(responseLineRE);
6933
- while (match) {
6934
- const processedChunkString = match[1];
6935
- try {
6936
- const partialResponse = new Response(processedChunkString, {
6937
- headers: response === null || response === void 0 ? void 0 : response.headers,
6938
- status: response === null || response === void 0 ? void 0 : response.status,
6939
- statusText: response === null || response === void 0 ? void 0 : response.statusText,
6940
- });
6941
- yield yield __await(new HttpResponse(partialResponse));
6942
- buffer = buffer.slice(match[0].length);
6943
- match = buffer.match(responseLineRE);
6944
- }
6945
- catch (e) {
6946
- throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`);
6947
- }
6948
- }
6949
- }
6950
- }
6951
- finally {
6952
- reader.releaseLock();
6953
- }
6954
- });
6731
+ return toObject;
6732
+ }
6733
+ function listFileSearchStoresParametersToMldev(fromObject) {
6734
+ const toObject = {};
6735
+ const fromConfig = getValueByPath(fromObject, ['config']);
6736
+ if (fromConfig != null) {
6737
+ listFileSearchStoresConfigToMldev(fromConfig, toObject);
6955
6738
  }
6956
- async apiCall(url, requestInit) {
6957
- return fetch(url, requestInit).catch((e) => {
6958
- throw new Error(`exception ${e} sending request`);
6959
- });
6739
+ return toObject;
6740
+ }
6741
+ function listFileSearchStoresResponseFromMldev(fromObject) {
6742
+ const toObject = {};
6743
+ const fromSdkHttpResponse = getValueByPath(fromObject, [
6744
+ 'sdkHttpResponse',
6745
+ ]);
6746
+ if (fromSdkHttpResponse != null) {
6747
+ setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);
6960
6748
  }
6961
- getDefaultHeaders() {
6962
- const headers = {};
6963
- const versionHeaderValue = LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra;
6964
- headers[USER_AGENT_HEADER] = versionHeaderValue;
6965
- headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;
6966
- headers[CONTENT_TYPE_HEADER] = 'application/json';
6967
- return headers;
6749
+ const fromNextPageToken = getValueByPath(fromObject, [
6750
+ 'nextPageToken',
6751
+ ]);
6752
+ if (fromNextPageToken != null) {
6753
+ setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);
6968
6754
  }
6969
- async getHeadersInternal(httpOptions, url) {
6970
- const headers = new Headers();
6971
- if (httpOptions && httpOptions.headers) {
6972
- for (const [key, value] of Object.entries(httpOptions.headers)) {
6973
- headers.append(key, value);
6974
- }
6975
- // Append a timeout header if it is set, note that the timeout option is
6976
- // in milliseconds but the header is in seconds.
6977
- if (httpOptions.timeout && httpOptions.timeout > 0) {
6978
- headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1000)));
6979
- }
6755
+ const fromFileSearchStores = getValueByPath(fromObject, [
6756
+ 'fileSearchStores',
6757
+ ]);
6758
+ if (fromFileSearchStores != null) {
6759
+ let transformedList = fromFileSearchStores;
6760
+ if (Array.isArray(transformedList)) {
6761
+ transformedList = transformedList.map((item) => {
6762
+ return item;
6763
+ });
6980
6764
  }
6981
- await this.clientOptions.auth.addAuthHeaders(headers, url);
6982
- return headers;
6765
+ setValueByPath(toObject, ['fileSearchStores'], transformedList);
6983
6766
  }
6984
- getFileName(file) {
6985
- var _a;
6986
- let fileName = '';
6987
- if (typeof file === 'string') {
6988
- fileName = file.replace(/[/\\]+$/, '');
6989
- fileName = (_a = fileName.split(/[/\\]/).pop()) !== null && _a !== void 0 ? _a : '';
6767
+ return toObject;
6768
+ }
6769
+ function uploadToFileSearchStoreConfigToMldev(fromObject, parentObject) {
6770
+ const toObject = {};
6771
+ const fromMimeType = getValueByPath(fromObject, ['mimeType']);
6772
+ if (parentObject !== undefined && fromMimeType != null) {
6773
+ setValueByPath(parentObject, ['mimeType'], fromMimeType);
6774
+ }
6775
+ const fromDisplayName = getValueByPath(fromObject, ['displayName']);
6776
+ if (parentObject !== undefined && fromDisplayName != null) {
6777
+ setValueByPath(parentObject, ['displayName'], fromDisplayName);
6778
+ }
6779
+ const fromCustomMetadata = getValueByPath(fromObject, [
6780
+ 'customMetadata',
6781
+ ]);
6782
+ if (parentObject !== undefined && fromCustomMetadata != null) {
6783
+ let transformedList = fromCustomMetadata;
6784
+ if (Array.isArray(transformedList)) {
6785
+ transformedList = transformedList.map((item) => {
6786
+ return item;
6787
+ });
6990
6788
  }
6991
- return fileName;
6789
+ setValueByPath(parentObject, ['customMetadata'], transformedList);
6992
6790
  }
6993
- /**
6994
- * Uploads a file asynchronously using Gemini API only, this is not supported
6995
- * in Vertex AI.
6996
- *
6997
- * @param file The string path to the file to be uploaded or a Blob object.
6998
- * @param config Optional parameters specified in the `UploadFileConfig`
6999
- * interface. @see {@link types.UploadFileConfig}
7000
- * @return A promise that resolves to a `File` object.
7001
- * @throws An error if called on a Vertex AI client.
7002
- * @throws An error if the `mimeType` is not provided and can not be inferred,
7003
- */
7004
- async uploadFile(file, config) {
7005
- var _a;
7006
- const fileToUpload = {};
7007
- if (config != null) {
7008
- fileToUpload.mimeType = config.mimeType;
7009
- fileToUpload.name = config.name;
7010
- fileToUpload.displayName = config.displayName;
6791
+ const fromChunkingConfig = getValueByPath(fromObject, [
6792
+ 'chunkingConfig',
6793
+ ]);
6794
+ if (parentObject !== undefined && fromChunkingConfig != null) {
6795
+ setValueByPath(parentObject, ['chunkingConfig'], fromChunkingConfig);
6796
+ }
6797
+ return toObject;
6798
+ }
6799
+ function uploadToFileSearchStoreParametersToMldev(fromObject) {
6800
+ const toObject = {};
6801
+ const fromFileSearchStoreName = getValueByPath(fromObject, [
6802
+ 'fileSearchStoreName',
6803
+ ]);
6804
+ if (fromFileSearchStoreName != null) {
6805
+ setValueByPath(toObject, ['_url', 'file_search_store_name'], fromFileSearchStoreName);
6806
+ }
6807
+ const fromConfig = getValueByPath(fromObject, ['config']);
6808
+ if (fromConfig != null) {
6809
+ uploadToFileSearchStoreConfigToMldev(fromConfig, toObject);
6810
+ }
6811
+ return toObject;
6812
+ }
6813
+ function uploadToFileSearchStoreResumableResponseFromMldev(fromObject) {
6814
+ const toObject = {};
6815
+ const fromSdkHttpResponse = getValueByPath(fromObject, [
6816
+ 'sdkHttpResponse',
6817
+ ]);
6818
+ if (fromSdkHttpResponse != null) {
6819
+ setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);
6820
+ }
6821
+ return toObject;
6822
+ }
6823
+
6824
+ /**
6825
+ * @license
6826
+ * Copyright 2025 Google LLC
6827
+ * SPDX-License-Identifier: Apache-2.0
6828
+ */
6829
+ /**
6830
+ * API errors raised by the GenAI API.
6831
+ */
6832
+ class ApiError extends Error {
6833
+ constructor(options) {
6834
+ super(options.message);
6835
+ this.name = 'ApiError';
6836
+ this.status = options.status;
6837
+ Object.setPrototypeOf(this, ApiError.prototype);
6838
+ }
6839
+ }
6840
+
6841
+ /**
6842
+ * @license
6843
+ * Copyright 2025 Google LLC
6844
+ * SPDX-License-Identifier: Apache-2.0
6845
+ */
6846
+ const CONTENT_TYPE_HEADER = 'Content-Type';
6847
+ const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';
6848
+ const USER_AGENT_HEADER = 'User-Agent';
6849
+ const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';
6850
+ const SDK_VERSION = '1.32.0'; // x-release-please-version
6851
+ const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;
6852
+ const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';
6853
+ const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';
6854
+ /**
6855
+ * The ApiClient class is used to send requests to the Gemini API or Vertex AI
6856
+ * endpoints.
6857
+ */
6858
+ class ApiClient {
6859
+ constructor(opts) {
6860
+ var _a, _b;
6861
+ this.clientOptions = Object.assign(Object.assign({}, opts), { project: opts.project, location: opts.location, apiKey: opts.apiKey, vertexai: opts.vertexai });
6862
+ const initHttpOptions = {};
6863
+ if (this.clientOptions.vertexai) {
6864
+ initHttpOptions.apiVersion =
6865
+ (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 ? _a : VERTEX_AI_API_DEFAULT_VERSION;
6866
+ initHttpOptions.baseUrl = this.baseUrlFromProjectLocation();
6867
+ this.normalizeAuthParameters();
7011
6868
  }
7012
- if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) {
7013
- fileToUpload.name = `files/${fileToUpload.name}`;
6869
+ else {
6870
+ // Gemini API
6871
+ initHttpOptions.apiVersion =
6872
+ (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 ? _b : GOOGLE_AI_API_DEFAULT_VERSION;
6873
+ initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;
7014
6874
  }
7015
- const uploader = this.clientOptions.uploader;
7016
- const fileStat = await uploader.stat(file);
7017
- fileToUpload.sizeBytes = String(fileStat.size);
7018
- const mimeType = (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a !== void 0 ? _a : fileStat.type;
7019
- if (mimeType === undefined || mimeType === '') {
7020
- throw new Error('Can not determine mimeType. Please provide mimeType in the config.');
6875
+ initHttpOptions.headers = this.getDefaultHeaders();
6876
+ this.clientOptions.httpOptions = initHttpOptions;
6877
+ if (opts.httpOptions) {
6878
+ this.clientOptions.httpOptions = this.patchHttpOptions(initHttpOptions, opts.httpOptions);
7021
6879
  }
7022
- fileToUpload.mimeType = mimeType;
7023
- const body = {
7024
- file: fileToUpload,
7025
- };
7026
- const fileName = this.getFileName(file);
7027
- const path = formatMap('upload/v1beta/files', body['_url']);
7028
- const uploadUrl = await this.fetchUploadUrl(path, fileToUpload.sizeBytes, fileToUpload.mimeType, fileName, body, config === null || config === void 0 ? void 0 : config.httpOptions);
7029
- return uploader.upload(file, uploadUrl, this);
7030
6880
  }
7031
6881
  /**
7032
- * Uploads a file to a given file search store asynchronously using Gemini API only, this is not supported
7033
- * in Vertex AI.
7034
- *
7035
- * @param fileSearchStoreName The name of the file search store to upload the file to.
7036
- * @param file The string path to the file to be uploaded or a Blob object.
7037
- * @param config Optional parameters specified in the `UploadFileConfig`
7038
- * interface. @see {@link UploadFileConfig}
7039
- * @return A promise that resolves to a `File` object.
7040
- * @throws An error if called on a Vertex AI client.
7041
- * @throws An error if the `mimeType` is not provided and can not be inferred,
6882
+ * Determines the base URL for Vertex AI based on project and location.
6883
+ * Uses the global endpoint if location is 'global' or if project/location
6884
+ * are not specified (implying API key usage).
6885
+ * @private
7042
6886
  */
7043
- async uploadFileToFileSearchStore(fileSearchStoreName, file, config) {
7044
- var _a;
7045
- const uploader = this.clientOptions.uploader;
7046
- const fileStat = await uploader.stat(file);
7047
- const sizeBytes = String(fileStat.size);
7048
- const mimeType = (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a !== void 0 ? _a : fileStat.type;
7049
- if (mimeType === undefined || mimeType === '') {
7050
- throw new Error('Can not determine mimeType. Please provide mimeType in the config.');
7051
- }
7052
- const path = `upload/v1beta/${fileSearchStoreName}:uploadToFileSearchStore`;
7053
- const fileName = this.getFileName(file);
7054
- const body = {};
7055
- if (config === null || config === void 0 ? void 0 : config.customMetadata) {
7056
- body['customMetadata'] = config.customMetadata;
7057
- }
7058
- if (config === null || config === void 0 ? void 0 : config.chunkingConfig) {
7059
- body['chunkingConfig'] = config.chunkingConfig;
6887
+ baseUrlFromProjectLocation() {
6888
+ if (this.clientOptions.project &&
6889
+ this.clientOptions.location &&
6890
+ this.clientOptions.location !== 'global') {
6891
+ // Regional endpoint
6892
+ return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;
7060
6893
  }
7061
- const uploadUrl = await this.fetchUploadUrl(path, sizeBytes, mimeType, fileName, body, config === null || config === void 0 ? void 0 : config.httpOptions);
7062
- return uploader.uploadToFileSearchStore(file, uploadUrl, this);
6894
+ // Global endpoint (covers 'global' location and API key usage)
6895
+ return `https://aiplatform.googleapis.com/`;
7063
6896
  }
7064
6897
  /**
7065
- * Downloads a file asynchronously to the specified path.
7066
- *
7067
- * @params params - The parameters for the download request, see {@link
7068
- * types.DownloadFileParameters}
6898
+ * Normalizes authentication parameters for Vertex AI.
6899
+ * If project and location are provided, API key is cleared.
6900
+ * If project and location are not provided (implying API key usage),
6901
+ * project and location are cleared.
6902
+ * @private
7069
6903
  */
7070
- async downloadFile(params) {
7071
- const downloader = this.clientOptions.downloader;
7072
- await downloader.download(params, this);
6904
+ normalizeAuthParameters() {
6905
+ if (this.clientOptions.project && this.clientOptions.location) {
6906
+ // Using project/location for auth, clear potential API key
6907
+ this.clientOptions.apiKey = undefined;
6908
+ return;
6909
+ }
6910
+ // Using API key for auth (or no auth provided yet), clear project/location
6911
+ this.clientOptions.project = undefined;
6912
+ this.clientOptions.location = undefined;
7073
6913
  }
7074
- async fetchUploadUrl(path, sizeBytes, mimeType, fileName, body, configHttpOptions) {
6914
+ isVertexAI() {
7075
6915
  var _a;
7076
- let httpOptions = {};
7077
- if (configHttpOptions) {
7078
- httpOptions = configHttpOptions;
7079
- }
7080
- else {
7081
- httpOptions = {
7082
- apiVersion: '',
7083
- 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 } : {})),
7084
- };
7085
- }
7086
- const httpResponse = await this.request({
7087
- path,
7088
- body: JSON.stringify(body),
7089
- httpMethod: 'POST',
7090
- httpOptions,
7091
- });
7092
- if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) {
7093
- throw new Error('Server did not return an HttpResponse or the returned HttpResponse did not have headers.');
6916
+ return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 ? _a : false;
6917
+ }
6918
+ getProject() {
6919
+ return this.clientOptions.project;
6920
+ }
6921
+ getLocation() {
6922
+ return this.clientOptions.location;
6923
+ }
6924
+ getApiVersion() {
6925
+ if (this.clientOptions.httpOptions &&
6926
+ this.clientOptions.httpOptions.apiVersion !== undefined) {
6927
+ return this.clientOptions.httpOptions.apiVersion;
7094
6928
  }
7095
- const uploadUrl = (_a = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-url'];
7096
- if (uploadUrl === undefined) {
7097
- throw new Error('Failed to get upload url. Server did not return the x-google-upload-url in the headers');
6929
+ throw new Error('API version is not set.');
6930
+ }
6931
+ getBaseUrl() {
6932
+ if (this.clientOptions.httpOptions &&
6933
+ this.clientOptions.httpOptions.baseUrl !== undefined) {
6934
+ return this.clientOptions.httpOptions.baseUrl;
7098
6935
  }
7099
- return uploadUrl;
6936
+ throw new Error('Base URL is not set.');
7100
6937
  }
7101
- }
7102
- async function throwErrorIfNotOK(response) {
7103
- var _a;
7104
- if (response === undefined) {
7105
- throw new Error('response is undefined');
6938
+ getRequestUrl() {
6939
+ return this.getRequestUrlInternal(this.clientOptions.httpOptions);
7106
6940
  }
7107
- if (!response.ok) {
7108
- const status = response.status;
7109
- let errorBody;
7110
- if ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json')) {
7111
- errorBody = await response.json();
6941
+ getHeaders() {
6942
+ if (this.clientOptions.httpOptions &&
6943
+ this.clientOptions.httpOptions.headers !== undefined) {
6944
+ return this.clientOptions.httpOptions.headers;
7112
6945
  }
7113
6946
  else {
7114
- errorBody = {
7115
- error: {
7116
- message: await response.text(),
7117
- code: response.status,
7118
- status: response.statusText,
7119
- },
7120
- };
7121
- }
7122
- const errorMessage = JSON.stringify(errorBody);
7123
- if (status >= 400 && status < 600) {
7124
- const apiError = new ApiError({
7125
- message: errorMessage,
7126
- status: status,
7127
- });
7128
- throw apiError;
6947
+ throw new Error('Headers are not set.');
7129
6948
  }
7130
- throw new Error(errorMessage);
7131
- }
7132
- }
7133
- /**
7134
- * Recursively updates the `requestInit.body` with values from an `extraBody` object.
7135
- *
7136
- * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed.
7137
- * The `extraBody` is then deeply merged into this parsed object.
7138
- * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged,
7139
- * as merging structured data into an opaque Blob is not supported.
7140
- *
7141
- * The function does not enforce that updated values from `extraBody` have the
7142
- * same type as existing values in `requestInit.body`. Type mismatches during
7143
- * the merge will result in a warning, but the value from `extraBody` will overwrite
7144
- * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure.
7145
- *
7146
- * @param requestInit The RequestInit object whose body will be updated.
7147
- * @param extraBody The object containing updates to be merged into `requestInit.body`.
7148
- */
7149
- function includeExtraBodyToRequestInit(requestInit, extraBody) {
7150
- if (!extraBody || Object.keys(extraBody).length === 0) {
7151
- return;
7152
- }
7153
- if (requestInit.body instanceof Blob) {
7154
- console.warn('includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.');
7155
- return;
7156
6949
  }
7157
- let currentBodyObject = {};
7158
- // If adding new type to HttpRequest.body, please check the code below to
7159
- // see if we need to update the logic.
7160
- if (typeof requestInit.body === 'string' && requestInit.body.length > 0) {
7161
- try {
7162
- const parsedBody = JSON.parse(requestInit.body);
7163
- if (typeof parsedBody === 'object' &&
7164
- parsedBody !== null &&
7165
- !Array.isArray(parsedBody)) {
7166
- currentBodyObject = parsedBody;
7167
- }
7168
- else {
7169
- console.warn('includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.');
7170
- return;
7171
- }
7172
- /* eslint-disable-next-line @typescript-eslint/no-unused-vars */
6950
+ getRequestUrlInternal(httpOptions) {
6951
+ if (!httpOptions ||
6952
+ httpOptions.baseUrl === undefined ||
6953
+ httpOptions.apiVersion === undefined) {
6954
+ throw new Error('HTTP options are not correctly set.');
7173
6955
  }
7174
- catch (e) {
7175
- console.warn('includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.');
7176
- return;
6956
+ const baseUrl = httpOptions.baseUrl.endsWith('/')
6957
+ ? httpOptions.baseUrl.slice(0, -1)
6958
+ : httpOptions.baseUrl;
6959
+ const urlElement = [baseUrl];
6960
+ if (httpOptions.apiVersion && httpOptions.apiVersion !== '') {
6961
+ urlElement.push(httpOptions.apiVersion);
7177
6962
  }
6963
+ return urlElement.join('/');
7178
6964
  }
7179
- function deepMerge(target, source) {
7180
- const output = Object.assign({}, target);
7181
- for (const key in source) {
7182
- if (Object.prototype.hasOwnProperty.call(source, key)) {
7183
- const sourceValue = source[key];
7184
- const targetValue = output[key];
7185
- if (sourceValue &&
7186
- typeof sourceValue === 'object' &&
7187
- !Array.isArray(sourceValue) &&
7188
- targetValue &&
7189
- typeof targetValue === 'object' &&
7190
- !Array.isArray(targetValue)) {
7191
- output[key] = deepMerge(targetValue, sourceValue);
7192
- }
7193
- else {
7194
- if (targetValue &&
7195
- sourceValue &&
7196
- typeof targetValue !== typeof sourceValue) {
7197
- console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`);
7198
- }
7199
- output[key] = sourceValue;
7200
- }
7201
- }
7202
- }
7203
- return output;
6965
+ getBaseResourcePath() {
6966
+ return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`;
7204
6967
  }
7205
- const mergedBody = deepMerge(currentBodyObject, extraBody);
7206
- requestInit.body = JSON.stringify(mergedBody);
7207
- }
7208
-
7209
- /**
7210
- * @license
7211
- * Copyright 2025 Google LLC
7212
- * SPDX-License-Identifier: Apache-2.0
7213
- */
7214
- function crossError() {
7215
- // TODO(b/399934880): this message needs a link to a help page explaining how to enable conditional exports
7216
- return new Error(`This feature requires the web or Node specific @google/genai implementation, you can fix this by either:
7217
-
7218
- *Enabling conditional exports for your project [recommended]*
7219
-
7220
- *Using a platform specific import* - Make sure your code imports either '@google/genai/web' or '@google/genai/node' instead of '@google/genai'.
7221
- `);
7222
- }
7223
-
7224
- /**
7225
- * @license
7226
- * Copyright 2025 Google LLC
7227
- * SPDX-License-Identifier: Apache-2.0
7228
- */
7229
- class CrossDownloader {
7230
- async download(_params, _apiClient) {
7231
- throw crossError();
6968
+ getApiKey() {
6969
+ return this.clientOptions.apiKey;
7232
6970
  }
7233
- }
7234
-
7235
- const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes
7236
- const MAX_RETRY_COUNT = 3;
7237
- const INITIAL_RETRY_DELAY_MS = 1000;
7238
- const DELAY_MULTIPLIER = 2;
7239
- const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status';
7240
- class CrossUploader {
7241
- async upload(file, uploadUrl, apiClient) {
7242
- if (typeof file === 'string') {
7243
- throw crossError();
6971
+ getWebsocketBaseUrl() {
6972
+ const baseUrl = this.getBaseUrl();
6973
+ const urlParts = new URL(baseUrl);
6974
+ urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss';
6975
+ return urlParts.toString();
6976
+ }
6977
+ setBaseUrl(url) {
6978
+ if (this.clientOptions.httpOptions) {
6979
+ this.clientOptions.httpOptions.baseUrl = url;
7244
6980
  }
7245
6981
  else {
7246
- return uploadBlob(file, uploadUrl, apiClient);
6982
+ throw new Error('HTTP options are not correctly set.');
7247
6983
  }
7248
6984
  }
7249
- async uploadToFileSearchStore(file, uploadUrl, apiClient) {
7250
- if (typeof file === 'string') {
7251
- throw crossError();
6985
+ constructUrl(path, httpOptions, prependProjectLocation) {
6986
+ const urlElement = [this.getRequestUrlInternal(httpOptions)];
6987
+ if (prependProjectLocation) {
6988
+ urlElement.push(this.getBaseResourcePath());
7252
6989
  }
7253
- else {
7254
- return uploadBlobToFileSearchStore(file, uploadUrl, apiClient);
6990
+ if (path !== '') {
6991
+ urlElement.push(path);
7255
6992
  }
6993
+ const url = new URL(`${urlElement.join('/')}`);
6994
+ return url;
7256
6995
  }
7257
- async stat(file) {
7258
- if (typeof file === 'string') {
7259
- throw crossError();
6996
+ shouldPrependVertexProjectPath(request) {
6997
+ if (this.clientOptions.apiKey) {
6998
+ return false;
7260
6999
  }
7261
- else {
7262
- return getBlobStat(file);
7000
+ if (!this.clientOptions.vertexai) {
7001
+ return false;
7263
7002
  }
7003
+ if (request.path.startsWith('projects/')) {
7004
+ // Assume the path already starts with
7005
+ // `projects/<project>/location/<location>`.
7006
+ return false;
7007
+ }
7008
+ if (request.httpMethod === 'GET' &&
7009
+ request.path.startsWith('publishers/google/models')) {
7010
+ // These paths are used by Vertex's models.get and models.list
7011
+ // calls. For base models Vertex does not accept a project/location
7012
+ // prefix (for tuned model the prefix is required).
7013
+ return false;
7014
+ }
7015
+ return true;
7264
7016
  }
7265
- }
7266
- async function uploadBlob(file, uploadUrl, apiClient) {
7267
- var _a;
7268
- const response = await uploadBlobInternal(file, uploadUrl, apiClient);
7269
- const responseJson = (await (response === null || response === void 0 ? void 0 : response.json()));
7270
- if (((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') {
7271
- throw new Error('Failed to upload file: Upload status is not finalized.');
7272
- }
7273
- return responseJson['file'];
7274
- }
7275
- async function uploadBlobToFileSearchStore(file, uploadUrl, apiClient) {
7276
- var _a;
7277
- const response = await uploadBlobInternal(file, uploadUrl, apiClient);
7278
- const responseJson = (await (response === null || response === void 0 ? void 0 : response.json()));
7279
- if (((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') {
7280
- throw new Error('Failed to upload file: Upload status is not finalized.');
7281
- }
7282
- const resp = uploadToFileSearchStoreOperationFromMldev(responseJson);
7283
- const typedResp = new UploadToFileSearchStoreOperation();
7284
- Object.assign(typedResp, resp);
7285
- return typedResp;
7286
- }
7287
- async function uploadBlobInternal(file, uploadUrl, apiClient) {
7288
- var _a, _b;
7289
- let fileSize = 0;
7290
- let offset = 0;
7291
- let response = new HttpResponse(new Response());
7292
- let uploadCommand = 'upload';
7293
- fileSize = file.size;
7294
- while (offset < fileSize) {
7295
- const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);
7296
- const chunk = file.slice(offset, offset + chunkSize);
7297
- if (offset + chunkSize >= fileSize) {
7298
- uploadCommand += ', finalize';
7017
+ async request(request) {
7018
+ let patchedHttpOptions = this.clientOptions.httpOptions;
7019
+ if (request.httpOptions) {
7020
+ patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions);
7299
7021
  }
7300
- let retryCount = 0;
7301
- let currentDelayMs = INITIAL_RETRY_DELAY_MS;
7302
- while (retryCount < MAX_RETRY_COUNT) {
7303
- response = await apiClient.request({
7304
- path: '',
7305
- body: chunk,
7306
- httpMethod: 'POST',
7307
- httpOptions: {
7308
- apiVersion: '',
7309
- baseUrl: uploadUrl,
7310
- headers: {
7311
- 'X-Goog-Upload-Command': uploadCommand,
7312
- 'X-Goog-Upload-Offset': String(offset),
7313
- 'Content-Length': String(chunkSize),
7314
- },
7315
- },
7316
- });
7317
- if ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {
7318
- break;
7022
+ const prependProjectLocation = this.shouldPrependVertexProjectPath(request);
7023
+ const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation);
7024
+ if (request.queryParams) {
7025
+ for (const [key, value] of Object.entries(request.queryParams)) {
7026
+ url.searchParams.append(key, String(value));
7319
7027
  }
7320
- retryCount++;
7321
- await sleep(currentDelayMs);
7322
- currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;
7323
7028
  }
7324
- offset += chunkSize;
7325
- // The `x-goog-upload-status` header field can be `active`, `final` and
7326
- //`cancelled` in resposne.
7327
- if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') {
7328
- break;
7029
+ let requestInit = {};
7030
+ if (request.httpMethod === 'GET') {
7031
+ if (request.body && request.body !== '{}') {
7032
+ throw new Error('Request body should be empty for GET request, but got non empty request body');
7033
+ }
7329
7034
  }
7330
- // TODO(b/401391430) Investigate why the upload status is not finalized
7331
- // even though all content has been uploaded.
7332
- if (fileSize <= offset) {
7333
- throw new Error('All content has been uploaded, but the upload status is not finalized.');
7035
+ else {
7036
+ requestInit.body = request.body;
7334
7037
  }
7038
+ requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, url.toString(), request.abortSignal);
7039
+ return this.unaryApiCall(url, requestInit, request.httpMethod);
7335
7040
  }
7336
- return response;
7337
- }
7338
- async function getBlobStat(file) {
7339
- const fileStat = { size: file.size, type: file.type };
7340
- return fileStat;
7341
- }
7342
- function sleep(ms) {
7343
- return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
7344
- }
7345
-
7346
- /**
7347
- * @license
7348
- * Copyright 2025 Google LLC
7349
- * SPDX-License-Identifier: Apache-2.0
7350
- */
7351
- class CrossWebSocketFactory {
7352
- create(_url, _headers, _callbacks) {
7353
- throw crossError();
7354
- }
7355
- }
7356
-
7357
- /**
7358
- * @license
7359
- * Copyright 2025 Google LLC
7360
- * SPDX-License-Identifier: Apache-2.0
7361
- */
7362
- // Code generated by the Google Gen AI SDK generator DO NOT EDIT.
7363
- function createFileParametersToMldev(fromObject) {
7364
- const toObject = {};
7365
- const fromFile = getValueByPath(fromObject, ['file']);
7366
- if (fromFile != null) {
7367
- setValueByPath(toObject, ['file'], fromFile);
7368
- }
7369
- return toObject;
7370
- }
7371
- function createFileResponseFromMldev(fromObject) {
7372
- const toObject = {};
7373
- const fromSdkHttpResponse = getValueByPath(fromObject, [
7374
- 'sdkHttpResponse',
7375
- ]);
7376
- if (fromSdkHttpResponse != null) {
7377
- setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);
7041
+ patchHttpOptions(baseHttpOptions, requestHttpOptions) {
7042
+ const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions));
7043
+ for (const [key, value] of Object.entries(requestHttpOptions)) {
7044
+ // Records compile to objects.
7045
+ if (typeof value === 'object') {
7046
+ // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type
7047
+ // because expression of type 'string' can't be used to index type
7048
+ // 'HttpOptions'.
7049
+ patchedHttpOptions[key] = Object.assign(Object.assign({}, patchedHttpOptions[key]), value);
7050
+ }
7051
+ else if (value !== undefined) {
7052
+ // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type
7053
+ // because expression of type 'string' can't be used to index type
7054
+ // 'HttpOptions'.
7055
+ patchedHttpOptions[key] = value;
7056
+ }
7057
+ }
7058
+ return patchedHttpOptions;
7378
7059
  }
7379
- return toObject;
7380
- }
7381
- function deleteFileParametersToMldev(fromObject) {
7382
- const toObject = {};
7383
- const fromName = getValueByPath(fromObject, ['name']);
7384
- if (fromName != null) {
7385
- setValueByPath(toObject, ['_url', 'file'], tFileName(fromName));
7060
+ async requestStream(request) {
7061
+ let patchedHttpOptions = this.clientOptions.httpOptions;
7062
+ if (request.httpOptions) {
7063
+ patchedHttpOptions = this.patchHttpOptions(this.clientOptions.httpOptions, request.httpOptions);
7064
+ }
7065
+ const prependProjectLocation = this.shouldPrependVertexProjectPath(request);
7066
+ const url = this.constructUrl(request.path, patchedHttpOptions, prependProjectLocation);
7067
+ if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') {
7068
+ url.searchParams.set('alt', 'sse');
7069
+ }
7070
+ let requestInit = {};
7071
+ requestInit.body = request.body;
7072
+ requestInit = await this.includeExtraHttpOptionsToRequestInit(requestInit, patchedHttpOptions, url.toString(), request.abortSignal);
7073
+ return this.streamApiCall(url, requestInit, request.httpMethod);
7386
7074
  }
7387
- return toObject;
7388
- }
7389
- function deleteFileResponseFromMldev(fromObject) {
7390
- const toObject = {};
7391
- const fromSdkHttpResponse = getValueByPath(fromObject, [
7392
- 'sdkHttpResponse',
7393
- ]);
7394
- if (fromSdkHttpResponse != null) {
7395
- setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);
7075
+ async includeExtraHttpOptionsToRequestInit(requestInit, httpOptions, url, abortSignal) {
7076
+ if ((httpOptions && httpOptions.timeout) || abortSignal) {
7077
+ const abortController = new AbortController();
7078
+ const signal = abortController.signal;
7079
+ if (httpOptions.timeout && (httpOptions === null || httpOptions === void 0 ? void 0 : httpOptions.timeout) > 0) {
7080
+ const timeoutHandle = setTimeout(() => abortController.abort(), httpOptions.timeout);
7081
+ if (timeoutHandle &&
7082
+ typeof timeoutHandle.unref ===
7083
+ 'function') {
7084
+ // call unref to prevent nodejs process from hanging, see
7085
+ // https://nodejs.org/api/timers.html#timeoutunref
7086
+ timeoutHandle.unref();
7087
+ }
7088
+ }
7089
+ if (abortSignal) {
7090
+ abortSignal.addEventListener('abort', () => {
7091
+ abortController.abort();
7092
+ });
7093
+ }
7094
+ requestInit.signal = signal;
7095
+ }
7096
+ if (httpOptions && httpOptions.extraBody !== null) {
7097
+ includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody);
7098
+ }
7099
+ requestInit.headers = await this.getHeadersInternal(httpOptions, url);
7100
+ return requestInit;
7396
7101
  }
7397
- return toObject;
7398
- }
7399
- function getFileParametersToMldev(fromObject) {
7400
- const toObject = {};
7401
- const fromName = getValueByPath(fromObject, ['name']);
7402
- if (fromName != null) {
7403
- setValueByPath(toObject, ['_url', 'file'], tFileName(fromName));
7102
+ async unaryApiCall(url, requestInit, httpMethod) {
7103
+ return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod }))
7104
+ .then(async (response) => {
7105
+ await throwErrorIfNotOK(response);
7106
+ return new HttpResponse(response);
7107
+ })
7108
+ .catch((e) => {
7109
+ if (e instanceof Error) {
7110
+ throw e;
7111
+ }
7112
+ else {
7113
+ throw new Error(JSON.stringify(e));
7114
+ }
7115
+ });
7404
7116
  }
7405
- return toObject;
7406
- }
7407
- function listFilesConfigToMldev(fromObject, parentObject) {
7408
- const toObject = {};
7409
- const fromPageSize = getValueByPath(fromObject, ['pageSize']);
7410
- if (parentObject !== undefined && fromPageSize != null) {
7411
- setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);
7117
+ async streamApiCall(url, requestInit, httpMethod) {
7118
+ return this.apiCall(url.toString(), Object.assign(Object.assign({}, requestInit), { method: httpMethod }))
7119
+ .then(async (response) => {
7120
+ await throwErrorIfNotOK(response);
7121
+ return this.processStreamResponse(response);
7122
+ })
7123
+ .catch((e) => {
7124
+ if (e instanceof Error) {
7125
+ throw e;
7126
+ }
7127
+ else {
7128
+ throw new Error(JSON.stringify(e));
7129
+ }
7130
+ });
7412
7131
  }
7413
- const fromPageToken = getValueByPath(fromObject, ['pageToken']);
7414
- if (parentObject !== undefined && fromPageToken != null) {
7415
- setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);
7132
+ processStreamResponse(response) {
7133
+ return __asyncGenerator(this, arguments, function* processStreamResponse_1() {
7134
+ var _a;
7135
+ const reader = (_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.getReader();
7136
+ const decoder = new TextDecoder('utf-8');
7137
+ if (!reader) {
7138
+ throw new Error('Response body is empty');
7139
+ }
7140
+ try {
7141
+ let buffer = '';
7142
+ const dataPrefix = 'data:';
7143
+ const delimiters = ['\n\n', '\r\r', '\r\n\r\n'];
7144
+ while (true) {
7145
+ const { done, value } = yield __await(reader.read());
7146
+ if (done) {
7147
+ if (buffer.trim().length > 0) {
7148
+ throw new Error('Incomplete JSON segment at the end');
7149
+ }
7150
+ break;
7151
+ }
7152
+ const chunkString = decoder.decode(value, { stream: true });
7153
+ // Parse and throw an error if the chunk contains an error.
7154
+ try {
7155
+ const chunkJson = JSON.parse(chunkString);
7156
+ if ('error' in chunkJson) {
7157
+ const errorJson = JSON.parse(JSON.stringify(chunkJson['error']));
7158
+ const status = errorJson['status'];
7159
+ const code = errorJson['code'];
7160
+ const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`;
7161
+ if (code >= 400 && code < 600) {
7162
+ const apiError = new ApiError({
7163
+ message: errorMessage,
7164
+ status: code,
7165
+ });
7166
+ throw apiError;
7167
+ }
7168
+ }
7169
+ }
7170
+ catch (e) {
7171
+ const error = e;
7172
+ if (error.name === 'ApiError') {
7173
+ throw e;
7174
+ }
7175
+ }
7176
+ buffer += chunkString;
7177
+ let delimiterIndex = -1;
7178
+ let delimiterLength = 0;
7179
+ while (true) {
7180
+ delimiterIndex = -1;
7181
+ delimiterLength = 0;
7182
+ for (const delimiter of delimiters) {
7183
+ const index = buffer.indexOf(delimiter);
7184
+ if (index !== -1 &&
7185
+ (delimiterIndex === -1 || index < delimiterIndex)) {
7186
+ delimiterIndex = index;
7187
+ delimiterLength = delimiter.length;
7188
+ }
7189
+ }
7190
+ if (delimiterIndex === -1) {
7191
+ break; // No complete event in buffer
7192
+ }
7193
+ const eventString = buffer.substring(0, delimiterIndex);
7194
+ buffer = buffer.substring(delimiterIndex + delimiterLength);
7195
+ const trimmedEvent = eventString.trim();
7196
+ if (trimmedEvent.startsWith(dataPrefix)) {
7197
+ const processedChunkString = trimmedEvent
7198
+ .substring(dataPrefix.length)
7199
+ .trim();
7200
+ try {
7201
+ const partialResponse = new Response(processedChunkString, {
7202
+ headers: response === null || response === void 0 ? void 0 : response.headers,
7203
+ status: response === null || response === void 0 ? void 0 : response.status,
7204
+ statusText: response === null || response === void 0 ? void 0 : response.statusText,
7205
+ });
7206
+ yield yield __await(new HttpResponse(partialResponse));
7207
+ }
7208
+ catch (e) {
7209
+ throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`);
7210
+ }
7211
+ }
7212
+ }
7213
+ }
7214
+ }
7215
+ finally {
7216
+ reader.releaseLock();
7217
+ }
7218
+ });
7416
7219
  }
7417
- return toObject;
7418
- }
7419
- function listFilesParametersToMldev(fromObject) {
7420
- const toObject = {};
7421
- const fromConfig = getValueByPath(fromObject, ['config']);
7422
- if (fromConfig != null) {
7423
- listFilesConfigToMldev(fromConfig, toObject);
7220
+ async apiCall(url, requestInit) {
7221
+ return fetch(url, requestInit).catch((e) => {
7222
+ throw new Error(`exception ${e} sending request`);
7223
+ });
7424
7224
  }
7425
- return toObject;
7426
- }
7427
- function listFilesResponseFromMldev(fromObject) {
7428
- const toObject = {};
7429
- const fromSdkHttpResponse = getValueByPath(fromObject, [
7430
- 'sdkHttpResponse',
7431
- ]);
7432
- if (fromSdkHttpResponse != null) {
7433
- setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);
7225
+ getDefaultHeaders() {
7226
+ const headers = {};
7227
+ const versionHeaderValue = LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra;
7228
+ headers[USER_AGENT_HEADER] = versionHeaderValue;
7229
+ headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;
7230
+ headers[CONTENT_TYPE_HEADER] = 'application/json';
7231
+ return headers;
7434
7232
  }
7435
- const fromNextPageToken = getValueByPath(fromObject, [
7436
- 'nextPageToken',
7437
- ]);
7438
- if (fromNextPageToken != null) {
7439
- setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);
7233
+ async getHeadersInternal(httpOptions, url) {
7234
+ const headers = new Headers();
7235
+ if (httpOptions && httpOptions.headers) {
7236
+ for (const [key, value] of Object.entries(httpOptions.headers)) {
7237
+ headers.append(key, value);
7238
+ }
7239
+ // Append a timeout header if it is set, note that the timeout option is
7240
+ // in milliseconds but the header is in seconds.
7241
+ if (httpOptions.timeout && httpOptions.timeout > 0) {
7242
+ headers.append(SERVER_TIMEOUT_HEADER, String(Math.ceil(httpOptions.timeout / 1000)));
7243
+ }
7244
+ }
7245
+ await this.clientOptions.auth.addAuthHeaders(headers, url);
7246
+ return headers;
7440
7247
  }
7441
- const fromFiles = getValueByPath(fromObject, ['files']);
7442
- if (fromFiles != null) {
7443
- let transformedList = fromFiles;
7444
- if (Array.isArray(transformedList)) {
7445
- transformedList = transformedList.map((item) => {
7446
- return item;
7447
- });
7248
+ getFileName(file) {
7249
+ var _a;
7250
+ let fileName = '';
7251
+ if (typeof file === 'string') {
7252
+ fileName = file.replace(/[/\\]+$/, '');
7253
+ fileName = (_a = fileName.split(/[/\\]/).pop()) !== null && _a !== void 0 ? _a : '';
7448
7254
  }
7449
- setValueByPath(toObject, ['files'], transformedList);
7255
+ return fileName;
7450
7256
  }
7451
- return toObject;
7452
- }
7453
-
7454
- /**
7455
- * @license
7456
- * Copyright 2025 Google LLC
7457
- * SPDX-License-Identifier: Apache-2.0
7458
- */
7459
- class Files extends BaseModule {
7460
- constructor(apiClient) {
7461
- super();
7462
- this.apiClient = apiClient;
7463
- /**
7464
- * Lists all current project files from the service.
7465
- *
7466
- * @param params - The parameters for the list request
7467
- * @return The paginated results of the list of files
7468
- *
7469
- * @example
7470
- * The following code prints the names of all files from the service, the
7471
- * size of each page is 10.
7472
- *
7473
- * ```ts
7474
- * const listResponse = await ai.files.list({config: {'pageSize': 10}});
7475
- * for await (const file of listResponse) {
7476
- * console.log(file.name);
7477
- * }
7478
- * ```
7479
- */
7480
- this.list = async (params = {}) => {
7481
- return new Pager(PagedItem.PAGED_ITEM_FILES, (x) => this.listInternal(x), await this.listInternal(params), params);
7257
+ /**
7258
+ * Uploads a file asynchronously using Gemini API only, this is not supported
7259
+ * in Vertex AI.
7260
+ *
7261
+ * @param file The string path to the file to be uploaded or a Blob object.
7262
+ * @param config Optional parameters specified in the `UploadFileConfig`
7263
+ * interface. @see {@link types.UploadFileConfig}
7264
+ * @return A promise that resolves to a `File` object.
7265
+ * @throws An error if called on a Vertex AI client.
7266
+ * @throws An error if the `mimeType` is not provided and can not be inferred,
7267
+ */
7268
+ async uploadFile(file, config) {
7269
+ var _a;
7270
+ const fileToUpload = {};
7271
+ if (config != null) {
7272
+ fileToUpload.mimeType = config.mimeType;
7273
+ fileToUpload.name = config.name;
7274
+ fileToUpload.displayName = config.displayName;
7275
+ }
7276
+ if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) {
7277
+ fileToUpload.name = `files/${fileToUpload.name}`;
7278
+ }
7279
+ const uploader = this.clientOptions.uploader;
7280
+ const fileStat = await uploader.stat(file);
7281
+ fileToUpload.sizeBytes = String(fileStat.size);
7282
+ const mimeType = (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a !== void 0 ? _a : fileStat.type;
7283
+ if (mimeType === undefined || mimeType === '') {
7284
+ throw new Error('Can not determine mimeType. Please provide mimeType in the config.');
7285
+ }
7286
+ fileToUpload.mimeType = mimeType;
7287
+ const body = {
7288
+ file: fileToUpload,
7482
7289
  };
7290
+ const fileName = this.getFileName(file);
7291
+ const path = formatMap('upload/v1beta/files', body['_url']);
7292
+ const uploadUrl = await this.fetchUploadUrl(path, fileToUpload.sizeBytes, fileToUpload.mimeType, fileName, body, config === null || config === void 0 ? void 0 : config.httpOptions);
7293
+ return uploader.upload(file, uploadUrl, this);
7483
7294
  }
7484
7295
  /**
7485
- * Uploads a file asynchronously to the Gemini API.
7486
- * This method is not available in Vertex AI.
7487
- * Supported upload sources:
7488
- * - Node.js: File path (string) or Blob object.
7489
- * - Browser: Blob object (e.g., File).
7490
- *
7491
- * @remarks
7492
- * The `mimeType` can be specified in the `config` parameter. If omitted:
7493
- * - For file path (string) inputs, the `mimeType` will be inferred from the
7494
- * file extension.
7495
- * - For Blob object inputs, the `mimeType` will be set to the Blob's `type`
7496
- * property.
7497
- * Somex eamples for file extension to mimeType mapping:
7498
- * .txt -> text/plain
7499
- * .json -> application/json
7500
- * .jpg -> image/jpeg
7501
- * .png -> image/png
7502
- * .mp3 -> audio/mpeg
7503
- * .mp4 -> video/mp4
7504
- *
7505
- * This section can contain multiple paragraphs and code examples.
7296
+ * Uploads a file to a given file search store asynchronously using Gemini API only, this is not supported
7297
+ * in Vertex AI.
7506
7298
  *
7507
- * @param params - Optional parameters specified in the
7508
- * `types.UploadFileParameters` interface.
7509
- * @see {@link types.UploadFileParameters#config} for the optional
7510
- * config in the parameters.
7511
- * @return A promise that resolves to a `types.File` object.
7299
+ * @param fileSearchStoreName The name of the file search store to upload the file to.
7300
+ * @param file The string path to the file to be uploaded or a Blob object.
7301
+ * @param config Optional parameters specified in the `UploadFileConfig`
7302
+ * interface. @see {@link UploadFileConfig}
7303
+ * @return A promise that resolves to a `File` object.
7512
7304
  * @throws An error if called on a Vertex AI client.
7513
7305
  * @throws An error if the `mimeType` is not provided and can not be inferred,
7514
- * the `mimeType` can be provided in the `params.config` parameter.
7515
- * @throws An error occurs if a suitable upload location cannot be established.
7516
- *
7517
- * @example
7518
- * The following code uploads a file to Gemini API.
7519
- *
7520
- * ```ts
7521
- * const file = await ai.files.upload({file: 'file.txt', config: {
7522
- * mimeType: 'text/plain',
7523
- * }});
7524
- * console.log(file.name);
7525
- * ```
7526
7306
  */
7527
- async upload(params) {
7528
- if (this.apiClient.isVertexAI()) {
7529
- throw new Error('Vertex AI does not support uploading files. You can share files through a GCS bucket.');
7307
+ async uploadFileToFileSearchStore(fileSearchStoreName, file, config) {
7308
+ var _a;
7309
+ const uploader = this.clientOptions.uploader;
7310
+ const fileStat = await uploader.stat(file);
7311
+ const sizeBytes = String(fileStat.size);
7312
+ const mimeType = (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== null && _a !== void 0 ? _a : fileStat.type;
7313
+ if (mimeType === undefined || mimeType === '') {
7314
+ throw new Error('Can not determine mimeType. Please provide mimeType in the config.');
7530
7315
  }
7531
- return this.apiClient
7532
- .uploadFile(params.file, params.config)
7533
- .then((resp) => {
7534
- return resp;
7535
- });
7316
+ const path = `upload/v1beta/${fileSearchStoreName}:uploadToFileSearchStore`;
7317
+ const fileName = this.getFileName(file);
7318
+ const body = {};
7319
+ if (config != null) {
7320
+ uploadToFileSearchStoreConfigToMldev(config, body);
7321
+ }
7322
+ const uploadUrl = await this.fetchUploadUrl(path, sizeBytes, mimeType, fileName, body, config === null || config === void 0 ? void 0 : config.httpOptions);
7323
+ return uploader.uploadToFileSearchStore(file, uploadUrl, this);
7536
7324
  }
7537
7325
  /**
7538
- * Downloads a remotely stored file asynchronously to a location specified in
7539
- * the `params` object. This method only works on Node environment, to
7540
- * download files in the browser, use a browser compliant method like an <a>
7541
- * tag.
7542
- *
7543
- * @param params - The parameters for the download request.
7544
- *
7545
- * @example
7546
- * The following code downloads an example file named "files/mehozpxf877d" as
7547
- * "file.txt".
7326
+ * Downloads a file asynchronously to the specified path.
7548
7327
  *
7549
- * ```ts
7550
- * await ai.files.download({file: file.name, downloadPath: 'file.txt'});
7551
- * ```
7328
+ * @params params - The parameters for the download request, see {@link
7329
+ * types.DownloadFileParameters}
7552
7330
  */
7553
- async download(params) {
7554
- await this.apiClient.downloadFile(params);
7331
+ async downloadFile(params) {
7332
+ const downloader = this.clientOptions.downloader;
7333
+ await downloader.download(params, this);
7555
7334
  }
7556
- async listInternal(params) {
7557
- var _a, _b;
7558
- let response;
7559
- let path = '';
7560
- let queryParams = {};
7561
- if (this.apiClient.isVertexAI()) {
7562
- throw new Error('This method is only supported by the Gemini Developer API.');
7335
+ async fetchUploadUrl(path, sizeBytes, mimeType, fileName, body, configHttpOptions) {
7336
+ var _a;
7337
+ let httpOptions = {};
7338
+ if (configHttpOptions) {
7339
+ httpOptions = configHttpOptions;
7563
7340
  }
7564
7341
  else {
7565
- const body = listFilesParametersToMldev(params);
7566
- path = formatMap('files', body['_url']);
7567
- queryParams = body['_query'];
7568
- delete body['_url'];
7569
- delete body['_query'];
7570
- response = this.apiClient
7571
- .request({
7572
- path: path,
7573
- queryParams: queryParams,
7574
- body: JSON.stringify(body),
7575
- httpMethod: 'GET',
7576
- httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
7577
- abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
7578
- })
7579
- .then((httpResponse) => {
7580
- return httpResponse.json().then((jsonResponse) => {
7581
- const response = jsonResponse;
7582
- response.sdkHttpResponse = {
7583
- headers: httpResponse.headers,
7584
- };
7585
- return response;
7586
- });
7587
- });
7588
- return response.then((apiResponse) => {
7589
- const resp = listFilesResponseFromMldev(apiResponse);
7590
- const typedResp = new ListFilesResponse();
7591
- Object.assign(typedResp, resp);
7592
- return typedResp;
7593
- });
7342
+ httpOptions = {
7343
+ apiVersion: '', // api-version is set in the path.
7344
+ 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 } : {})),
7345
+ };
7346
+ }
7347
+ const httpResponse = await this.request({
7348
+ path,
7349
+ body: JSON.stringify(body),
7350
+ httpMethod: 'POST',
7351
+ httpOptions,
7352
+ });
7353
+ if (!httpResponse || !(httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers)) {
7354
+ throw new Error('Server did not return an HttpResponse or the returned HttpResponse did not have headers.');
7355
+ }
7356
+ const uploadUrl = (_a = httpResponse === null || httpResponse === void 0 ? void 0 : httpResponse.headers) === null || _a === void 0 ? void 0 : _a['x-goog-upload-url'];
7357
+ if (uploadUrl === undefined) {
7358
+ throw new Error('Failed to get upload url. Server did not return the x-google-upload-url in the headers');
7594
7359
  }
7360
+ return uploadUrl;
7595
7361
  }
7596
- async createInternal(params) {
7597
- var _a, _b;
7598
- let response;
7599
- let path = '';
7600
- let queryParams = {};
7601
- if (this.apiClient.isVertexAI()) {
7602
- throw new Error('This method is only supported by the Gemini Developer API.');
7362
+ }
7363
+ async function throwErrorIfNotOK(response) {
7364
+ var _a;
7365
+ if (response === undefined) {
7366
+ throw new Error('response is undefined');
7367
+ }
7368
+ if (!response.ok) {
7369
+ const status = response.status;
7370
+ let errorBody;
7371
+ if ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.includes('application/json')) {
7372
+ errorBody = await response.json();
7603
7373
  }
7604
7374
  else {
7605
- const body = createFileParametersToMldev(params);
7606
- path = formatMap('upload/v1beta/files', body['_url']);
7607
- queryParams = body['_query'];
7608
- delete body['_url'];
7609
- delete body['_query'];
7610
- response = this.apiClient
7611
- .request({
7612
- path: path,
7613
- queryParams: queryParams,
7614
- body: JSON.stringify(body),
7615
- httpMethod: 'POST',
7616
- httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
7617
- abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
7618
- })
7619
- .then((httpResponse) => {
7620
- return httpResponse.json();
7621
- });
7622
- return response.then((apiResponse) => {
7623
- const resp = createFileResponseFromMldev(apiResponse);
7624
- const typedResp = new CreateFileResponse();
7625
- Object.assign(typedResp, resp);
7626
- return typedResp;
7375
+ errorBody = {
7376
+ error: {
7377
+ message: await response.text(),
7378
+ code: response.status,
7379
+ status: response.statusText,
7380
+ },
7381
+ };
7382
+ }
7383
+ const errorMessage = JSON.stringify(errorBody);
7384
+ if (status >= 400 && status < 600) {
7385
+ const apiError = new ApiError({
7386
+ message: errorMessage,
7387
+ status: status,
7627
7388
  });
7389
+ throw apiError;
7628
7390
  }
7391
+ throw new Error(errorMessage);
7629
7392
  }
7630
- /**
7631
- * Retrieves the file information from the service.
7632
- *
7633
- * @param params - The parameters for the get request
7634
- * @return The Promise that resolves to the types.File object requested.
7635
- *
7636
- * @example
7637
- * ```ts
7638
- * const config: GetFileParameters = {
7639
- * name: fileName,
7640
- * };
7641
- * file = await ai.files.get(config);
7642
- * console.log(file.name);
7643
- * ```
7644
- */
7645
- async get(params) {
7646
- var _a, _b;
7647
- let response;
7648
- let path = '';
7649
- let queryParams = {};
7650
- if (this.apiClient.isVertexAI()) {
7651
- throw new Error('This method is only supported by the Gemini Developer API.');
7393
+ }
7394
+ /**
7395
+ * Recursively updates the `requestInit.body` with values from an `extraBody` object.
7396
+ *
7397
+ * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed.
7398
+ * The `extraBody` is then deeply merged into this parsed object.
7399
+ * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged,
7400
+ * as merging structured data into an opaque Blob is not supported.
7401
+ *
7402
+ * The function does not enforce that updated values from `extraBody` have the
7403
+ * same type as existing values in `requestInit.body`. Type mismatches during
7404
+ * the merge will result in a warning, but the value from `extraBody` will overwrite
7405
+ * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure.
7406
+ *
7407
+ * @param requestInit The RequestInit object whose body will be updated.
7408
+ * @param extraBody The object containing updates to be merged into `requestInit.body`.
7409
+ */
7410
+ function includeExtraBodyToRequestInit(requestInit, extraBody) {
7411
+ if (!extraBody || Object.keys(extraBody).length === 0) {
7412
+ return;
7413
+ }
7414
+ if (requestInit.body instanceof Blob) {
7415
+ console.warn('includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.');
7416
+ return;
7417
+ }
7418
+ let currentBodyObject = {};
7419
+ // If adding new type to HttpRequest.body, please check the code below to
7420
+ // see if we need to update the logic.
7421
+ if (typeof requestInit.body === 'string' && requestInit.body.length > 0) {
7422
+ try {
7423
+ const parsedBody = JSON.parse(requestInit.body);
7424
+ if (typeof parsedBody === 'object' &&
7425
+ parsedBody !== null &&
7426
+ !Array.isArray(parsedBody)) {
7427
+ currentBodyObject = parsedBody;
7428
+ }
7429
+ else {
7430
+ console.warn('includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.');
7431
+ return;
7432
+ }
7433
+ /* eslint-disable-next-line @typescript-eslint/no-unused-vars */
7652
7434
  }
7653
- else {
7654
- const body = getFileParametersToMldev(params);
7655
- path = formatMap('files/{file}', body['_url']);
7656
- queryParams = body['_query'];
7657
- delete body['_url'];
7658
- delete body['_query'];
7659
- response = this.apiClient
7660
- .request({
7661
- path: path,
7662
- queryParams: queryParams,
7663
- body: JSON.stringify(body),
7664
- httpMethod: 'GET',
7665
- httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
7666
- abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
7667
- })
7668
- .then((httpResponse) => {
7669
- return httpResponse.json();
7670
- });
7671
- return response.then((resp) => {
7672
- return resp;
7673
- });
7435
+ catch (e) {
7436
+ console.warn('includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.');
7437
+ return;
7674
7438
  }
7675
7439
  }
7676
- /**
7677
- * Deletes a remotely stored file.
7678
- *
7679
- * @param params - The parameters for the delete request.
7680
- * @return The DeleteFileResponse, the response for the delete method.
7681
- *
7682
- * @example
7683
- * The following code deletes an example file named "files/mehozpxf877d".
7684
- *
7685
- * ```ts
7686
- * await ai.files.delete({name: file.name});
7687
- * ```
7688
- */
7689
- async delete(params) {
7690
- var _a, _b;
7691
- let response;
7692
- let path = '';
7693
- let queryParams = {};
7694
- if (this.apiClient.isVertexAI()) {
7695
- throw new Error('This method is only supported by the Gemini Developer API.');
7696
- }
7697
- else {
7698
- const body = deleteFileParametersToMldev(params);
7699
- path = formatMap('files/{file}', body['_url']);
7700
- queryParams = body['_query'];
7701
- delete body['_url'];
7702
- delete body['_query'];
7703
- response = this.apiClient
7704
- .request({
7705
- path: path,
7706
- queryParams: queryParams,
7707
- body: JSON.stringify(body),
7708
- httpMethod: 'DELETE',
7709
- httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
7710
- abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
7711
- })
7712
- .then((httpResponse) => {
7713
- return httpResponse.json().then((jsonResponse) => {
7714
- const response = jsonResponse;
7715
- response.sdkHttpResponse = {
7716
- headers: httpResponse.headers,
7717
- };
7718
- return response;
7719
- });
7720
- });
7721
- return response.then((apiResponse) => {
7722
- const resp = deleteFileResponseFromMldev(apiResponse);
7723
- const typedResp = new DeleteFileResponse();
7724
- Object.assign(typedResp, resp);
7725
- return typedResp;
7726
- });
7440
+ function deepMerge(target, source) {
7441
+ const output = Object.assign({}, target);
7442
+ for (const key in source) {
7443
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
7444
+ const sourceValue = source[key];
7445
+ const targetValue = output[key];
7446
+ if (sourceValue &&
7447
+ typeof sourceValue === 'object' &&
7448
+ !Array.isArray(sourceValue) &&
7449
+ targetValue &&
7450
+ typeof targetValue === 'object' &&
7451
+ !Array.isArray(targetValue)) {
7452
+ output[key] = deepMerge(targetValue, sourceValue);
7453
+ }
7454
+ else {
7455
+ if (targetValue &&
7456
+ sourceValue &&
7457
+ typeof targetValue !== typeof sourceValue) {
7458
+ console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`);
7459
+ }
7460
+ output[key] = sourceValue;
7461
+ }
7462
+ }
7727
7463
  }
7464
+ return output;
7728
7465
  }
7466
+ const mergedBody = deepMerge(currentBodyObject, extraBody);
7467
+ requestInit.body = JSON.stringify(mergedBody);
7729
7468
  }
7730
7469
 
7731
7470
  /**
@@ -7733,116 +7472,182 @@ class Files extends BaseModule {
7733
7472
  * Copyright 2025 Google LLC
7734
7473
  * SPDX-License-Identifier: Apache-2.0
7735
7474
  */
7736
- // Code generated by the Google Gen AI SDK generator DO NOT EDIT.
7737
- function createFileSearchStoreConfigToMldev(fromObject, parentObject) {
7738
- const toObject = {};
7739
- const fromDisplayName = getValueByPath(fromObject, ['displayName']);
7740
- if (parentObject !== undefined && fromDisplayName != null) {
7741
- setValueByPath(parentObject, ['displayName'], fromDisplayName);
7742
- }
7743
- return toObject;
7475
+ function crossError() {
7476
+ // TODO(b/399934880): this message needs a link to a help page explaining how to enable conditional exports
7477
+ return new Error(`This feature requires the web or Node specific @google/genai implementation, you can fix this by either:
7478
+
7479
+ *Enabling conditional exports for your project [recommended]*
7480
+
7481
+ *Using a platform specific import* - Make sure your code imports either '@google/genai/web' or '@google/genai/node' instead of '@google/genai'.
7482
+ `);
7744
7483
  }
7745
- function createFileSearchStoreParametersToMldev(fromObject) {
7746
- const toObject = {};
7747
- const fromConfig = getValueByPath(fromObject, ['config']);
7748
- if (fromConfig != null) {
7749
- createFileSearchStoreConfigToMldev(fromConfig, toObject);
7484
+
7485
+ /**
7486
+ * @license
7487
+ * Copyright 2025 Google LLC
7488
+ * SPDX-License-Identifier: Apache-2.0
7489
+ */
7490
+ class CrossDownloader {
7491
+ async download(_params, _apiClient) {
7492
+ throw crossError();
7750
7493
  }
7751
- return toObject;
7752
7494
  }
7753
- function deleteFileSearchStoreConfigToMldev(fromObject, parentObject) {
7754
- const toObject = {};
7755
- const fromForce = getValueByPath(fromObject, ['force']);
7756
- if (parentObject !== undefined && fromForce != null) {
7757
- setValueByPath(parentObject, ['_query', 'force'], fromForce);
7495
+
7496
+ const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes
7497
+ const MAX_RETRY_COUNT = 3;
7498
+ const INITIAL_RETRY_DELAY_MS = 1000;
7499
+ const DELAY_MULTIPLIER = 2;
7500
+ const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status';
7501
+ class CrossUploader {
7502
+ async upload(file, uploadUrl, apiClient) {
7503
+ if (typeof file === 'string') {
7504
+ throw crossError();
7505
+ }
7506
+ else {
7507
+ return uploadBlob(file, uploadUrl, apiClient);
7508
+ }
7758
7509
  }
7759
- return toObject;
7760
- }
7761
- function deleteFileSearchStoreParametersToMldev(fromObject) {
7762
- const toObject = {};
7763
- const fromName = getValueByPath(fromObject, ['name']);
7764
- if (fromName != null) {
7765
- setValueByPath(toObject, ['_url', 'name'], fromName);
7510
+ async uploadToFileSearchStore(file, uploadUrl, apiClient) {
7511
+ if (typeof file === 'string') {
7512
+ throw crossError();
7513
+ }
7514
+ else {
7515
+ return uploadBlobToFileSearchStore(file, uploadUrl, apiClient);
7516
+ }
7766
7517
  }
7767
- const fromConfig = getValueByPath(fromObject, ['config']);
7768
- if (fromConfig != null) {
7769
- deleteFileSearchStoreConfigToMldev(fromConfig, toObject);
7518
+ async stat(file) {
7519
+ if (typeof file === 'string') {
7520
+ throw crossError();
7521
+ }
7522
+ else {
7523
+ return getBlobStat(file);
7524
+ }
7770
7525
  }
7771
- return toObject;
7772
7526
  }
7773
- function getFileSearchStoreParametersToMldev(fromObject) {
7774
- const toObject = {};
7775
- const fromName = getValueByPath(fromObject, ['name']);
7776
- if (fromName != null) {
7777
- setValueByPath(toObject, ['_url', 'name'], fromName);
7527
+ async function uploadBlob(file, uploadUrl, apiClient) {
7528
+ var _a;
7529
+ const response = await uploadBlobInternal(file, uploadUrl, apiClient);
7530
+ const responseJson = (await (response === null || response === void 0 ? void 0 : response.json()));
7531
+ if (((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') {
7532
+ throw new Error('Failed to upload file: Upload status is not finalized.');
7778
7533
  }
7779
- return toObject;
7534
+ return responseJson['file'];
7780
7535
  }
7781
- function importFileConfigToMldev(fromObject, parentObject) {
7782
- const toObject = {};
7783
- const fromCustomMetadata = getValueByPath(fromObject, [
7784
- 'customMetadata',
7785
- ]);
7786
- if (parentObject !== undefined && fromCustomMetadata != null) {
7787
- let transformedList = fromCustomMetadata;
7788
- if (Array.isArray(transformedList)) {
7789
- transformedList = transformedList.map((item) => {
7790
- return item;
7536
+ async function uploadBlobToFileSearchStore(file, uploadUrl, apiClient) {
7537
+ var _a;
7538
+ const response = await uploadBlobInternal(file, uploadUrl, apiClient);
7539
+ const responseJson = (await (response === null || response === void 0 ? void 0 : response.json()));
7540
+ if (((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'final') {
7541
+ throw new Error('Failed to upload file: Upload status is not finalized.');
7542
+ }
7543
+ const resp = uploadToFileSearchStoreOperationFromMldev(responseJson);
7544
+ const typedResp = new UploadToFileSearchStoreOperation();
7545
+ Object.assign(typedResp, resp);
7546
+ return typedResp;
7547
+ }
7548
+ async function uploadBlobInternal(file, uploadUrl, apiClient) {
7549
+ var _a, _b;
7550
+ let fileSize = 0;
7551
+ let offset = 0;
7552
+ let response = new HttpResponse(new Response());
7553
+ let uploadCommand = 'upload';
7554
+ fileSize = file.size;
7555
+ while (offset < fileSize) {
7556
+ const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);
7557
+ const chunk = file.slice(offset, offset + chunkSize);
7558
+ if (offset + chunkSize >= fileSize) {
7559
+ uploadCommand += ', finalize';
7560
+ }
7561
+ let retryCount = 0;
7562
+ let currentDelayMs = INITIAL_RETRY_DELAY_MS;
7563
+ while (retryCount < MAX_RETRY_COUNT) {
7564
+ response = await apiClient.request({
7565
+ path: '',
7566
+ body: chunk,
7567
+ httpMethod: 'POST',
7568
+ httpOptions: {
7569
+ apiVersion: '',
7570
+ baseUrl: uploadUrl,
7571
+ headers: {
7572
+ 'X-Goog-Upload-Command': uploadCommand,
7573
+ 'X-Goog-Upload-Offset': String(offset),
7574
+ 'Content-Length': String(chunkSize),
7575
+ },
7576
+ },
7791
7577
  });
7578
+ if ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {
7579
+ break;
7580
+ }
7581
+ retryCount++;
7582
+ await sleep(currentDelayMs);
7583
+ currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;
7584
+ }
7585
+ offset += chunkSize;
7586
+ // The `x-goog-upload-status` header field can be `active`, `final` and
7587
+ //`cancelled` in resposne.
7588
+ if (((_b = response === null || response === void 0 ? void 0 : response.headers) === null || _b === void 0 ? void 0 : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== 'active') {
7589
+ break;
7590
+ }
7591
+ // TODO(b/401391430) Investigate why the upload status is not finalized
7592
+ // even though all content has been uploaded.
7593
+ if (fileSize <= offset) {
7594
+ throw new Error('All content has been uploaded, but the upload status is not finalized.');
7792
7595
  }
7793
- setValueByPath(parentObject, ['customMetadata'], transformedList);
7794
7596
  }
7795
- const fromChunkingConfig = getValueByPath(fromObject, [
7796
- 'chunkingConfig',
7797
- ]);
7798
- if (parentObject !== undefined && fromChunkingConfig != null) {
7799
- setValueByPath(parentObject, ['chunkingConfig'], fromChunkingConfig);
7597
+ return response;
7598
+ }
7599
+ async function getBlobStat(file) {
7600
+ const fileStat = { size: file.size, type: file.type };
7601
+ return fileStat;
7602
+ }
7603
+ function sleep(ms) {
7604
+ return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
7605
+ }
7606
+
7607
+ /**
7608
+ * @license
7609
+ * Copyright 2025 Google LLC
7610
+ * SPDX-License-Identifier: Apache-2.0
7611
+ */
7612
+ class CrossWebSocketFactory {
7613
+ create(_url, _headers, _callbacks) {
7614
+ throw crossError();
7800
7615
  }
7801
- return toObject;
7802
7616
  }
7803
- function importFileOperationFromMldev(fromObject) {
7617
+
7618
+ /**
7619
+ * @license
7620
+ * Copyright 2025 Google LLC
7621
+ * SPDX-License-Identifier: Apache-2.0
7622
+ */
7623
+ // Code generated by the Google Gen AI SDK generator DO NOT EDIT.
7624
+ function createFileParametersToMldev(fromObject) {
7804
7625
  const toObject = {};
7805
- const fromName = getValueByPath(fromObject, ['name']);
7806
- if (fromName != null) {
7807
- setValueByPath(toObject, ['name'], fromName);
7808
- }
7809
- const fromMetadata = getValueByPath(fromObject, ['metadata']);
7810
- if (fromMetadata != null) {
7811
- setValueByPath(toObject, ['metadata'], fromMetadata);
7812
- }
7813
- const fromDone = getValueByPath(fromObject, ['done']);
7814
- if (fromDone != null) {
7815
- setValueByPath(toObject, ['done'], fromDone);
7816
- }
7817
- const fromError = getValueByPath(fromObject, ['error']);
7818
- if (fromError != null) {
7819
- setValueByPath(toObject, ['error'], fromError);
7820
- }
7821
- const fromResponse = getValueByPath(fromObject, ['response']);
7822
- if (fromResponse != null) {
7823
- setValueByPath(toObject, ['response'], importFileResponseFromMldev(fromResponse));
7626
+ const fromFile = getValueByPath(fromObject, ['file']);
7627
+ if (fromFile != null) {
7628
+ setValueByPath(toObject, ['file'], fromFile);
7824
7629
  }
7825
7630
  return toObject;
7826
7631
  }
7827
- function importFileParametersToMldev(fromObject) {
7632
+ function createFileResponseFromMldev(fromObject) {
7828
7633
  const toObject = {};
7829
- const fromFileSearchStoreName = getValueByPath(fromObject, [
7830
- 'fileSearchStoreName',
7634
+ const fromSdkHttpResponse = getValueByPath(fromObject, [
7635
+ 'sdkHttpResponse',
7831
7636
  ]);
7832
- if (fromFileSearchStoreName != null) {
7833
- setValueByPath(toObject, ['_url', 'file_search_store_name'], fromFileSearchStoreName);
7834
- }
7835
- const fromFileName = getValueByPath(fromObject, ['fileName']);
7836
- if (fromFileName != null) {
7837
- setValueByPath(toObject, ['fileName'], fromFileName);
7637
+ if (fromSdkHttpResponse != null) {
7638
+ setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);
7838
7639
  }
7839
- const fromConfig = getValueByPath(fromObject, ['config']);
7840
- if (fromConfig != null) {
7841
- importFileConfigToMldev(fromConfig, toObject);
7640
+ return toObject;
7641
+ }
7642
+ function deleteFileParametersToMldev(fromObject) {
7643
+ const toObject = {};
7644
+ const fromName = getValueByPath(fromObject, ['name']);
7645
+ if (fromName != null) {
7646
+ setValueByPath(toObject, ['_url', 'file'], tFileName(fromName));
7842
7647
  }
7843
7648
  return toObject;
7844
7649
  }
7845
- function importFileResponseFromMldev(fromObject) {
7650
+ function deleteFileResponseFromMldev(fromObject) {
7846
7651
  const toObject = {};
7847
7652
  const fromSdkHttpResponse = getValueByPath(fromObject, [
7848
7653
  'sdkHttpResponse',
@@ -7850,17 +7655,17 @@ function importFileResponseFromMldev(fromObject) {
7850
7655
  if (fromSdkHttpResponse != null) {
7851
7656
  setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);
7852
7657
  }
7853
- const fromParent = getValueByPath(fromObject, ['parent']);
7854
- if (fromParent != null) {
7855
- setValueByPath(toObject, ['parent'], fromParent);
7856
- }
7857
- const fromDocumentName = getValueByPath(fromObject, ['documentName']);
7858
- if (fromDocumentName != null) {
7859
- setValueByPath(toObject, ['documentName'], fromDocumentName);
7658
+ return toObject;
7659
+ }
7660
+ function getFileParametersToMldev(fromObject) {
7661
+ const toObject = {};
7662
+ const fromName = getValueByPath(fromObject, ['name']);
7663
+ if (fromName != null) {
7664
+ setValueByPath(toObject, ['_url', 'file'], tFileName(fromName));
7860
7665
  }
7861
7666
  return toObject;
7862
7667
  }
7863
- function listFileSearchStoresConfigToMldev(fromObject, parentObject) {
7668
+ function listFilesConfigToMldev(fromObject, parentObject) {
7864
7669
  const toObject = {};
7865
7670
  const fromPageSize = getValueByPath(fromObject, ['pageSize']);
7866
7671
  if (parentObject !== undefined && fromPageSize != null) {
@@ -7872,15 +7677,15 @@ function listFileSearchStoresConfigToMldev(fromObject, parentObject) {
7872
7677
  }
7873
7678
  return toObject;
7874
7679
  }
7875
- function listFileSearchStoresParametersToMldev(fromObject) {
7680
+ function listFilesParametersToMldev(fromObject) {
7876
7681
  const toObject = {};
7877
7682
  const fromConfig = getValueByPath(fromObject, ['config']);
7878
7683
  if (fromConfig != null) {
7879
- listFileSearchStoresConfigToMldev(fromConfig, toObject);
7684
+ listFilesConfigToMldev(fromConfig, toObject);
7880
7685
  }
7881
7686
  return toObject;
7882
7687
  }
7883
- function listFileSearchStoresResponseFromMldev(fromObject) {
7688
+ function listFilesResponseFromMldev(fromObject) {
7884
7689
  const toObject = {};
7885
7690
  const fromSdkHttpResponse = getValueByPath(fromObject, [
7886
7691
  'sdkHttpResponse',
@@ -7894,73 +7699,291 @@ function listFileSearchStoresResponseFromMldev(fromObject) {
7894
7699
  if (fromNextPageToken != null) {
7895
7700
  setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);
7896
7701
  }
7897
- const fromFileSearchStores = getValueByPath(fromObject, [
7898
- 'fileSearchStores',
7899
- ]);
7900
- if (fromFileSearchStores != null) {
7901
- let transformedList = fromFileSearchStores;
7702
+ const fromFiles = getValueByPath(fromObject, ['files']);
7703
+ if (fromFiles != null) {
7704
+ let transformedList = fromFiles;
7902
7705
  if (Array.isArray(transformedList)) {
7903
7706
  transformedList = transformedList.map((item) => {
7904
7707
  return item;
7905
7708
  });
7906
7709
  }
7907
- setValueByPath(toObject, ['fileSearchStores'], transformedList);
7908
- }
7909
- return toObject;
7910
- }
7911
- function uploadToFileSearchStoreConfigToMldev(fromObject, parentObject) {
7912
- const toObject = {};
7913
- const fromMimeType = getValueByPath(fromObject, ['mimeType']);
7914
- if (parentObject !== undefined && fromMimeType != null) {
7915
- setValueByPath(parentObject, ['mimeType'], fromMimeType);
7916
- }
7917
- const fromDisplayName = getValueByPath(fromObject, ['displayName']);
7918
- if (parentObject !== undefined && fromDisplayName != null) {
7919
- setValueByPath(parentObject, ['displayName'], fromDisplayName);
7710
+ setValueByPath(toObject, ['files'], transformedList);
7711
+ }
7712
+ return toObject;
7713
+ }
7714
+
7715
+ /**
7716
+ * @license
7717
+ * Copyright 2025 Google LLC
7718
+ * SPDX-License-Identifier: Apache-2.0
7719
+ */
7720
+ class Files extends BaseModule {
7721
+ constructor(apiClient) {
7722
+ super();
7723
+ this.apiClient = apiClient;
7724
+ /**
7725
+ * Lists files.
7726
+ *
7727
+ * @param params - The parameters for the list request.
7728
+ * @return - A pager of files.
7729
+ *
7730
+ * @example
7731
+ * ```ts
7732
+ * const files = await ai.files.list({config: {'pageSize': 2}});
7733
+ * for await (const file of files) {
7734
+ * console.log(file);
7735
+ * }
7736
+ * ```
7737
+ */
7738
+ this.list = async (params = {}) => {
7739
+ return new Pager(PagedItem.PAGED_ITEM_FILES, (x) => this.listInternal(x), await this.listInternal(params), params);
7740
+ };
7741
+ }
7742
+ /**
7743
+ * Uploads a file asynchronously to the Gemini API.
7744
+ * This method is not available in Vertex AI.
7745
+ * Supported upload sources:
7746
+ * - Node.js: File path (string) or Blob object.
7747
+ * - Browser: Blob object (e.g., File).
7748
+ *
7749
+ * @remarks
7750
+ * The `mimeType` can be specified in the `config` parameter. If omitted:
7751
+ * - For file path (string) inputs, the `mimeType` will be inferred from the
7752
+ * file extension.
7753
+ * - For Blob object inputs, the `mimeType` will be set to the Blob's `type`
7754
+ * property.
7755
+ * Somex eamples for file extension to mimeType mapping:
7756
+ * .txt -> text/plain
7757
+ * .json -> application/json
7758
+ * .jpg -> image/jpeg
7759
+ * .png -> image/png
7760
+ * .mp3 -> audio/mpeg
7761
+ * .mp4 -> video/mp4
7762
+ *
7763
+ * This section can contain multiple paragraphs and code examples.
7764
+ *
7765
+ * @param params - Optional parameters specified in the
7766
+ * `types.UploadFileParameters` interface.
7767
+ * @see {@link types.UploadFileParameters#config} for the optional
7768
+ * config in the parameters.
7769
+ * @return A promise that resolves to a `types.File` object.
7770
+ * @throws An error if called on a Vertex AI client.
7771
+ * @throws An error if the `mimeType` is not provided and can not be inferred,
7772
+ * the `mimeType` can be provided in the `params.config` parameter.
7773
+ * @throws An error occurs if a suitable upload location cannot be established.
7774
+ *
7775
+ * @example
7776
+ * The following code uploads a file to Gemini API.
7777
+ *
7778
+ * ```ts
7779
+ * const file = await ai.files.upload({file: 'file.txt', config: {
7780
+ * mimeType: 'text/plain',
7781
+ * }});
7782
+ * console.log(file.name);
7783
+ * ```
7784
+ */
7785
+ async upload(params) {
7786
+ if (this.apiClient.isVertexAI()) {
7787
+ throw new Error('Vertex AI does not support uploading files. You can share files through a GCS bucket.');
7788
+ }
7789
+ return this.apiClient
7790
+ .uploadFile(params.file, params.config)
7791
+ .then((resp) => {
7792
+ return resp;
7793
+ });
7794
+ }
7795
+ /**
7796
+ * Downloads a remotely stored file asynchronously to a location specified in
7797
+ * the `params` object. This method only works on Node environment, to
7798
+ * download files in the browser, use a browser compliant method like an <a>
7799
+ * tag.
7800
+ *
7801
+ * @param params - The parameters for the download request.
7802
+ *
7803
+ * @example
7804
+ * The following code downloads an example file named "files/mehozpxf877d" as
7805
+ * "file.txt".
7806
+ *
7807
+ * ```ts
7808
+ * await ai.files.download({file: file.name, downloadPath: 'file.txt'});
7809
+ * ```
7810
+ */
7811
+ async download(params) {
7812
+ await this.apiClient.downloadFile(params);
7813
+ }
7814
+ async listInternal(params) {
7815
+ var _a, _b;
7816
+ let response;
7817
+ let path = '';
7818
+ let queryParams = {};
7819
+ if (this.apiClient.isVertexAI()) {
7820
+ throw new Error('This method is only supported by the Gemini Developer API.');
7821
+ }
7822
+ else {
7823
+ const body = listFilesParametersToMldev(params);
7824
+ path = formatMap('files', body['_url']);
7825
+ queryParams = body['_query'];
7826
+ delete body['_url'];
7827
+ delete body['_query'];
7828
+ response = this.apiClient
7829
+ .request({
7830
+ path: path,
7831
+ queryParams: queryParams,
7832
+ body: JSON.stringify(body),
7833
+ httpMethod: 'GET',
7834
+ httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
7835
+ abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
7836
+ })
7837
+ .then((httpResponse) => {
7838
+ return httpResponse.json().then((jsonResponse) => {
7839
+ const response = jsonResponse;
7840
+ response.sdkHttpResponse = {
7841
+ headers: httpResponse.headers,
7842
+ };
7843
+ return response;
7844
+ });
7845
+ });
7846
+ return response.then((apiResponse) => {
7847
+ const resp = listFilesResponseFromMldev(apiResponse);
7848
+ const typedResp = new ListFilesResponse();
7849
+ Object.assign(typedResp, resp);
7850
+ return typedResp;
7851
+ });
7852
+ }
7853
+ }
7854
+ async createInternal(params) {
7855
+ var _a, _b;
7856
+ let response;
7857
+ let path = '';
7858
+ let queryParams = {};
7859
+ if (this.apiClient.isVertexAI()) {
7860
+ throw new Error('This method is only supported by the Gemini Developer API.');
7861
+ }
7862
+ else {
7863
+ const body = createFileParametersToMldev(params);
7864
+ path = formatMap('upload/v1beta/files', body['_url']);
7865
+ queryParams = body['_query'];
7866
+ delete body['_url'];
7867
+ delete body['_query'];
7868
+ response = this.apiClient
7869
+ .request({
7870
+ path: path,
7871
+ queryParams: queryParams,
7872
+ body: JSON.stringify(body),
7873
+ httpMethod: 'POST',
7874
+ httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
7875
+ abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
7876
+ })
7877
+ .then((httpResponse) => {
7878
+ return httpResponse.json();
7879
+ });
7880
+ return response.then((apiResponse) => {
7881
+ const resp = createFileResponseFromMldev(apiResponse);
7882
+ const typedResp = new CreateFileResponse();
7883
+ Object.assign(typedResp, resp);
7884
+ return typedResp;
7885
+ });
7886
+ }
7920
7887
  }
7921
- const fromCustomMetadata = getValueByPath(fromObject, [
7922
- 'customMetadata',
7923
- ]);
7924
- if (parentObject !== undefined && fromCustomMetadata != null) {
7925
- let transformedList = fromCustomMetadata;
7926
- if (Array.isArray(transformedList)) {
7927
- transformedList = transformedList.map((item) => {
7928
- return item;
7888
+ /**
7889
+ * Retrieves the file information from the service.
7890
+ *
7891
+ * @param params - The parameters for the get request
7892
+ * @return The Promise that resolves to the types.File object requested.
7893
+ *
7894
+ * @example
7895
+ * ```ts
7896
+ * const config: GetFileParameters = {
7897
+ * name: fileName,
7898
+ * };
7899
+ * file = await ai.files.get(config);
7900
+ * console.log(file.name);
7901
+ * ```
7902
+ */
7903
+ async get(params) {
7904
+ var _a, _b;
7905
+ let response;
7906
+ let path = '';
7907
+ let queryParams = {};
7908
+ if (this.apiClient.isVertexAI()) {
7909
+ throw new Error('This method is only supported by the Gemini Developer API.');
7910
+ }
7911
+ else {
7912
+ const body = getFileParametersToMldev(params);
7913
+ path = formatMap('files/{file}', body['_url']);
7914
+ queryParams = body['_query'];
7915
+ delete body['_url'];
7916
+ delete body['_query'];
7917
+ response = this.apiClient
7918
+ .request({
7919
+ path: path,
7920
+ queryParams: queryParams,
7921
+ body: JSON.stringify(body),
7922
+ httpMethod: 'GET',
7923
+ httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
7924
+ abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
7925
+ })
7926
+ .then((httpResponse) => {
7927
+ return httpResponse.json();
7928
+ });
7929
+ return response.then((resp) => {
7930
+ return resp;
7929
7931
  });
7930
7932
  }
7931
- setValueByPath(parentObject, ['customMetadata'], transformedList);
7932
- }
7933
- const fromChunkingConfig = getValueByPath(fromObject, [
7934
- 'chunkingConfig',
7935
- ]);
7936
- if (parentObject !== undefined && fromChunkingConfig != null) {
7937
- setValueByPath(parentObject, ['chunkingConfig'], fromChunkingConfig);
7938
- }
7939
- return toObject;
7940
- }
7941
- function uploadToFileSearchStoreParametersToMldev(fromObject) {
7942
- const toObject = {};
7943
- const fromFileSearchStoreName = getValueByPath(fromObject, [
7944
- 'fileSearchStoreName',
7945
- ]);
7946
- if (fromFileSearchStoreName != null) {
7947
- setValueByPath(toObject, ['_url', 'file_search_store_name'], fromFileSearchStoreName);
7948
- }
7949
- const fromConfig = getValueByPath(fromObject, ['config']);
7950
- if (fromConfig != null) {
7951
- uploadToFileSearchStoreConfigToMldev(fromConfig, toObject);
7952
7933
  }
7953
- return toObject;
7954
- }
7955
- function uploadToFileSearchStoreResumableResponseFromMldev(fromObject) {
7956
- const toObject = {};
7957
- const fromSdkHttpResponse = getValueByPath(fromObject, [
7958
- 'sdkHttpResponse',
7959
- ]);
7960
- if (fromSdkHttpResponse != null) {
7961
- setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);
7934
+ /**
7935
+ * Deletes a remotely stored file.
7936
+ *
7937
+ * @param params - The parameters for the delete request.
7938
+ * @return The DeleteFileResponse, the response for the delete method.
7939
+ *
7940
+ * @example
7941
+ * The following code deletes an example file named "files/mehozpxf877d".
7942
+ *
7943
+ * ```ts
7944
+ * await ai.files.delete({name: file.name});
7945
+ * ```
7946
+ */
7947
+ async delete(params) {
7948
+ var _a, _b;
7949
+ let response;
7950
+ let path = '';
7951
+ let queryParams = {};
7952
+ if (this.apiClient.isVertexAI()) {
7953
+ throw new Error('This method is only supported by the Gemini Developer API.');
7954
+ }
7955
+ else {
7956
+ const body = deleteFileParametersToMldev(params);
7957
+ path = formatMap('files/{file}', body['_url']);
7958
+ queryParams = body['_query'];
7959
+ delete body['_url'];
7960
+ delete body['_query'];
7961
+ response = this.apiClient
7962
+ .request({
7963
+ path: path,
7964
+ queryParams: queryParams,
7965
+ body: JSON.stringify(body),
7966
+ httpMethod: 'DELETE',
7967
+ httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
7968
+ abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
7969
+ })
7970
+ .then((httpResponse) => {
7971
+ return httpResponse.json().then((jsonResponse) => {
7972
+ const response = jsonResponse;
7973
+ response.sdkHttpResponse = {
7974
+ headers: httpResponse.headers,
7975
+ };
7976
+ return response;
7977
+ });
7978
+ });
7979
+ return response.then((apiResponse) => {
7980
+ const resp = deleteFileResponseFromMldev(apiResponse);
7981
+ const typedResp = new DeleteFileResponse();
7982
+ Object.assign(typedResp, resp);
7983
+ return typedResp;
7984
+ });
7985
+ }
7962
7986
  }
7963
- return toObject;
7964
7987
  }
7965
7988
 
7966
7989
  /**
@@ -8065,17 +8088,14 @@ class Documents extends BaseModule {
8065
8088
  *
8066
8089
  * @example
8067
8090
  * ```ts
8068
- * const documents = await ai.documents.list({config: {'pageSize': 2}});
8091
+ * const documents = await ai.documents.list({parent:'rag_store_name', config: {'pageSize': 2}});
8069
8092
  * for await (const document of documents) {
8070
8093
  * console.log(document);
8071
8094
  * }
8072
8095
  * ```
8073
8096
  */
8074
8097
  this.list = async (params) => {
8075
- return new Pager(PagedItem.PAGED_ITEM_DOCUMENTS, (x) => this.listInternal({
8076
- parent: params.parent,
8077
- config: x.config,
8078
- }), await this.listInternal(params), params);
8098
+ return new Pager(PagedItem.PAGED_ITEM_DOCUMENTS, (x) => this.listInternal({ parent: params.parent, config: x.config }), await this.listInternal(params), params);
8079
8099
  };
8080
8100
  }
8081
8101
  /**
@@ -8143,12 +8163,6 @@ class Documents extends BaseModule {
8143
8163
  });
8144
8164
  }
8145
8165
  }
8146
- /**
8147
- * Lists all Documents in a FileSearchStore.
8148
- *
8149
- * @param params - The parameters for listing documents.
8150
- * @return ListDocumentsResponse.
8151
- */
8152
8166
  async listInternal(params) {
8153
8167
  var _a, _b;
8154
8168
  let response;
@@ -8357,12 +8371,6 @@ class FileSearchStores extends BaseModule {
8357
8371
  });
8358
8372
  }
8359
8373
  }
8360
- /**
8361
- * Lists all FileSearchStore owned by the user.
8362
- *
8363
- * @param params - The parameters for listing file search stores.
8364
- * @return ListFileSearchStoresResponse.
8365
- */
8366
8374
  async listInternal(params) {
8367
8375
  var _a, _b;
8368
8376
  let response;
@@ -9209,14 +9217,14 @@ function sessionResumptionConfigToMldev$1(fromObject) {
9209
9217
  }
9210
9218
  function speechConfigToVertex$1(fromObject) {
9211
9219
  const toObject = {};
9212
- const fromLanguageCode = getValueByPath(fromObject, ['languageCode']);
9213
- if (fromLanguageCode != null) {
9214
- setValueByPath(toObject, ['languageCode'], fromLanguageCode);
9215
- }
9216
9220
  const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']);
9217
9221
  if (fromVoiceConfig != null) {
9218
9222
  setValueByPath(toObject, ['voiceConfig'], fromVoiceConfig);
9219
9223
  }
9224
+ const fromLanguageCode = getValueByPath(fromObject, ['languageCode']);
9225
+ if (fromLanguageCode != null) {
9226
+ setValueByPath(toObject, ['languageCode'], fromLanguageCode);
9227
+ }
9220
9228
  if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) {
9221
9229
  throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.');
9222
9230
  }
@@ -10312,6 +10320,12 @@ function generateContentConfigToMldev(apiClient, fromObject, parentObject) {
10312
10320
  if (fromImageConfig != null) {
10313
10321
  setValueByPath(toObject, ['imageConfig'], imageConfigToMldev(fromImageConfig));
10314
10322
  }
10323
+ const fromEnableEnhancedCivicAnswers = getValueByPath(fromObject, [
10324
+ 'enableEnhancedCivicAnswers',
10325
+ ]);
10326
+ if (fromEnableEnhancedCivicAnswers != null) {
10327
+ setValueByPath(toObject, ['enableEnhancedCivicAnswers'], fromEnableEnhancedCivicAnswers);
10328
+ }
10315
10329
  return toObject;
10316
10330
  }
10317
10331
  function generateContentConfigToVertex(apiClient, fromObject, parentObject) {
@@ -10476,6 +10490,10 @@ function generateContentConfigToVertex(apiClient, fromObject, parentObject) {
10476
10490
  if (fromImageConfig != null) {
10477
10491
  setValueByPath(toObject, ['imageConfig'], imageConfigToVertex(fromImageConfig));
10478
10492
  }
10493
+ if (getValueByPath(fromObject, ['enableEnhancedCivicAnswers']) !==
10494
+ undefined) {
10495
+ throw new Error('enableEnhancedCivicAnswers parameter is not supported in Vertex AI.');
10496
+ }
10479
10497
  return toObject;
10480
10498
  }
10481
10499
  function generateContentParametersToMldev(apiClient, fromObject) {
@@ -12204,14 +12222,14 @@ function segmentImageSourceToVertex(fromObject, parentObject) {
12204
12222
  }
12205
12223
  function speechConfigToVertex(fromObject) {
12206
12224
  const toObject = {};
12207
- const fromLanguageCode = getValueByPath(fromObject, ['languageCode']);
12208
- if (fromLanguageCode != null) {
12209
- setValueByPath(toObject, ['languageCode'], fromLanguageCode);
12210
- }
12211
12225
  const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']);
12212
12226
  if (fromVoiceConfig != null) {
12213
12227
  setValueByPath(toObject, ['voiceConfig'], fromVoiceConfig);
12214
12228
  }
12229
+ const fromLanguageCode = getValueByPath(fromObject, ['languageCode']);
12230
+ if (fromLanguageCode != null) {
12231
+ setValueByPath(toObject, ['languageCode'], fromLanguageCode);
12232
+ }
12215
12233
  if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) {
12216
12234
  throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.');
12217
12235
  }
@@ -12689,8 +12707,8 @@ function isMcpCallableTool(object) {
12689
12707
  object instanceof McpCallableTool);
12690
12708
  }
12691
12709
  // List all tools from the MCP client.
12692
- function listAllTools(mcpClient, maxTools = 100) {
12693
- return __asyncGenerator(this, arguments, function* listAllTools_1() {
12710
+ function listAllTools(mcpClient_1) {
12711
+ return __asyncGenerator(this, arguments, function* listAllTools_1(mcpClient, maxTools = 100) {
12694
12712
  let cursor = undefined;
12695
12713
  let numTools = 0;
12696
12714
  while (numTools < maxTools) {
@@ -14010,9 +14028,9 @@ class Models extends BaseModule {
14010
14028
  let remoteCallCount = 0;
14011
14029
  const afcToolsMap = await this.initAfcToolsMap(params);
14012
14030
  return (function (models, afcTools, params) {
14013
- var _a, _b;
14014
14031
  return __asyncGenerator(this, arguments, function* () {
14015
- var _c, e_1, _d, _e;
14032
+ var _a, e_1, _b, _c;
14033
+ var _d, _e;
14016
14034
  while (remoteCallCount < maxRemoteCalls) {
14017
14035
  if (wereFunctionsCalled) {
14018
14036
  remoteCallCount++;
@@ -14023,14 +14041,14 @@ class Models extends BaseModule {
14023
14041
  const functionResponses = [];
14024
14042
  const responseContents = [];
14025
14043
  try {
14026
- 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) {
14027
- _e = response_1_1.value;
14044
+ 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) {
14045
+ _c = response_1_1.value;
14028
14046
  _f = false;
14029
- const chunk = _e;
14047
+ const chunk = _c;
14030
14048
  yield yield __await(chunk);
14031
- if (chunk.candidates && ((_a = chunk.candidates[0]) === null || _a === void 0 ? void 0 : _a.content)) {
14049
+ if (chunk.candidates && ((_d = chunk.candidates[0]) === null || _d === void 0 ? void 0 : _d.content)) {
14032
14050
  responseContents.push(chunk.candidates[0].content);
14033
- for (const part of (_b = chunk.candidates[0].content.parts) !== null && _b !== void 0 ? _b : []) {
14051
+ for (const part of (_e = chunk.candidates[0].content.parts) !== null && _e !== void 0 ? _e : []) {
14034
14052
  if (remoteCallCount < maxRemoteCalls && part.functionCall) {
14035
14053
  if (!part.functionCall.name) {
14036
14054
  throw new Error('Function call name was not returned by the model.');
@@ -14052,7 +14070,7 @@ class Models extends BaseModule {
14052
14070
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
14053
14071
  finally {
14054
14072
  try {
14055
- if (!_f && !_c && (_d = response_1.return)) yield __await(_d.call(response_1));
14073
+ if (!_f && !_a && (_b = response_1.return)) yield __await(_b.call(response_1));
14056
14074
  }
14057
14075
  finally { if (e_1) throw e_1.error; }
14058
14076
  }
@@ -15938,6 +15956,26 @@ function cancelTuningJobParametersToVertex(fromObject, _rootObject) {
15938
15956
  }
15939
15957
  return toObject;
15940
15958
  }
15959
+ function cancelTuningJobResponseFromMldev(fromObject, _rootObject) {
15960
+ const toObject = {};
15961
+ const fromSdkHttpResponse = getValueByPath(fromObject, [
15962
+ 'sdkHttpResponse',
15963
+ ]);
15964
+ if (fromSdkHttpResponse != null) {
15965
+ setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);
15966
+ }
15967
+ return toObject;
15968
+ }
15969
+ function cancelTuningJobResponseFromVertex(fromObject, _rootObject) {
15970
+ const toObject = {};
15971
+ const fromSdkHttpResponse = getValueByPath(fromObject, [
15972
+ 'sdkHttpResponse',
15973
+ ]);
15974
+ if (fromSdkHttpResponse != null) {
15975
+ setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);
15976
+ }
15977
+ return toObject;
15978
+ }
15941
15979
  function createTuningJobConfigToMldev(fromObject, parentObject, _rootObject) {
15942
15980
  const toObject = {};
15943
15981
  if (getValueByPath(fromObject, ['validationDataset']) !== undefined) {
@@ -16599,28 +16637,33 @@ class Tunings extends BaseModule {
16599
16637
  super();
16600
16638
  this.apiClient = apiClient;
16601
16639
  /**
16602
- * Gets a TuningJob.
16640
+ * Lists tuning jobs.
16603
16641
  *
16604
- * @param name - The resource name of the tuning job.
16605
- * @return - A TuningJob object.
16642
+ * @param params - The parameters for the list request.
16643
+ * @return - A pager of tuning jobs.
16606
16644
  *
16607
- * @experimental - The SDK's tuning implementation is experimental, and may
16608
- * change in future versions.
16645
+ * @example
16646
+ * ```ts
16647
+ * const tuningJobs = await ai.tunings.list({config: {'pageSize': 2}});
16648
+ * for await (const tuningJob of tuningJobs) {
16649
+ * console.log(tuningJob);
16650
+ * }
16651
+ * ```
16609
16652
  */
16610
- this.get = async (params) => {
16611
- return await this.getInternal(params);
16653
+ this.list = async (params = {}) => {
16654
+ return new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params);
16612
16655
  };
16613
16656
  /**
16614
- * Lists tuning jobs.
16657
+ * Gets a TuningJob.
16615
16658
  *
16616
- * @param config - The configuration for the list request.
16617
- * @return - A list of tuning jobs.
16659
+ * @param name - The resource name of the tuning job.
16660
+ * @return - A TuningJob object.
16618
16661
  *
16619
16662
  * @experimental - The SDK's tuning implementation is experimental, and may
16620
16663
  * change in future versions.
16621
16664
  */
16622
- this.list = async (params = {}) => {
16623
- return new Pager(PagedItem.PAGED_ITEM_TUNING_JOBS, (x) => this.listInternal(x), await this.listInternal(params), params);
16665
+ this.get = async (params) => {
16666
+ return await this.getInternal(params);
16624
16667
  };
16625
16668
  /**
16626
16669
  * Creates a supervised fine-tuning job.
@@ -16815,6 +16858,7 @@ class Tunings extends BaseModule {
16815
16858
  */
16816
16859
  async cancel(params) {
16817
16860
  var _a, _b, _c, _d;
16861
+ let response;
16818
16862
  let path = '';
16819
16863
  let queryParams = {};
16820
16864
  if (this.apiClient.isVertexAI()) {
@@ -16823,13 +16867,29 @@ class Tunings extends BaseModule {
16823
16867
  queryParams = body['_query'];
16824
16868
  delete body['_url'];
16825
16869
  delete body['_query'];
16826
- await this.apiClient.request({
16870
+ response = this.apiClient
16871
+ .request({
16827
16872
  path: path,
16828
16873
  queryParams: queryParams,
16829
16874
  body: JSON.stringify(body),
16830
16875
  httpMethod: 'POST',
16831
16876
  httpOptions: (_a = params.config) === null || _a === void 0 ? void 0 : _a.httpOptions,
16832
16877
  abortSignal: (_b = params.config) === null || _b === void 0 ? void 0 : _b.abortSignal,
16878
+ })
16879
+ .then((httpResponse) => {
16880
+ return httpResponse.json().then((jsonResponse) => {
16881
+ const response = jsonResponse;
16882
+ response.sdkHttpResponse = {
16883
+ headers: httpResponse.headers,
16884
+ };
16885
+ return response;
16886
+ });
16887
+ });
16888
+ return response.then((apiResponse) => {
16889
+ const resp = cancelTuningJobResponseFromVertex(apiResponse);
16890
+ const typedResp = new CancelTuningJobResponse();
16891
+ Object.assign(typedResp, resp);
16892
+ return typedResp;
16833
16893
  });
16834
16894
  }
16835
16895
  else {
@@ -16838,13 +16898,29 @@ class Tunings extends BaseModule {
16838
16898
  queryParams = body['_query'];
16839
16899
  delete body['_url'];
16840
16900
  delete body['_query'];
16841
- await this.apiClient.request({
16901
+ response = this.apiClient
16902
+ .request({
16842
16903
  path: path,
16843
16904
  queryParams: queryParams,
16844
16905
  body: JSON.stringify(body),
16845
16906
  httpMethod: 'POST',
16846
16907
  httpOptions: (_c = params.config) === null || _c === void 0 ? void 0 : _c.httpOptions,
16847
16908
  abortSignal: (_d = params.config) === null || _d === void 0 ? void 0 : _d.abortSignal,
16909
+ })
16910
+ .then((httpResponse) => {
16911
+ return httpResponse.json().then((jsonResponse) => {
16912
+ const response = jsonResponse;
16913
+ response.sdkHttpResponse = {
16914
+ headers: httpResponse.headers,
16915
+ };
16916
+ return response;
16917
+ });
16918
+ });
16919
+ return response.then((apiResponse) => {
16920
+ const resp = cancelTuningJobResponseFromMldev(apiResponse);
16921
+ const typedResp = new CancelTuningJobResponse();
16922
+ Object.assign(typedResp, resp);
16923
+ return typedResp;
16848
16924
  });
16849
16925
  }
16850
16926
  }
@@ -16999,13 +17075,14 @@ class GoogleGenAI {
16999
17075
  this.vertexai = (_a = options.vertexai) !== null && _a !== void 0 ? _a : false;
17000
17076
  this.apiKey = options.apiKey;
17001
17077
  this.apiVersion = options.apiVersion;
17078
+ this.httpOptions = options.httpOptions;
17002
17079
  const auth = new WebAuth(this.apiKey);
17003
17080
  this.apiClient = new ApiClient({
17004
17081
  auth: auth,
17005
17082
  apiVersion: this.apiVersion,
17006
17083
  apiKey: this.apiKey,
17007
17084
  vertexai: this.vertexai,
17008
- httpOptions: options.httpOptions,
17085
+ httpOptions: this.httpOptions,
17009
17086
  userAgentExtra: LANGUAGE_LABEL_PREFIX + 'cross',
17010
17087
  uploader: new CrossUploader(),
17011
17088
  downloader: new CrossDownloader(),
@@ -17023,5 +17100,5 @@ class GoogleGenAI {
17023
17100
  }
17024
17101
  }
17025
17102
 
17026
- export { ActivityHandling, AdapterSize, ApiError, ApiSpec, AuthType, Batches, Behavior, BlockedReason, Caches, Chat, Chats, ComputeTokensResponse, ContentReferenceImage, ControlReferenceImage, ControlReferenceType, CountTokensResponse, CreateFileResponse, DeleteCachedContentResponse, DeleteFileResponse, DeleteModelResponse, DocumentState, DynamicRetrievalConfigMode, EditImageResponse, EditMode, EmbedContentResponse, EndSensitivity, Environment, FeatureSelectionPreference, FileSource, FileState, Files, FinishReason, FunctionCallingConfigMode, FunctionResponse, FunctionResponseBlob, FunctionResponseFileData, FunctionResponsePart, FunctionResponseScheduling, GenerateContentResponse, GenerateContentResponsePromptFeedback, GenerateContentResponseUsageMetadata, GenerateImagesResponse, GenerateVideosOperation, GenerateVideosResponse, GoogleGenAI, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, HttpElementLocation, HttpResponse, ImagePromptLanguage, ImportFileOperation, ImportFileResponse, InlinedEmbedContentResponse, InlinedResponse, JobState, Language, ListBatchJobsResponse, ListCachedContentsResponse, ListDocumentsResponse, ListFileSearchStoresResponse, ListFilesResponse, ListModelsResponse, ListTuningJobsResponse, Live, LiveClientToolResponse, LiveMusicPlaybackControl, LiveMusicServerMessage, LiveSendToolResponseParameters, LiveServerMessage, MaskReferenceImage, MaskReferenceMode, MediaModality, MediaResolution, Modality, Mode, Models, MusicGenerationMode, Operations, Outcome, PagedItem, Pager, PartMediaResolutionLevel, PersonGeneration, PhishBlockThreshold, RawReferenceImage, RecontextImageResponse, ReplayResponse, SafetyFilterLevel, Scale, SegmentImageResponse, SegmentMode, Session, SingleEmbedContentResponse, StartSensitivity, StyleReferenceImage, SubjectReferenceImage, SubjectReferenceType, ThinkingLevel, Tokens, TrafficType, TuningMethod, TuningMode, TuningTask, TurnCompleteReason, TurnCoverage, Type, UploadToFileSearchStoreOperation, UploadToFileSearchStoreResponse, UploadToFileSearchStoreResumableResponse, UpscaleImageResponse, UrlRetrievalStatus, VideoCompressionQuality, VideoGenerationMaskMode, VideoGenerationReferenceType, createFunctionResponsePartFromBase64, createFunctionResponsePartFromUri, createModelContent, createPartFromBase64, createPartFromCodeExecutionResult, createPartFromExecutableCode, createPartFromFunctionCall, createPartFromFunctionResponse, createPartFromText, createPartFromUri, createUserContent, mcpToTool, setDefaultBaseUrls };
17103
+ export { ActivityHandling, AdapterSize, ApiError, ApiSpec, AuthType, Batches, Behavior, BlockedReason, Caches, CancelTuningJobResponse, Chat, Chats, ComputeTokensResponse, ContentReferenceImage, ControlReferenceImage, ControlReferenceType, CountTokensResponse, CreateFileResponse, DeleteCachedContentResponse, DeleteFileResponse, DeleteModelResponse, DocumentState, DynamicRetrievalConfigMode, EditImageResponse, EditMode, EmbedContentResponse, EndSensitivity, Environment, FeatureSelectionPreference, FileSource, FileState, Files, FinishReason, FunctionCallingConfigMode, FunctionResponse, FunctionResponseBlob, FunctionResponseFileData, FunctionResponsePart, FunctionResponseScheduling, GenerateContentResponse, GenerateContentResponsePromptFeedback, GenerateContentResponseUsageMetadata, GenerateImagesResponse, GenerateVideosOperation, GenerateVideosResponse, GoogleGenAI, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, HttpElementLocation, HttpResponse, ImagePromptLanguage, ImportFileOperation, ImportFileResponse, InlinedEmbedContentResponse, InlinedResponse, JobState, Language, ListBatchJobsResponse, ListCachedContentsResponse, ListDocumentsResponse, ListFileSearchStoresResponse, ListFilesResponse, ListModelsResponse, ListTuningJobsResponse, Live, LiveClientToolResponse, LiveMusicPlaybackControl, LiveMusicServerMessage, LiveSendToolResponseParameters, LiveServerMessage, MaskReferenceImage, MaskReferenceMode, MediaModality, MediaResolution, Modality, Mode, Models, MusicGenerationMode, Operations, Outcome, PagedItem, Pager, PartMediaResolutionLevel, PersonGeneration, PhishBlockThreshold, RawReferenceImage, RecontextImageResponse, ReplayResponse, SafetyFilterLevel, Scale, SegmentImageResponse, SegmentMode, Session, SingleEmbedContentResponse, StartSensitivity, StyleReferenceImage, SubjectReferenceImage, SubjectReferenceType, ThinkingLevel, Tokens, TrafficType, TuningMethod, TuningMode, TuningTask, TurnCompleteReason, TurnCoverage, Type, UploadToFileSearchStoreOperation, UploadToFileSearchStoreResponse, UploadToFileSearchStoreResumableResponse, UpscaleImageResponse, UrlRetrievalStatus, VideoCompressionQuality, VideoGenerationMaskMode, VideoGenerationReferenceType, createFunctionResponsePartFromBase64, createFunctionResponsePartFromUri, createModelContent, createPartFromBase64, createPartFromCodeExecutionResult, createPartFromExecutableCode, createPartFromFunctionCall, createPartFromFunctionResponse, createPartFromText, createPartFromUri, createUserContent, mcpToTool, setDefaultBaseUrls };
17027
17104
  //# sourceMappingURL=index.mjs.map