@google/genai 1.32.0 → 1.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +233 -1
- package/dist/genai.d.ts +2092 -10
- package/dist/index.cjs +2285 -228
- package/dist/index.mjs +2286 -229
- package/dist/index.mjs.map +1 -1
- package/dist/node/index.cjs +2249 -195
- package/dist/node/index.mjs +2250 -196
- package/dist/node/index.mjs.map +1 -1
- package/dist/node/node.d.ts +2092 -10
- package/dist/web/index.mjs +2179 -125
- package/dist/web/index.mjs.map +1 -1
- package/dist/web/web.d.ts +2092 -10
- package/package.json +1 -1
package/dist/web/index.mjs
CHANGED
|
@@ -786,21 +786,29 @@ var PhishBlockThreshold;
|
|
|
786
786
|
*/
|
|
787
787
|
PhishBlockThreshold["BLOCK_ONLY_EXTREMELY_HIGH"] = "BLOCK_ONLY_EXTREMELY_HIGH";
|
|
788
788
|
})(PhishBlockThreshold || (PhishBlockThreshold = {}));
|
|
789
|
-
/** The
|
|
789
|
+
/** The number of thoughts tokens that the model should generate. */
|
|
790
790
|
var ThinkingLevel;
|
|
791
791
|
(function (ThinkingLevel) {
|
|
792
792
|
/**
|
|
793
|
-
*
|
|
793
|
+
* Unspecified thinking level.
|
|
794
794
|
*/
|
|
795
795
|
ThinkingLevel["THINKING_LEVEL_UNSPECIFIED"] = "THINKING_LEVEL_UNSPECIFIED";
|
|
796
796
|
/**
|
|
797
797
|
* Low thinking level.
|
|
798
798
|
*/
|
|
799
799
|
ThinkingLevel["LOW"] = "LOW";
|
|
800
|
+
/**
|
|
801
|
+
* Medium thinking level.
|
|
802
|
+
*/
|
|
803
|
+
ThinkingLevel["MEDIUM"] = "MEDIUM";
|
|
800
804
|
/**
|
|
801
805
|
* High thinking level.
|
|
802
806
|
*/
|
|
803
807
|
ThinkingLevel["HIGH"] = "HIGH";
|
|
808
|
+
/**
|
|
809
|
+
* MINIMAL thinking level.
|
|
810
|
+
*/
|
|
811
|
+
ThinkingLevel["MINIMAL"] = "MINIMAL";
|
|
804
812
|
})(ThinkingLevel || (ThinkingLevel = {}));
|
|
805
813
|
/** Harm category. */
|
|
806
814
|
var HarmCategory;
|
|
@@ -959,6 +967,14 @@ var FinishReason;
|
|
|
959
967
|
* The model was expected to generate an image, but none was generated.
|
|
960
968
|
*/
|
|
961
969
|
FinishReason["NO_IMAGE"] = "NO_IMAGE";
|
|
970
|
+
/**
|
|
971
|
+
* Image generation stopped because the generated image may be a recitation from a source.
|
|
972
|
+
*/
|
|
973
|
+
FinishReason["IMAGE_RECITATION"] = "IMAGE_RECITATION";
|
|
974
|
+
/**
|
|
975
|
+
* Image generation stopped for a reason not otherwise specified.
|
|
976
|
+
*/
|
|
977
|
+
FinishReason["IMAGE_OTHER"] = "IMAGE_OTHER";
|
|
962
978
|
})(FinishReason || (FinishReason = {}));
|
|
963
979
|
/** Output only. Harm probability levels in the content. */
|
|
964
980
|
var HarmProbability;
|
|
@@ -1263,6 +1279,10 @@ var PartMediaResolutionLevel;
|
|
|
1263
1279
|
* Media resolution set to high.
|
|
1264
1280
|
*/
|
|
1265
1281
|
PartMediaResolutionLevel["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH";
|
|
1282
|
+
/**
|
|
1283
|
+
* Media resolution set to ultra high.
|
|
1284
|
+
*/
|
|
1285
|
+
PartMediaResolutionLevel["MEDIA_RESOLUTION_ULTRA_HIGH"] = "MEDIA_RESOLUTION_ULTRA_HIGH";
|
|
1266
1286
|
})(PartMediaResolutionLevel || (PartMediaResolutionLevel = {}));
|
|
1267
1287
|
/** Options for feature selection preference. */
|
|
1268
1288
|
var FeatureSelectionPreference;
|
|
@@ -1581,6 +1601,22 @@ var MediaModality;
|
|
|
1581
1601
|
*/
|
|
1582
1602
|
MediaModality["DOCUMENT"] = "DOCUMENT";
|
|
1583
1603
|
})(MediaModality || (MediaModality = {}));
|
|
1604
|
+
/** The type of the VAD signal. */
|
|
1605
|
+
var VadSignalType;
|
|
1606
|
+
(function (VadSignalType) {
|
|
1607
|
+
/**
|
|
1608
|
+
* The default is VAD_SIGNAL_TYPE_UNSPECIFIED.
|
|
1609
|
+
*/
|
|
1610
|
+
VadSignalType["VAD_SIGNAL_TYPE_UNSPECIFIED"] = "VAD_SIGNAL_TYPE_UNSPECIFIED";
|
|
1611
|
+
/**
|
|
1612
|
+
* Start of sentence signal.
|
|
1613
|
+
*/
|
|
1614
|
+
VadSignalType["VAD_SIGNAL_TYPE_SOS"] = "VAD_SIGNAL_TYPE_SOS";
|
|
1615
|
+
/**
|
|
1616
|
+
* End of sentence signal.
|
|
1617
|
+
*/
|
|
1618
|
+
VadSignalType["VAD_SIGNAL_TYPE_EOS"] = "VAD_SIGNAL_TYPE_EOS";
|
|
1619
|
+
})(VadSignalType || (VadSignalType = {}));
|
|
1584
1620
|
/** Start of speech sensitivity. */
|
|
1585
1621
|
var StartSensitivity;
|
|
1586
1622
|
(function (StartSensitivity) {
|
|
@@ -6251,6 +6287,18 @@ PERFORMANCE OF THIS SOFTWARE.
|
|
|
6251
6287
|
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
|
|
6252
6288
|
|
|
6253
6289
|
|
|
6290
|
+
function __rest(s, e) {
|
|
6291
|
+
var t = {};
|
|
6292
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
|
6293
|
+
t[p] = s[p];
|
|
6294
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
|
6295
|
+
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
6296
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
|
6297
|
+
t[p[i]] = s[p[i]];
|
|
6298
|
+
}
|
|
6299
|
+
return t;
|
|
6300
|
+
}
|
|
6301
|
+
|
|
6254
6302
|
function __values(o) {
|
|
6255
6303
|
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
|
|
6256
6304
|
if (m) return m.call(o);
|
|
@@ -7210,7 +7258,7 @@ function generationConfigToVertex$1(fromObject) {
|
|
|
7210
7258
|
}
|
|
7211
7259
|
const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']);
|
|
7212
7260
|
if (fromSpeechConfig != null) {
|
|
7213
|
-
setValueByPath(toObject, ['speechConfig'],
|
|
7261
|
+
setValueByPath(toObject, ['speechConfig'], fromSpeechConfig);
|
|
7214
7262
|
}
|
|
7215
7263
|
const fromStopSequences = getValueByPath(fromObject, [
|
|
7216
7264
|
'stopSequences',
|
|
@@ -7377,6 +7425,9 @@ function liveConnectConfigToMldev$1(fromObject, parentObject) {
|
|
|
7377
7425
|
if (parentObject !== undefined && fromProactivity != null) {
|
|
7378
7426
|
setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity);
|
|
7379
7427
|
}
|
|
7428
|
+
if (getValueByPath(fromObject, ['explicitVadSignal']) !== undefined) {
|
|
7429
|
+
throw new Error('explicitVadSignal parameter is not supported in Gemini API.');
|
|
7430
|
+
}
|
|
7380
7431
|
return toObject;
|
|
7381
7432
|
}
|
|
7382
7433
|
function liveConnectConfigToVertex(fromObject, parentObject) {
|
|
@@ -7423,7 +7474,7 @@ function liveConnectConfigToVertex(fromObject, parentObject) {
|
|
|
7423
7474
|
}
|
|
7424
7475
|
const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']);
|
|
7425
7476
|
if (parentObject !== undefined && fromSpeechConfig != null) {
|
|
7426
|
-
setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'],
|
|
7477
|
+
setValueByPath(parentObject, ['setup', 'generationConfig', 'speechConfig'], tLiveSpeechConfig(fromSpeechConfig));
|
|
7427
7478
|
}
|
|
7428
7479
|
const fromThinkingConfig = getValueByPath(fromObject, [
|
|
7429
7480
|
'thinkingConfig',
|
|
@@ -7487,6 +7538,12 @@ function liveConnectConfigToVertex(fromObject, parentObject) {
|
|
|
7487
7538
|
if (parentObject !== undefined && fromProactivity != null) {
|
|
7488
7539
|
setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity);
|
|
7489
7540
|
}
|
|
7541
|
+
const fromExplicitVadSignal = getValueByPath(fromObject, [
|
|
7542
|
+
'explicitVadSignal',
|
|
7543
|
+
]);
|
|
7544
|
+
if (parentObject !== undefined && fromExplicitVadSignal != null) {
|
|
7545
|
+
setValueByPath(parentObject, ['setup', 'explicitVadSignal'], fromExplicitVadSignal);
|
|
7546
|
+
}
|
|
7490
7547
|
return toObject;
|
|
7491
7548
|
}
|
|
7492
7549
|
function liveConnectParametersToMldev(apiClient, fromObject) {
|
|
@@ -7663,6 +7720,12 @@ function liveServerMessageFromVertex(fromObject) {
|
|
|
7663
7720
|
if (fromSessionResumptionUpdate != null) {
|
|
7664
7721
|
setValueByPath(toObject, ['sessionResumptionUpdate'], fromSessionResumptionUpdate);
|
|
7665
7722
|
}
|
|
7723
|
+
const fromVoiceActivityDetectionSignal = getValueByPath(fromObject, [
|
|
7724
|
+
'voiceActivityDetectionSignal',
|
|
7725
|
+
]);
|
|
7726
|
+
if (fromVoiceActivityDetectionSignal != null) {
|
|
7727
|
+
setValueByPath(toObject, ['voiceActivityDetectionSignal'], fromVoiceActivityDetectionSignal);
|
|
7728
|
+
}
|
|
7666
7729
|
return toObject;
|
|
7667
7730
|
}
|
|
7668
7731
|
function partToMldev$2(fromObject) {
|
|
@@ -7736,21 +7799,6 @@ function sessionResumptionConfigToMldev$1(fromObject) {
|
|
|
7736
7799
|
}
|
|
7737
7800
|
return toObject;
|
|
7738
7801
|
}
|
|
7739
|
-
function speechConfigToVertex$1(fromObject) {
|
|
7740
|
-
const toObject = {};
|
|
7741
|
-
const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']);
|
|
7742
|
-
if (fromVoiceConfig != null) {
|
|
7743
|
-
setValueByPath(toObject, ['voiceConfig'], fromVoiceConfig);
|
|
7744
|
-
}
|
|
7745
|
-
const fromLanguageCode = getValueByPath(fromObject, ['languageCode']);
|
|
7746
|
-
if (fromLanguageCode != null) {
|
|
7747
|
-
setValueByPath(toObject, ['languageCode'], fromLanguageCode);
|
|
7748
|
-
}
|
|
7749
|
-
if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) {
|
|
7750
|
-
throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.');
|
|
7751
|
-
}
|
|
7752
|
-
return toObject;
|
|
7753
|
-
}
|
|
7754
7802
|
function toolToMldev$2(fromObject) {
|
|
7755
7803
|
const toObject = {};
|
|
7756
7804
|
const fromFunctionDeclarations = getValueByPath(fromObject, [
|
|
@@ -8993,7 +9041,7 @@ function generateContentConfigToVertex(apiClient, fromObject, parentObject) {
|
|
|
8993
9041
|
}
|
|
8994
9042
|
const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']);
|
|
8995
9043
|
if (fromSpeechConfig != null) {
|
|
8996
|
-
setValueByPath(toObject, ['speechConfig'],
|
|
9044
|
+
setValueByPath(toObject, ['speechConfig'], tSpeechConfig(fromSpeechConfig));
|
|
8997
9045
|
}
|
|
8998
9046
|
const fromAudioTimestamp = getValueByPath(fromObject, [
|
|
8999
9047
|
'audioTimestamp',
|
|
@@ -9939,7 +9987,7 @@ function generationConfigToVertex(fromObject) {
|
|
|
9939
9987
|
}
|
|
9940
9988
|
const fromSpeechConfig = getValueByPath(fromObject, ['speechConfig']);
|
|
9941
9989
|
if (fromSpeechConfig != null) {
|
|
9942
|
-
setValueByPath(toObject, ['speechConfig'],
|
|
9990
|
+
setValueByPath(toObject, ['speechConfig'], fromSpeechConfig);
|
|
9943
9991
|
}
|
|
9944
9992
|
const fromStopSequences = getValueByPath(fromObject, [
|
|
9945
9993
|
'stopSequences',
|
|
@@ -10741,21 +10789,6 @@ function segmentImageSourceToVertex(fromObject, parentObject) {
|
|
|
10741
10789
|
}
|
|
10742
10790
|
return toObject;
|
|
10743
10791
|
}
|
|
10744
|
-
function speechConfigToVertex(fromObject) {
|
|
10745
|
-
const toObject = {};
|
|
10746
|
-
const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']);
|
|
10747
|
-
if (fromVoiceConfig != null) {
|
|
10748
|
-
setValueByPath(toObject, ['voiceConfig'], fromVoiceConfig);
|
|
10749
|
-
}
|
|
10750
|
-
const fromLanguageCode = getValueByPath(fromObject, ['languageCode']);
|
|
10751
|
-
if (fromLanguageCode != null) {
|
|
10752
|
-
setValueByPath(toObject, ['languageCode'], fromLanguageCode);
|
|
10753
|
-
}
|
|
10754
|
-
if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) {
|
|
10755
|
-
throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.');
|
|
10756
|
-
}
|
|
10757
|
-
return toObject;
|
|
10758
|
-
}
|
|
10759
10792
|
function toolConfigToMldev(fromObject) {
|
|
10760
10793
|
const toObject = {};
|
|
10761
10794
|
const fromFunctionCallingConfig = getValueByPath(fromObject, [
|
|
@@ -11437,7 +11470,7 @@ const CONTENT_TYPE_HEADER = 'Content-Type';
|
|
|
11437
11470
|
const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';
|
|
11438
11471
|
const USER_AGENT_HEADER = 'User-Agent';
|
|
11439
11472
|
const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';
|
|
11440
|
-
const SDK_VERSION = '1.
|
|
11473
|
+
const SDK_VERSION = '1.34.0'; // x-release-please-version
|
|
11441
11474
|
const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;
|
|
11442
11475
|
const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';
|
|
11443
11476
|
const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';
|
|
@@ -11511,6 +11544,11 @@ class ApiClient {
|
|
|
11511
11544
|
getLocation() {
|
|
11512
11545
|
return this.clientOptions.location;
|
|
11513
11546
|
}
|
|
11547
|
+
async getAuthHeaders() {
|
|
11548
|
+
const headers = new Headers();
|
|
11549
|
+
await this.clientOptions.auth.addAuthHeaders(headers);
|
|
11550
|
+
return headers;
|
|
11551
|
+
}
|
|
11514
11552
|
getApiVersion() {
|
|
11515
11553
|
if (this.clientOptions.httpOptions &&
|
|
11516
11554
|
this.clientOptions.httpOptions.apiVersion !== undefined) {
|
|
@@ -14909,6 +14947,9 @@ function liveConnectConfigToMldev(fromObject, parentObject) {
|
|
|
14909
14947
|
if (parentObject !== undefined && fromProactivity != null) {
|
|
14910
14948
|
setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity);
|
|
14911
14949
|
}
|
|
14950
|
+
if (getValueByPath(fromObject, ['explicitVadSignal']) !== undefined) {
|
|
14951
|
+
throw new Error('explicitVadSignal parameter is not supported in Gemini API.');
|
|
14952
|
+
}
|
|
14912
14953
|
return toObject;
|
|
14913
14954
|
}
|
|
14914
14955
|
function liveConnectConstraintsToMldev(apiClient, fromObject) {
|
|
@@ -15821,115 +15862,2107 @@ class FileSearchStores extends BaseModule {
|
|
|
15821
15862
|
* Copyright 2025 Google LLC
|
|
15822
15863
|
* SPDX-License-Identifier: Apache-2.0
|
|
15823
15864
|
*/
|
|
15824
|
-
//
|
|
15825
|
-
|
|
15826
|
-
|
|
15827
|
-
|
|
15828
|
-
|
|
15829
|
-
|
|
15865
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
15866
|
+
/**
|
|
15867
|
+
* https://stackoverflow.com/a/2117523
|
|
15868
|
+
*/
|
|
15869
|
+
let uuid4Internal = function () {
|
|
15870
|
+
const { crypto } = globalThis;
|
|
15871
|
+
if (crypto === null || crypto === void 0 ? void 0 : crypto.randomUUID) {
|
|
15872
|
+
uuid4Internal = crypto.randomUUID.bind(crypto);
|
|
15873
|
+
return crypto.randomUUID();
|
|
15874
|
+
}
|
|
15875
|
+
const u8 = new Uint8Array(1);
|
|
15876
|
+
const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff;
|
|
15877
|
+
return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16));
|
|
15878
|
+
};
|
|
15879
|
+
const uuid4 = () => uuid4Internal();
|
|
15880
|
+
|
|
15881
|
+
/**
|
|
15882
|
+
* @license
|
|
15883
|
+
* Copyright 2025 Google LLC
|
|
15884
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
15885
|
+
*/
|
|
15886
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
15887
|
+
function isAbortError(err) {
|
|
15888
|
+
return (typeof err === 'object' &&
|
|
15889
|
+
err !== null &&
|
|
15890
|
+
// Spec-compliant fetch implementations
|
|
15891
|
+
(('name' in err && err.name === 'AbortError') ||
|
|
15892
|
+
// Expo fetch
|
|
15893
|
+
('message' in err && String(err.message).includes('FetchRequestCanceledException'))));
|
|
15894
|
+
}
|
|
15895
|
+
const castToError = (err) => {
|
|
15896
|
+
if (err instanceof Error)
|
|
15897
|
+
return err;
|
|
15898
|
+
if (typeof err === 'object' && err !== null) {
|
|
15899
|
+
try {
|
|
15900
|
+
if (Object.prototype.toString.call(err) === '[object Error]') {
|
|
15901
|
+
// @ts-ignore - not all envs have native support for cause yet
|
|
15902
|
+
const error = new Error(err.message, err.cause ? { cause: err.cause } : {});
|
|
15903
|
+
if (err.stack)
|
|
15904
|
+
error.stack = err.stack;
|
|
15905
|
+
// @ts-ignore - not all envs have native support for cause yet
|
|
15906
|
+
if (err.cause && !error.cause)
|
|
15907
|
+
error.cause = err.cause;
|
|
15908
|
+
if (err.name)
|
|
15909
|
+
error.name = err.name;
|
|
15910
|
+
return error;
|
|
15911
|
+
}
|
|
15912
|
+
}
|
|
15913
|
+
catch (_a) { }
|
|
15914
|
+
try {
|
|
15915
|
+
return new Error(JSON.stringify(err));
|
|
15916
|
+
}
|
|
15917
|
+
catch (_b) { }
|
|
15830
15918
|
}
|
|
15831
|
-
return
|
|
15919
|
+
return new Error(err);
|
|
15920
|
+
};
|
|
15921
|
+
|
|
15922
|
+
/**
|
|
15923
|
+
* @license
|
|
15924
|
+
* Copyright 2025 Google LLC
|
|
15925
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
15926
|
+
*/
|
|
15927
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
15928
|
+
class GeminiNextGenAPIClientError extends Error {
|
|
15832
15929
|
}
|
|
15833
|
-
|
|
15834
|
-
|
|
15835
|
-
|
|
15836
|
-
|
|
15837
|
-
|
|
15930
|
+
class APIError extends GeminiNextGenAPIClientError {
|
|
15931
|
+
constructor(status, error, message, headers) {
|
|
15932
|
+
super(`${APIError.makeMessage(status, error, message)}`);
|
|
15933
|
+
this.status = status;
|
|
15934
|
+
this.headers = headers;
|
|
15935
|
+
this.error = error;
|
|
15936
|
+
}
|
|
15937
|
+
static makeMessage(status, error, message) {
|
|
15938
|
+
const msg = (error === null || error === void 0 ? void 0 : error.message) ?
|
|
15939
|
+
typeof error.message === 'string' ?
|
|
15940
|
+
error.message
|
|
15941
|
+
: JSON.stringify(error.message)
|
|
15942
|
+
: error ? JSON.stringify(error)
|
|
15943
|
+
: message;
|
|
15944
|
+
if (status && msg) {
|
|
15945
|
+
return `${status} ${msg}`;
|
|
15946
|
+
}
|
|
15947
|
+
if (status) {
|
|
15948
|
+
return `${status} status code (no body)`;
|
|
15949
|
+
}
|
|
15950
|
+
if (msg) {
|
|
15951
|
+
return msg;
|
|
15952
|
+
}
|
|
15953
|
+
return '(no status code or body)';
|
|
15954
|
+
}
|
|
15955
|
+
static generate(status, errorResponse, message, headers) {
|
|
15956
|
+
if (!status || !headers) {
|
|
15957
|
+
return new APIConnectionError({ message, cause: castToError(errorResponse) });
|
|
15958
|
+
}
|
|
15959
|
+
const error = errorResponse;
|
|
15960
|
+
if (status === 400) {
|
|
15961
|
+
return new BadRequestError(status, error, message, headers);
|
|
15962
|
+
}
|
|
15963
|
+
if (status === 401) {
|
|
15964
|
+
return new AuthenticationError(status, error, message, headers);
|
|
15965
|
+
}
|
|
15966
|
+
if (status === 403) {
|
|
15967
|
+
return new PermissionDeniedError(status, error, message, headers);
|
|
15968
|
+
}
|
|
15969
|
+
if (status === 404) {
|
|
15970
|
+
return new NotFoundError(status, error, message, headers);
|
|
15971
|
+
}
|
|
15972
|
+
if (status === 409) {
|
|
15973
|
+
return new ConflictError(status, error, message, headers);
|
|
15974
|
+
}
|
|
15975
|
+
if (status === 422) {
|
|
15976
|
+
return new UnprocessableEntityError(status, error, message, headers);
|
|
15977
|
+
}
|
|
15978
|
+
if (status === 429) {
|
|
15979
|
+
return new RateLimitError(status, error, message, headers);
|
|
15980
|
+
}
|
|
15981
|
+
if (status >= 500) {
|
|
15982
|
+
return new InternalServerError(status, error, message, headers);
|
|
15983
|
+
}
|
|
15984
|
+
return new APIError(status, error, message, headers);
|
|
15838
15985
|
}
|
|
15839
|
-
return toObject;
|
|
15840
15986
|
}
|
|
15841
|
-
|
|
15842
|
-
|
|
15843
|
-
|
|
15844
|
-
'sdkHttpResponse',
|
|
15845
|
-
]);
|
|
15846
|
-
if (fromSdkHttpResponse != null) {
|
|
15847
|
-
setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);
|
|
15987
|
+
class APIUserAbortError extends APIError {
|
|
15988
|
+
constructor({ message } = {}) {
|
|
15989
|
+
super(undefined, undefined, message || 'Request was aborted.', undefined);
|
|
15848
15990
|
}
|
|
15849
|
-
return toObject;
|
|
15850
15991
|
}
|
|
15851
|
-
|
|
15852
|
-
|
|
15853
|
-
|
|
15854
|
-
'
|
|
15855
|
-
|
|
15856
|
-
|
|
15857
|
-
|
|
15992
|
+
class APIConnectionError extends APIError {
|
|
15993
|
+
constructor({ message, cause }) {
|
|
15994
|
+
super(undefined, undefined, message || 'Connection error.', undefined);
|
|
15995
|
+
// in some environments the 'cause' property is already declared
|
|
15996
|
+
// @ts-ignore
|
|
15997
|
+
if (cause)
|
|
15998
|
+
this.cause = cause;
|
|
15858
15999
|
}
|
|
15859
|
-
return toObject;
|
|
15860
16000
|
}
|
|
15861
|
-
|
|
15862
|
-
|
|
15863
|
-
|
|
15864
|
-
throw new Error('validationDataset parameter is not supported in Gemini API.');
|
|
16001
|
+
class APIConnectionTimeoutError extends APIConnectionError {
|
|
16002
|
+
constructor({ message } = {}) {
|
|
16003
|
+
super({ message: message !== null && message !== void 0 ? message : 'Request timed out.' });
|
|
15865
16004
|
}
|
|
15866
|
-
|
|
15867
|
-
|
|
15868
|
-
|
|
15869
|
-
|
|
15870
|
-
|
|
16005
|
+
}
|
|
16006
|
+
class BadRequestError extends APIError {
|
|
16007
|
+
}
|
|
16008
|
+
class AuthenticationError extends APIError {
|
|
16009
|
+
}
|
|
16010
|
+
class PermissionDeniedError extends APIError {
|
|
16011
|
+
}
|
|
16012
|
+
class NotFoundError extends APIError {
|
|
16013
|
+
}
|
|
16014
|
+
class ConflictError extends APIError {
|
|
16015
|
+
}
|
|
16016
|
+
class UnprocessableEntityError extends APIError {
|
|
16017
|
+
}
|
|
16018
|
+
class RateLimitError extends APIError {
|
|
16019
|
+
}
|
|
16020
|
+
class InternalServerError extends APIError {
|
|
16021
|
+
}
|
|
16022
|
+
|
|
16023
|
+
/**
|
|
16024
|
+
* @license
|
|
16025
|
+
* Copyright 2025 Google LLC
|
|
16026
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16027
|
+
*/
|
|
16028
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
16029
|
+
// https://url.spec.whatwg.org/#url-scheme-string
|
|
16030
|
+
const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
|
|
16031
|
+
const isAbsoluteURL = (url) => {
|
|
16032
|
+
return startsWithSchemeRegexp.test(url);
|
|
16033
|
+
};
|
|
16034
|
+
let isArrayInternal = (val) => ((isArrayInternal = Array.isArray), isArrayInternal(val));
|
|
16035
|
+
const isArray = isArrayInternal;
|
|
16036
|
+
let isReadonlyArrayInternal = isArray;
|
|
16037
|
+
const isReadonlyArray = isReadonlyArrayInternal;
|
|
16038
|
+
// https://stackoverflow.com/a/34491287
|
|
16039
|
+
function isEmptyObj(obj) {
|
|
16040
|
+
if (!obj)
|
|
16041
|
+
return true;
|
|
16042
|
+
for (const _k in obj)
|
|
16043
|
+
return false;
|
|
16044
|
+
return true;
|
|
16045
|
+
}
|
|
16046
|
+
// https://eslint.org/docs/latest/rules/no-prototype-builtins
|
|
16047
|
+
function hasOwn(obj, key) {
|
|
16048
|
+
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
16049
|
+
}
|
|
16050
|
+
const validatePositiveInteger = (name, n) => {
|
|
16051
|
+
if (typeof n !== 'number' || !Number.isInteger(n)) {
|
|
16052
|
+
throw new GeminiNextGenAPIClientError(`${name} must be an integer`);
|
|
15871
16053
|
}
|
|
15872
|
-
if (
|
|
15873
|
-
throw new
|
|
16054
|
+
if (n < 0) {
|
|
16055
|
+
throw new GeminiNextGenAPIClientError(`${name} must be a positive integer`);
|
|
15874
16056
|
}
|
|
15875
|
-
|
|
15876
|
-
|
|
15877
|
-
|
|
16057
|
+
return n;
|
|
16058
|
+
};
|
|
16059
|
+
const safeJSON = (text) => {
|
|
16060
|
+
try {
|
|
16061
|
+
return JSON.parse(text);
|
|
15878
16062
|
}
|
|
15879
|
-
|
|
15880
|
-
|
|
15881
|
-
]);
|
|
15882
|
-
if (fromLearningRateMultiplier != null) {
|
|
15883
|
-
setValueByPath(toObject, ['tuningTask', 'hyperparameters', 'learningRateMultiplier'], fromLearningRateMultiplier);
|
|
16063
|
+
catch (err) {
|
|
16064
|
+
return undefined;
|
|
15884
16065
|
}
|
|
15885
|
-
|
|
15886
|
-
|
|
15887
|
-
|
|
16066
|
+
};
|
|
16067
|
+
|
|
16068
|
+
/**
|
|
16069
|
+
* @license
|
|
16070
|
+
* Copyright 2025 Google LLC
|
|
16071
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16072
|
+
*/
|
|
16073
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
16074
|
+
const sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
16075
|
+
|
|
16076
|
+
/**
|
|
16077
|
+
* @license
|
|
16078
|
+
* Copyright 2025 Google LLC
|
|
16079
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16080
|
+
*/
|
|
16081
|
+
const VERSION = '0.0.1';
|
|
16082
|
+
|
|
16083
|
+
/**
|
|
16084
|
+
* @license
|
|
16085
|
+
* Copyright 2025 Google LLC
|
|
16086
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16087
|
+
*/
|
|
16088
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
16089
|
+
/**
|
|
16090
|
+
* Note this does not detect 'browser'; for that, use getBrowserInfo().
|
|
16091
|
+
*/
|
|
16092
|
+
function getDetectedPlatform() {
|
|
16093
|
+
if (typeof Deno !== 'undefined' && Deno.build != null) {
|
|
16094
|
+
return 'deno';
|
|
15888
16095
|
}
|
|
15889
|
-
if (
|
|
15890
|
-
|
|
15891
|
-
throw new Error('preTunedModelCheckpointId parameter is not supported in Gemini API.');
|
|
16096
|
+
if (typeof EdgeRuntime !== 'undefined') {
|
|
16097
|
+
return 'edge';
|
|
15892
16098
|
}
|
|
15893
|
-
if (
|
|
15894
|
-
|
|
16099
|
+
if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') {
|
|
16100
|
+
return 'node';
|
|
15895
16101
|
}
|
|
15896
|
-
|
|
15897
|
-
|
|
15898
|
-
|
|
16102
|
+
return 'unknown';
|
|
16103
|
+
}
|
|
16104
|
+
const getPlatformProperties = () => {
|
|
16105
|
+
var _a, _b, _c, _d, _e;
|
|
16106
|
+
const detectedPlatform = getDetectedPlatform();
|
|
16107
|
+
if (detectedPlatform === 'deno') {
|
|
16108
|
+
return {
|
|
16109
|
+
'X-Stainless-Lang': 'js',
|
|
16110
|
+
'X-Stainless-Package-Version': VERSION,
|
|
16111
|
+
'X-Stainless-OS': normalizePlatform(Deno.build.os),
|
|
16112
|
+
'X-Stainless-Arch': normalizeArch(Deno.build.arch),
|
|
16113
|
+
'X-Stainless-Runtime': 'deno',
|
|
16114
|
+
'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : (_b = (_a = Deno.version) === null || _a === void 0 ? void 0 : _a.deno) !== null && _b !== void 0 ? _b : 'unknown',
|
|
16115
|
+
};
|
|
15899
16116
|
}
|
|
15900
|
-
|
|
15901
|
-
|
|
15902
|
-
|
|
16117
|
+
if (typeof EdgeRuntime !== 'undefined') {
|
|
16118
|
+
return {
|
|
16119
|
+
'X-Stainless-Lang': 'js',
|
|
16120
|
+
'X-Stainless-Package-Version': VERSION,
|
|
16121
|
+
'X-Stainless-OS': 'Unknown',
|
|
16122
|
+
'X-Stainless-Arch': `other:${EdgeRuntime}`,
|
|
16123
|
+
'X-Stainless-Runtime': 'edge',
|
|
16124
|
+
'X-Stainless-Runtime-Version': globalThis.process.version,
|
|
16125
|
+
};
|
|
15903
16126
|
}
|
|
15904
|
-
|
|
15905
|
-
|
|
16127
|
+
// Check if Node.js
|
|
16128
|
+
if (detectedPlatform === 'node') {
|
|
16129
|
+
return {
|
|
16130
|
+
'X-Stainless-Lang': 'js',
|
|
16131
|
+
'X-Stainless-Package-Version': VERSION,
|
|
16132
|
+
'X-Stainless-OS': normalizePlatform((_c = globalThis.process.platform) !== null && _c !== void 0 ? _c : 'unknown'),
|
|
16133
|
+
'X-Stainless-Arch': normalizeArch((_d = globalThis.process.arch) !== null && _d !== void 0 ? _d : 'unknown'),
|
|
16134
|
+
'X-Stainless-Runtime': 'node',
|
|
16135
|
+
'X-Stainless-Runtime-Version': (_e = globalThis.process.version) !== null && _e !== void 0 ? _e : 'unknown',
|
|
16136
|
+
};
|
|
15906
16137
|
}
|
|
15907
|
-
|
|
15908
|
-
|
|
16138
|
+
const browserInfo = getBrowserInfo();
|
|
16139
|
+
if (browserInfo) {
|
|
16140
|
+
return {
|
|
16141
|
+
'X-Stainless-Lang': 'js',
|
|
16142
|
+
'X-Stainless-Package-Version': VERSION,
|
|
16143
|
+
'X-Stainless-OS': 'Unknown',
|
|
16144
|
+
'X-Stainless-Arch': 'unknown',
|
|
16145
|
+
'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
|
|
16146
|
+
'X-Stainless-Runtime-Version': browserInfo.version,
|
|
16147
|
+
};
|
|
15909
16148
|
}
|
|
15910
|
-
|
|
16149
|
+
// TODO add support for Cloudflare workers, etc.
|
|
16150
|
+
return {
|
|
16151
|
+
'X-Stainless-Lang': 'js',
|
|
16152
|
+
'X-Stainless-Package-Version': VERSION,
|
|
16153
|
+
'X-Stainless-OS': 'Unknown',
|
|
16154
|
+
'X-Stainless-Arch': 'unknown',
|
|
16155
|
+
'X-Stainless-Runtime': 'unknown',
|
|
16156
|
+
'X-Stainless-Runtime-Version': 'unknown',
|
|
16157
|
+
};
|
|
16158
|
+
};
|
|
16159
|
+
// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
|
|
16160
|
+
function getBrowserInfo() {
|
|
16161
|
+
if (typeof navigator === 'undefined' || !navigator) {
|
|
16162
|
+
return null;
|
|
16163
|
+
}
|
|
16164
|
+
// NOTE: The order matters here!
|
|
16165
|
+
const browserPatterns = [
|
|
16166
|
+
{ key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
16167
|
+
{ key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
16168
|
+
{ key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
16169
|
+
{ key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
16170
|
+
{ key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
16171
|
+
{ key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
|
|
16172
|
+
];
|
|
16173
|
+
// Find the FIRST matching browser
|
|
16174
|
+
for (const { key, pattern } of browserPatterns) {
|
|
16175
|
+
const match = pattern.exec(navigator.userAgent);
|
|
16176
|
+
if (match) {
|
|
16177
|
+
const major = match[1] || 0;
|
|
16178
|
+
const minor = match[2] || 0;
|
|
16179
|
+
const patch = match[3] || 0;
|
|
16180
|
+
return { browser: key, version: `${major}.${minor}.${patch}` };
|
|
16181
|
+
}
|
|
16182
|
+
}
|
|
16183
|
+
return null;
|
|
16184
|
+
}
|
|
16185
|
+
const normalizeArch = (arch) => {
|
|
16186
|
+
// Node docs:
|
|
16187
|
+
// - https://nodejs.org/api/process.html#processarch
|
|
16188
|
+
// Deno docs:
|
|
16189
|
+
// - https://doc.deno.land/deno/stable/~/Deno.build
|
|
16190
|
+
if (arch === 'x32')
|
|
16191
|
+
return 'x32';
|
|
16192
|
+
if (arch === 'x86_64' || arch === 'x64')
|
|
16193
|
+
return 'x64';
|
|
16194
|
+
if (arch === 'arm')
|
|
16195
|
+
return 'arm';
|
|
16196
|
+
if (arch === 'aarch64' || arch === 'arm64')
|
|
16197
|
+
return 'arm64';
|
|
16198
|
+
if (arch)
|
|
16199
|
+
return `other:${arch}`;
|
|
16200
|
+
return 'unknown';
|
|
16201
|
+
};
|
|
16202
|
+
const normalizePlatform = (platform) => {
|
|
16203
|
+
// Node platforms:
|
|
16204
|
+
// - https://nodejs.org/api/process.html#processplatform
|
|
16205
|
+
// Deno platforms:
|
|
16206
|
+
// - https://doc.deno.land/deno/stable/~/Deno.build
|
|
16207
|
+
// - https://github.com/denoland/deno/issues/14799
|
|
16208
|
+
platform = platform.toLowerCase();
|
|
16209
|
+
// NOTE: this iOS check is untested and may not work
|
|
16210
|
+
// Node does not work natively on IOS, there is a fork at
|
|
16211
|
+
// https://github.com/nodejs-mobile/nodejs-mobile
|
|
16212
|
+
// however it is unknown at the time of writing how to detect if it is running
|
|
16213
|
+
if (platform.includes('ios'))
|
|
16214
|
+
return 'iOS';
|
|
16215
|
+
if (platform === 'android')
|
|
16216
|
+
return 'Android';
|
|
16217
|
+
if (platform === 'darwin')
|
|
16218
|
+
return 'MacOS';
|
|
16219
|
+
if (platform === 'win32')
|
|
16220
|
+
return 'Windows';
|
|
16221
|
+
if (platform === 'freebsd')
|
|
16222
|
+
return 'FreeBSD';
|
|
16223
|
+
if (platform === 'openbsd')
|
|
16224
|
+
return 'OpenBSD';
|
|
16225
|
+
if (platform === 'linux')
|
|
16226
|
+
return 'Linux';
|
|
16227
|
+
if (platform)
|
|
16228
|
+
return `Other:${platform}`;
|
|
16229
|
+
return 'Unknown';
|
|
16230
|
+
};
|
|
16231
|
+
let _platformHeaders;
|
|
16232
|
+
const getPlatformHeaders = () => {
|
|
16233
|
+
return (_platformHeaders !== null && _platformHeaders !== void 0 ? _platformHeaders : (_platformHeaders = getPlatformProperties()));
|
|
16234
|
+
};
|
|
16235
|
+
|
|
16236
|
+
/**
|
|
16237
|
+
* @license
|
|
16238
|
+
* Copyright 2025 Google LLC
|
|
16239
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16240
|
+
*/
|
|
16241
|
+
function getDefaultFetch() {
|
|
16242
|
+
if (typeof fetch !== 'undefined') {
|
|
16243
|
+
return fetch;
|
|
16244
|
+
}
|
|
16245
|
+
throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`');
|
|
16246
|
+
}
|
|
16247
|
+
function makeReadableStream(...args) {
|
|
16248
|
+
const ReadableStream = globalThis.ReadableStream;
|
|
16249
|
+
if (typeof ReadableStream === 'undefined') {
|
|
16250
|
+
// Note: All of the platforms / runtimes we officially support already define
|
|
16251
|
+
// `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes.
|
|
16252
|
+
throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`');
|
|
16253
|
+
}
|
|
16254
|
+
return new ReadableStream(...args);
|
|
16255
|
+
}
|
|
16256
|
+
function ReadableStreamFrom(iterable) {
|
|
16257
|
+
let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
|
|
16258
|
+
return makeReadableStream({
|
|
16259
|
+
start() { },
|
|
16260
|
+
async pull(controller) {
|
|
16261
|
+
const { done, value } = await iter.next();
|
|
16262
|
+
if (done) {
|
|
16263
|
+
controller.close();
|
|
16264
|
+
}
|
|
16265
|
+
else {
|
|
16266
|
+
controller.enqueue(value);
|
|
16267
|
+
}
|
|
16268
|
+
},
|
|
16269
|
+
async cancel() {
|
|
16270
|
+
var _a;
|
|
16271
|
+
await ((_a = iter.return) === null || _a === void 0 ? void 0 : _a.call(iter));
|
|
16272
|
+
},
|
|
16273
|
+
});
|
|
15911
16274
|
}
|
|
15912
|
-
|
|
15913
|
-
|
|
15914
|
-
|
|
15915
|
-
|
|
15916
|
-
|
|
15917
|
-
|
|
15918
|
-
|
|
15919
|
-
|
|
15920
|
-
|
|
15921
|
-
|
|
15922
|
-
|
|
15923
|
-
|
|
15924
|
-
|
|
15925
|
-
|
|
15926
|
-
|
|
15927
|
-
|
|
16275
|
+
/**
|
|
16276
|
+
* Most browsers don't yet have async iterable support for ReadableStream,
|
|
16277
|
+
* and Node has a very different way of reading bytes from its "ReadableStream".
|
|
16278
|
+
*
|
|
16279
|
+
* This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
|
|
16280
|
+
*/
|
|
16281
|
+
function ReadableStreamToAsyncIterable(stream) {
|
|
16282
|
+
if (stream[Symbol.asyncIterator])
|
|
16283
|
+
return stream;
|
|
16284
|
+
const reader = stream.getReader();
|
|
16285
|
+
return {
|
|
16286
|
+
async next() {
|
|
16287
|
+
try {
|
|
16288
|
+
const result = await reader.read();
|
|
16289
|
+
if (result === null || result === void 0 ? void 0 : result.done)
|
|
16290
|
+
reader.releaseLock(); // release lock when stream becomes closed
|
|
16291
|
+
return result;
|
|
16292
|
+
}
|
|
16293
|
+
catch (e) {
|
|
16294
|
+
reader.releaseLock(); // release lock when stream becomes errored
|
|
16295
|
+
throw e;
|
|
16296
|
+
}
|
|
16297
|
+
},
|
|
16298
|
+
async return() {
|
|
16299
|
+
const cancelPromise = reader.cancel();
|
|
16300
|
+
reader.releaseLock();
|
|
16301
|
+
await cancelPromise;
|
|
16302
|
+
return { done: true, value: undefined };
|
|
16303
|
+
},
|
|
16304
|
+
[Symbol.asyncIterator]() {
|
|
16305
|
+
return this;
|
|
16306
|
+
},
|
|
16307
|
+
};
|
|
16308
|
+
}
|
|
16309
|
+
/**
|
|
16310
|
+
* Cancels a ReadableStream we don't need to consume.
|
|
16311
|
+
* See https://undici.nodejs.org/#/?id=garbage-collection
|
|
16312
|
+
*/
|
|
16313
|
+
async function CancelReadableStream(stream) {
|
|
16314
|
+
var _a, _b;
|
|
16315
|
+
if (stream === null || typeof stream !== 'object')
|
|
16316
|
+
return;
|
|
16317
|
+
if (stream[Symbol.asyncIterator]) {
|
|
16318
|
+
await ((_b = (_a = stream[Symbol.asyncIterator]()).return) === null || _b === void 0 ? void 0 : _b.call(_a));
|
|
16319
|
+
return;
|
|
15928
16320
|
}
|
|
15929
|
-
|
|
15930
|
-
|
|
15931
|
-
|
|
15932
|
-
|
|
16321
|
+
const reader = stream.getReader();
|
|
16322
|
+
const cancelPromise = reader.cancel();
|
|
16323
|
+
reader.releaseLock();
|
|
16324
|
+
await cancelPromise;
|
|
16325
|
+
}
|
|
16326
|
+
|
|
16327
|
+
/**
|
|
16328
|
+
* @license
|
|
16329
|
+
* Copyright 2025 Google LLC
|
|
16330
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16331
|
+
*/
|
|
16332
|
+
const FallbackEncoder = ({ headers, body }) => {
|
|
16333
|
+
return {
|
|
16334
|
+
bodyHeaders: {
|
|
16335
|
+
'content-type': 'application/json',
|
|
16336
|
+
},
|
|
16337
|
+
body: JSON.stringify(body),
|
|
16338
|
+
};
|
|
16339
|
+
};
|
|
16340
|
+
|
|
16341
|
+
/**
|
|
16342
|
+
* @license
|
|
16343
|
+
* Copyright 2025 Google LLC
|
|
16344
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16345
|
+
*/
|
|
16346
|
+
const checkFileSupport = () => {
|
|
16347
|
+
var _a;
|
|
16348
|
+
if (typeof File === 'undefined') {
|
|
16349
|
+
const { process } = globalThis;
|
|
16350
|
+
const isOldNode = typeof ((_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) === 'string' && parseInt(process.versions.node.split('.')) < 20;
|
|
16351
|
+
throw new Error('`File` is not defined as a global, which is required for file uploads.' +
|
|
16352
|
+
(isOldNode ?
|
|
16353
|
+
" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`."
|
|
16354
|
+
: ''));
|
|
16355
|
+
}
|
|
16356
|
+
};
|
|
16357
|
+
/**
|
|
16358
|
+
* Construct a `File` instance. This is used to ensure a helpful error is thrown
|
|
16359
|
+
* for environments that don't define a global `File` yet.
|
|
16360
|
+
*/
|
|
16361
|
+
function makeFile(fileBits, fileName, options) {
|
|
16362
|
+
checkFileSupport();
|
|
16363
|
+
return new File(fileBits, fileName !== null && fileName !== void 0 ? fileName : 'unknown_file', options);
|
|
16364
|
+
}
|
|
16365
|
+
function getName(value) {
|
|
16366
|
+
return (((typeof value === 'object' &&
|
|
16367
|
+
value !== null &&
|
|
16368
|
+
(('name' in value && value.name && String(value.name)) ||
|
|
16369
|
+
('url' in value && value.url && String(value.url)) ||
|
|
16370
|
+
('filename' in value && value.filename && String(value.filename)) ||
|
|
16371
|
+
('path' in value && value.path && String(value.path)))) ||
|
|
16372
|
+
'')
|
|
16373
|
+
.split(/[\\/]/)
|
|
16374
|
+
.pop() || undefined);
|
|
16375
|
+
}
|
|
16376
|
+
const isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';
|
|
16377
|
+
|
|
16378
|
+
/**
|
|
16379
|
+
* @license
|
|
16380
|
+
* Copyright 2025 Google LLC
|
|
16381
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16382
|
+
*/
|
|
16383
|
+
/**
|
|
16384
|
+
* This check adds the arrayBuffer() method type because it is available and used at runtime
|
|
16385
|
+
*/
|
|
16386
|
+
const isBlobLike = (value) => value != null &&
|
|
16387
|
+
typeof value === 'object' &&
|
|
16388
|
+
typeof value.size === 'number' &&
|
|
16389
|
+
typeof value.type === 'string' &&
|
|
16390
|
+
typeof value.text === 'function' &&
|
|
16391
|
+
typeof value.slice === 'function' &&
|
|
16392
|
+
typeof value.arrayBuffer === 'function';
|
|
16393
|
+
/**
|
|
16394
|
+
* This check adds the arrayBuffer() method type because it is available and used at runtime
|
|
16395
|
+
*/
|
|
16396
|
+
const isFileLike = (value) => value != null &&
|
|
16397
|
+
typeof value === 'object' &&
|
|
16398
|
+
typeof value.name === 'string' &&
|
|
16399
|
+
typeof value.lastModified === 'number' &&
|
|
16400
|
+
isBlobLike(value);
|
|
16401
|
+
const isResponseLike = (value) => value != null &&
|
|
16402
|
+
typeof value === 'object' &&
|
|
16403
|
+
typeof value.url === 'string' &&
|
|
16404
|
+
typeof value.blob === 'function';
|
|
16405
|
+
/**
|
|
16406
|
+
* Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats
|
|
16407
|
+
* @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts
|
|
16408
|
+
* @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible
|
|
16409
|
+
* @param {Object=} options additional properties
|
|
16410
|
+
* @param {string=} options.type the MIME type of the content
|
|
16411
|
+
* @param {number=} options.lastModified the last modified timestamp
|
|
16412
|
+
* @returns a {@link File} with the given properties
|
|
16413
|
+
*/
|
|
16414
|
+
async function toFile(value, name, options) {
|
|
16415
|
+
checkFileSupport();
|
|
16416
|
+
// If it's a promise, resolve it.
|
|
16417
|
+
value = await value;
|
|
16418
|
+
// If we've been given a `File` we don't need to do anything
|
|
16419
|
+
if (isFileLike(value)) {
|
|
16420
|
+
if (value instanceof File) {
|
|
16421
|
+
return value;
|
|
16422
|
+
}
|
|
16423
|
+
return makeFile([await value.arrayBuffer()], value.name);
|
|
16424
|
+
}
|
|
16425
|
+
if (isResponseLike(value)) {
|
|
16426
|
+
const blob = await value.blob();
|
|
16427
|
+
name || (name = new URL(value.url).pathname.split(/[\\/]/).pop());
|
|
16428
|
+
return makeFile(await getBytes(blob), name, options);
|
|
16429
|
+
}
|
|
16430
|
+
const parts = await getBytes(value);
|
|
16431
|
+
name || (name = getName(value));
|
|
16432
|
+
if (!(options === null || options === void 0 ? void 0 : options.type)) {
|
|
16433
|
+
const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type);
|
|
16434
|
+
if (typeof type === 'string') {
|
|
16435
|
+
options = Object.assign(Object.assign({}, options), { type });
|
|
16436
|
+
}
|
|
16437
|
+
}
|
|
16438
|
+
return makeFile(parts, name, options);
|
|
16439
|
+
}
|
|
16440
|
+
async function getBytes(value) {
|
|
16441
|
+
var _a, e_1, _b, _c;
|
|
16442
|
+
var _d;
|
|
16443
|
+
let parts = [];
|
|
16444
|
+
if (typeof value === 'string' ||
|
|
16445
|
+
ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
|
|
16446
|
+
value instanceof ArrayBuffer) {
|
|
16447
|
+
parts.push(value);
|
|
16448
|
+
}
|
|
16449
|
+
else if (isBlobLike(value)) {
|
|
16450
|
+
parts.push(value instanceof Blob ? value : await value.arrayBuffer());
|
|
16451
|
+
}
|
|
16452
|
+
else if (isAsyncIterable(value) // includes Readable, ReadableStream, etc.
|
|
16453
|
+
) {
|
|
16454
|
+
try {
|
|
16455
|
+
for (var _e = true, value_1 = __asyncValues(value), value_1_1; value_1_1 = await value_1.next(), _a = value_1_1.done, !_a; _e = true) {
|
|
16456
|
+
_c = value_1_1.value;
|
|
16457
|
+
_e = false;
|
|
16458
|
+
const chunk = _c;
|
|
16459
|
+
parts.push(...(await getBytes(chunk))); // TODO, consider validating?
|
|
16460
|
+
}
|
|
16461
|
+
}
|
|
16462
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
16463
|
+
finally {
|
|
16464
|
+
try {
|
|
16465
|
+
if (!_e && !_a && (_b = value_1.return)) await _b.call(value_1);
|
|
16466
|
+
}
|
|
16467
|
+
finally { if (e_1) throw e_1.error; }
|
|
16468
|
+
}
|
|
16469
|
+
}
|
|
16470
|
+
else {
|
|
16471
|
+
const constructor = (_d = value === null || value === void 0 ? void 0 : value.constructor) === null || _d === void 0 ? void 0 : _d.name;
|
|
16472
|
+
throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${propsForError(value)}`);
|
|
16473
|
+
}
|
|
16474
|
+
return parts;
|
|
16475
|
+
}
|
|
16476
|
+
function propsForError(value) {
|
|
16477
|
+
if (typeof value !== 'object' || value === null)
|
|
16478
|
+
return '';
|
|
16479
|
+
const props = Object.getOwnPropertyNames(value);
|
|
16480
|
+
return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`;
|
|
16481
|
+
}
|
|
16482
|
+
|
|
16483
|
+
/**
|
|
16484
|
+
* @license
|
|
16485
|
+
* Copyright 2025 Google LLC
|
|
16486
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16487
|
+
*/
|
|
16488
|
+
class APIResource {
|
|
16489
|
+
constructor(client) {
|
|
16490
|
+
this._client = client;
|
|
16491
|
+
}
|
|
16492
|
+
}
|
|
16493
|
+
/**
|
|
16494
|
+
* The key path from the client. For example, a resource accessible as `client.resource.subresource` would
|
|
16495
|
+
* have a property `static override readonly _key = Object.freeze(['resource', 'subresource'] as const);`.
|
|
16496
|
+
*/
|
|
16497
|
+
APIResource._key = [];
|
|
16498
|
+
|
|
16499
|
+
/**
|
|
16500
|
+
* @license
|
|
16501
|
+
* Copyright 2025 Google LLC
|
|
16502
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16503
|
+
*/
|
|
16504
|
+
/**
|
|
16505
|
+
* Percent-encode everything that isn't safe to have in a path without encoding safe chars.
|
|
16506
|
+
*
|
|
16507
|
+
* Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3:
|
|
16508
|
+
* > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
|
|
16509
|
+
* > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
|
|
16510
|
+
* > pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
|
|
16511
|
+
*/
|
|
16512
|
+
function encodeURIPath(str) {
|
|
16513
|
+
return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
|
|
16514
|
+
}
|
|
16515
|
+
const EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
|
|
16516
|
+
const createPathTagFunction = (pathEncoder = encodeURIPath) => (function path(statics, ...params) {
|
|
16517
|
+
// If there are no params, no processing is needed.
|
|
16518
|
+
if (statics.length === 1)
|
|
16519
|
+
return statics[0];
|
|
16520
|
+
let postPath = false;
|
|
16521
|
+
const invalidSegments = [];
|
|
16522
|
+
const path = statics.reduce((previousValue, currentValue, index) => {
|
|
16523
|
+
var _a, _b, _c;
|
|
16524
|
+
if (/[?#]/.test(currentValue)) {
|
|
16525
|
+
postPath = true;
|
|
16526
|
+
}
|
|
16527
|
+
const value = params[index];
|
|
16528
|
+
let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value);
|
|
16529
|
+
if (index !== params.length &&
|
|
16530
|
+
(value == null ||
|
|
16531
|
+
(typeof value === 'object' &&
|
|
16532
|
+
// handle values from other realms
|
|
16533
|
+
value.toString ===
|
|
16534
|
+
((_c = Object.getPrototypeOf((_b = Object.getPrototypeOf((_a = value.hasOwnProperty) !== null && _a !== void 0 ? _a : EMPTY)) !== null && _b !== void 0 ? _b : EMPTY)) === null || _c === void 0 ? void 0 : _c.toString)))) {
|
|
16535
|
+
encoded = value + '';
|
|
16536
|
+
invalidSegments.push({
|
|
16537
|
+
start: previousValue.length + currentValue.length,
|
|
16538
|
+
length: encoded.length,
|
|
16539
|
+
error: `Value of type ${Object.prototype.toString
|
|
16540
|
+
.call(value)
|
|
16541
|
+
.slice(8, -1)} is not a valid path parameter`,
|
|
16542
|
+
});
|
|
16543
|
+
}
|
|
16544
|
+
return previousValue + currentValue + (index === params.length ? '' : encoded);
|
|
16545
|
+
}, '');
|
|
16546
|
+
const pathOnly = path.split(/[?#]/, 1)[0];
|
|
16547
|
+
const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
|
|
16548
|
+
let match;
|
|
16549
|
+
// Find all invalid segments
|
|
16550
|
+
while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
|
|
16551
|
+
invalidSegments.push({
|
|
16552
|
+
start: match.index,
|
|
16553
|
+
length: match[0].length,
|
|
16554
|
+
error: `Value "${match[0]}" can\'t be safely passed as a path parameter`,
|
|
16555
|
+
});
|
|
16556
|
+
}
|
|
16557
|
+
invalidSegments.sort((a, b) => a.start - b.start);
|
|
16558
|
+
if (invalidSegments.length > 0) {
|
|
16559
|
+
let lastEnd = 0;
|
|
16560
|
+
const underline = invalidSegments.reduce((acc, segment) => {
|
|
16561
|
+
const spaces = ' '.repeat(segment.start - lastEnd);
|
|
16562
|
+
const arrows = '^'.repeat(segment.length);
|
|
16563
|
+
lastEnd = segment.start + segment.length;
|
|
16564
|
+
return acc + spaces + arrows;
|
|
16565
|
+
}, '');
|
|
16566
|
+
throw new GeminiNextGenAPIClientError(`Path parameters result in path with invalid segments:\n${invalidSegments
|
|
16567
|
+
.map((e) => e.error)
|
|
16568
|
+
.join('\n')}\n${path}\n${underline}`);
|
|
16569
|
+
}
|
|
16570
|
+
return path;
|
|
16571
|
+
});
|
|
16572
|
+
/**
|
|
16573
|
+
* URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced.
|
|
16574
|
+
*/
|
|
16575
|
+
const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath);
|
|
16576
|
+
|
|
16577
|
+
/**
|
|
16578
|
+
* @license
|
|
16579
|
+
* Copyright 2025 Google LLC
|
|
16580
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16581
|
+
*/
|
|
16582
|
+
class BaseInteractions extends APIResource {
|
|
16583
|
+
create(params, options) {
|
|
16584
|
+
var _a;
|
|
16585
|
+
const { api_version = this._client.apiVersion } = params, body = __rest(params, ["api_version"]);
|
|
16586
|
+
if ('model' in body && 'agent_config' in body) {
|
|
16587
|
+
throw new GeminiNextGenAPIClientError(`Invalid request: specified \`model\` and \`agent_config\`. If specifying \`model\`, use \`generation_config\`.`);
|
|
16588
|
+
}
|
|
16589
|
+
if ('agent' in body && 'generation_config' in body) {
|
|
16590
|
+
throw new GeminiNextGenAPIClientError(`Invalid request: specified \`agent\` and \`generation_config\`. If specifying \`agent\`, use \`agent_config\`.`);
|
|
16591
|
+
}
|
|
16592
|
+
return this._client.post(path `/${api_version}/interactions`, Object.assign(Object.assign({ body }, options), { stream: (_a = params.stream) !== null && _a !== void 0 ? _a : false }));
|
|
16593
|
+
}
|
|
16594
|
+
/**
|
|
16595
|
+
* Deletes the interaction by id.
|
|
16596
|
+
*
|
|
16597
|
+
* @example
|
|
16598
|
+
* ```ts
|
|
16599
|
+
* const interaction = await client.interactions.delete('id');
|
|
16600
|
+
* ```
|
|
16601
|
+
*/
|
|
16602
|
+
delete(id, params = {}, options) {
|
|
16603
|
+
const { api_version = this._client.apiVersion } = params !== null && params !== void 0 ? params : {};
|
|
16604
|
+
return this._client.delete(path `/${api_version}/interactions/${id}`, options);
|
|
16605
|
+
}
|
|
16606
|
+
/**
|
|
16607
|
+
* Cancels an interaction by id. This only applies to background interactions that are still running.
|
|
16608
|
+
*
|
|
16609
|
+
* @example
|
|
16610
|
+
* ```ts
|
|
16611
|
+
* const interaction = await client.interactions.cancel('id');
|
|
16612
|
+
* ```
|
|
16613
|
+
*/
|
|
16614
|
+
cancel(id, params = {}, options) {
|
|
16615
|
+
const { api_version = this._client.apiVersion } = params !== null && params !== void 0 ? params : {};
|
|
16616
|
+
return this._client.post(path `/${api_version}/interactions/${id}/cancel`, options);
|
|
16617
|
+
}
|
|
16618
|
+
get(id, params = {}, options) {
|
|
16619
|
+
var _a;
|
|
16620
|
+
const _b = params !== null && params !== void 0 ? params : {}, { api_version = this._client.apiVersion } = _b, query = __rest(_b, ["api_version"]);
|
|
16621
|
+
return this._client.get(path `/${api_version}/interactions/${id}`, Object.assign(Object.assign({ query }, options), { stream: (_a = params === null || params === void 0 ? void 0 : params.stream) !== null && _a !== void 0 ? _a : false }));
|
|
16622
|
+
}
|
|
16623
|
+
}
|
|
16624
|
+
BaseInteractions._key = Object.freeze(['interactions']);
|
|
16625
|
+
class Interactions extends BaseInteractions {
|
|
16626
|
+
}
|
|
16627
|
+
|
|
16628
|
+
/**
|
|
16629
|
+
* @license
|
|
16630
|
+
* Copyright 2025 Google LLC
|
|
16631
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16632
|
+
*/
|
|
16633
|
+
function concatBytes(buffers) {
|
|
16634
|
+
let length = 0;
|
|
16635
|
+
for (const buffer of buffers) {
|
|
16636
|
+
length += buffer.length;
|
|
16637
|
+
}
|
|
16638
|
+
const output = new Uint8Array(length);
|
|
16639
|
+
let index = 0;
|
|
16640
|
+
for (const buffer of buffers) {
|
|
16641
|
+
output.set(buffer, index);
|
|
16642
|
+
index += buffer.length;
|
|
16643
|
+
}
|
|
16644
|
+
return output;
|
|
16645
|
+
}
|
|
16646
|
+
let encodeUTF8_;
|
|
16647
|
+
function encodeUTF8(str) {
|
|
16648
|
+
let encoder;
|
|
16649
|
+
return (encodeUTF8_ !== null && encodeUTF8_ !== void 0 ? encodeUTF8_ : ((encoder = new globalThis.TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))))(str);
|
|
16650
|
+
}
|
|
16651
|
+
let decodeUTF8_;
|
|
16652
|
+
function decodeUTF8(bytes) {
|
|
16653
|
+
let decoder;
|
|
16654
|
+
return (decodeUTF8_ !== null && decodeUTF8_ !== void 0 ? decodeUTF8_ : ((decoder = new globalThis.TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))))(bytes);
|
|
16655
|
+
}
|
|
16656
|
+
|
|
16657
|
+
/**
|
|
16658
|
+
* @license
|
|
16659
|
+
* Copyright 2025 Google LLC
|
|
16660
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16661
|
+
*/
|
|
16662
|
+
/**
|
|
16663
|
+
* A re-implementation of httpx's `LineDecoder` in Python that handles incrementally
|
|
16664
|
+
* reading lines from text.
|
|
16665
|
+
*
|
|
16666
|
+
* https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258
|
|
16667
|
+
*/
|
|
16668
|
+
class LineDecoder {
|
|
16669
|
+
constructor() {
|
|
16670
|
+
this.buffer = new Uint8Array();
|
|
16671
|
+
this.carriageReturnIndex = null;
|
|
16672
|
+
}
|
|
16673
|
+
decode(chunk) {
|
|
16674
|
+
if (chunk == null) {
|
|
16675
|
+
return [];
|
|
16676
|
+
}
|
|
16677
|
+
const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
|
|
16678
|
+
: typeof chunk === 'string' ? encodeUTF8(chunk)
|
|
16679
|
+
: chunk;
|
|
16680
|
+
this.buffer = concatBytes([this.buffer, binaryChunk]);
|
|
16681
|
+
const lines = [];
|
|
16682
|
+
let patternIndex;
|
|
16683
|
+
while ((patternIndex = findNewlineIndex(this.buffer, this.carriageReturnIndex)) != null) {
|
|
16684
|
+
if (patternIndex.carriage && this.carriageReturnIndex == null) {
|
|
16685
|
+
// skip until we either get a corresponding `\n`, a new `\r` or nothing
|
|
16686
|
+
this.carriageReturnIndex = patternIndex.index;
|
|
16687
|
+
continue;
|
|
16688
|
+
}
|
|
16689
|
+
// we got double \r or \rtext\n
|
|
16690
|
+
if (this.carriageReturnIndex != null &&
|
|
16691
|
+
(patternIndex.index !== this.carriageReturnIndex + 1 || patternIndex.carriage)) {
|
|
16692
|
+
lines.push(decodeUTF8(this.buffer.subarray(0, this.carriageReturnIndex - 1)));
|
|
16693
|
+
this.buffer = this.buffer.subarray(this.carriageReturnIndex);
|
|
16694
|
+
this.carriageReturnIndex = null;
|
|
16695
|
+
continue;
|
|
16696
|
+
}
|
|
16697
|
+
const endIndex = this.carriageReturnIndex !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
|
|
16698
|
+
const line = decodeUTF8(this.buffer.subarray(0, endIndex));
|
|
16699
|
+
lines.push(line);
|
|
16700
|
+
this.buffer = this.buffer.subarray(patternIndex.index);
|
|
16701
|
+
this.carriageReturnIndex = null;
|
|
16702
|
+
}
|
|
16703
|
+
return lines;
|
|
16704
|
+
}
|
|
16705
|
+
flush() {
|
|
16706
|
+
if (!this.buffer.length) {
|
|
16707
|
+
return [];
|
|
16708
|
+
}
|
|
16709
|
+
return this.decode('\n');
|
|
16710
|
+
}
|
|
16711
|
+
}
|
|
16712
|
+
// prettier-ignore
|
|
16713
|
+
LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']);
|
|
16714
|
+
LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
|
|
16715
|
+
/**
|
|
16716
|
+
* This function searches the buffer for the end patterns, (\r or \n)
|
|
16717
|
+
* and returns an object with the index preceding the matched newline and the
|
|
16718
|
+
* index after the newline char. `null` is returned if no new line is found.
|
|
16719
|
+
*
|
|
16720
|
+
* ```ts
|
|
16721
|
+
* findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 }
|
|
16722
|
+
* ```
|
|
16723
|
+
*/
|
|
16724
|
+
function findNewlineIndex(buffer, startIndex) {
|
|
16725
|
+
const newline = 0x0a; // \n
|
|
16726
|
+
const carriage = 0x0d; // \r
|
|
16727
|
+
for (let i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < buffer.length; i++) {
|
|
16728
|
+
if (buffer[i] === newline) {
|
|
16729
|
+
return { preceding: i, index: i + 1, carriage: false };
|
|
16730
|
+
}
|
|
16731
|
+
if (buffer[i] === carriage) {
|
|
16732
|
+
return { preceding: i, index: i + 1, carriage: true };
|
|
16733
|
+
}
|
|
16734
|
+
}
|
|
16735
|
+
return null;
|
|
16736
|
+
}
|
|
16737
|
+
function findDoubleNewlineIndex(buffer) {
|
|
16738
|
+
// This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n)
|
|
16739
|
+
// and returns the index right after the first occurrence of any pattern,
|
|
16740
|
+
// or -1 if none of the patterns are found.
|
|
16741
|
+
const newline = 0x0a; // \n
|
|
16742
|
+
const carriage = 0x0d; // \r
|
|
16743
|
+
for (let i = 0; i < buffer.length - 1; i++) {
|
|
16744
|
+
if (buffer[i] === newline && buffer[i + 1] === newline) {
|
|
16745
|
+
// \n\n
|
|
16746
|
+
return i + 2;
|
|
16747
|
+
}
|
|
16748
|
+
if (buffer[i] === carriage && buffer[i + 1] === carriage) {
|
|
16749
|
+
// \r\r
|
|
16750
|
+
return i + 2;
|
|
16751
|
+
}
|
|
16752
|
+
if (buffer[i] === carriage &&
|
|
16753
|
+
buffer[i + 1] === newline &&
|
|
16754
|
+
i + 3 < buffer.length &&
|
|
16755
|
+
buffer[i + 2] === carriage &&
|
|
16756
|
+
buffer[i + 3] === newline) {
|
|
16757
|
+
// \r\n\r\n
|
|
16758
|
+
return i + 4;
|
|
16759
|
+
}
|
|
16760
|
+
}
|
|
16761
|
+
return -1;
|
|
16762
|
+
}
|
|
16763
|
+
|
|
16764
|
+
/**
|
|
16765
|
+
* @license
|
|
16766
|
+
* Copyright 2025 Google LLC
|
|
16767
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16768
|
+
*/
|
|
16769
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
16770
|
+
const levelNumbers = {
|
|
16771
|
+
off: 0,
|
|
16772
|
+
error: 200,
|
|
16773
|
+
warn: 300,
|
|
16774
|
+
info: 400,
|
|
16775
|
+
debug: 500,
|
|
16776
|
+
};
|
|
16777
|
+
const parseLogLevel = (maybeLevel, sourceName, client) => {
|
|
16778
|
+
if (!maybeLevel) {
|
|
16779
|
+
return undefined;
|
|
16780
|
+
}
|
|
16781
|
+
if (hasOwn(levelNumbers, maybeLevel)) {
|
|
16782
|
+
return maybeLevel;
|
|
16783
|
+
}
|
|
16784
|
+
loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);
|
|
16785
|
+
return undefined;
|
|
16786
|
+
};
|
|
16787
|
+
function noop() { }
|
|
16788
|
+
function makeLogFn(fnLevel, logger, logLevel) {
|
|
16789
|
+
if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) {
|
|
16790
|
+
return noop;
|
|
16791
|
+
}
|
|
16792
|
+
else {
|
|
16793
|
+
// Don't wrap logger functions, we want the stacktrace intact!
|
|
16794
|
+
return logger[fnLevel].bind(logger);
|
|
16795
|
+
}
|
|
16796
|
+
}
|
|
16797
|
+
const noopLogger = {
|
|
16798
|
+
error: noop,
|
|
16799
|
+
warn: noop,
|
|
16800
|
+
info: noop,
|
|
16801
|
+
debug: noop,
|
|
16802
|
+
};
|
|
16803
|
+
let cachedLoggers = /* @__PURE__ */ new WeakMap();
|
|
16804
|
+
function loggerFor(client) {
|
|
16805
|
+
var _a;
|
|
16806
|
+
const logger = client.logger;
|
|
16807
|
+
const logLevel = (_a = client.logLevel) !== null && _a !== void 0 ? _a : 'off';
|
|
16808
|
+
if (!logger) {
|
|
16809
|
+
return noopLogger;
|
|
16810
|
+
}
|
|
16811
|
+
const cachedLogger = cachedLoggers.get(logger);
|
|
16812
|
+
if (cachedLogger && cachedLogger[0] === logLevel) {
|
|
16813
|
+
return cachedLogger[1];
|
|
16814
|
+
}
|
|
16815
|
+
const levelLogger = {
|
|
16816
|
+
error: makeLogFn('error', logger, logLevel),
|
|
16817
|
+
warn: makeLogFn('warn', logger, logLevel),
|
|
16818
|
+
info: makeLogFn('info', logger, logLevel),
|
|
16819
|
+
debug: makeLogFn('debug', logger, logLevel),
|
|
16820
|
+
};
|
|
16821
|
+
cachedLoggers.set(logger, [logLevel, levelLogger]);
|
|
16822
|
+
return levelLogger;
|
|
16823
|
+
}
|
|
16824
|
+
const formatRequestDetails = (details) => {
|
|
16825
|
+
if (details.options) {
|
|
16826
|
+
details.options = Object.assign({}, details.options);
|
|
16827
|
+
delete details.options['headers']; // redundant + leaks internals
|
|
16828
|
+
}
|
|
16829
|
+
if (details.headers) {
|
|
16830
|
+
details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [
|
|
16831
|
+
name,
|
|
16832
|
+
(name.toLowerCase() === 'x-goog-api-key' ||
|
|
16833
|
+
name.toLowerCase() === 'authorization' ||
|
|
16834
|
+
name.toLowerCase() === 'cookie' ||
|
|
16835
|
+
name.toLowerCase() === 'set-cookie') ?
|
|
16836
|
+
'***'
|
|
16837
|
+
: value,
|
|
16838
|
+
]));
|
|
16839
|
+
}
|
|
16840
|
+
if ('retryOfRequestLogID' in details) {
|
|
16841
|
+
if (details.retryOfRequestLogID) {
|
|
16842
|
+
details.retryOf = details.retryOfRequestLogID;
|
|
16843
|
+
}
|
|
16844
|
+
delete details.retryOfRequestLogID;
|
|
16845
|
+
}
|
|
16846
|
+
return details;
|
|
16847
|
+
};
|
|
16848
|
+
|
|
16849
|
+
/**
|
|
16850
|
+
* @license
|
|
16851
|
+
* Copyright 2025 Google LLC
|
|
16852
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16853
|
+
*/
|
|
16854
|
+
class Stream {
|
|
16855
|
+
constructor(iterator, controller, client) {
|
|
16856
|
+
this.iterator = iterator;
|
|
16857
|
+
this.controller = controller;
|
|
16858
|
+
this.client = client;
|
|
16859
|
+
}
|
|
16860
|
+
static fromSSEResponse(response, controller, client) {
|
|
16861
|
+
let consumed = false;
|
|
16862
|
+
const logger = client ? loggerFor(client) : console;
|
|
16863
|
+
function iterator() {
|
|
16864
|
+
return __asyncGenerator(this, arguments, function* iterator_1() {
|
|
16865
|
+
var _a, e_1, _b, _c;
|
|
16866
|
+
if (consumed) {
|
|
16867
|
+
throw new GeminiNextGenAPIClientError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
|
|
16868
|
+
}
|
|
16869
|
+
consumed = true;
|
|
16870
|
+
let done = false;
|
|
16871
|
+
try {
|
|
16872
|
+
try {
|
|
16873
|
+
for (var _d = true, _e = __asyncValues(_iterSSEMessages(response, controller)), _f; _f = yield __await(_e.next()), _a = _f.done, !_a; _d = true) {
|
|
16874
|
+
_c = _f.value;
|
|
16875
|
+
_d = false;
|
|
16876
|
+
const sse = _c;
|
|
16877
|
+
if (done)
|
|
16878
|
+
continue;
|
|
16879
|
+
if (sse.data.startsWith('[DONE]')) {
|
|
16880
|
+
done = true;
|
|
16881
|
+
continue;
|
|
16882
|
+
}
|
|
16883
|
+
else {
|
|
16884
|
+
try {
|
|
16885
|
+
// @ts-ignore
|
|
16886
|
+
yield yield __await(JSON.parse(sse.data));
|
|
16887
|
+
}
|
|
16888
|
+
catch (e) {
|
|
16889
|
+
logger.error(`Could not parse message into JSON:`, sse.data);
|
|
16890
|
+
logger.error(`From chunk:`, sse.raw);
|
|
16891
|
+
throw e;
|
|
16892
|
+
}
|
|
16893
|
+
}
|
|
16894
|
+
}
|
|
16895
|
+
}
|
|
16896
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
16897
|
+
finally {
|
|
16898
|
+
try {
|
|
16899
|
+
if (!_d && !_a && (_b = _e.return)) yield __await(_b.call(_e));
|
|
16900
|
+
}
|
|
16901
|
+
finally { if (e_1) throw e_1.error; }
|
|
16902
|
+
}
|
|
16903
|
+
done = true;
|
|
16904
|
+
}
|
|
16905
|
+
catch (e) {
|
|
16906
|
+
// If the user calls `stream.controller.abort()`, we should exit without throwing.
|
|
16907
|
+
if (isAbortError(e))
|
|
16908
|
+
return yield __await(void 0);
|
|
16909
|
+
throw e;
|
|
16910
|
+
}
|
|
16911
|
+
finally {
|
|
16912
|
+
// If the user `break`s, abort the ongoing request.
|
|
16913
|
+
if (!done)
|
|
16914
|
+
controller.abort();
|
|
16915
|
+
}
|
|
16916
|
+
});
|
|
16917
|
+
}
|
|
16918
|
+
return new Stream(iterator, controller, client);
|
|
16919
|
+
}
|
|
16920
|
+
/**
|
|
16921
|
+
* Generates a Stream from a newline-separated ReadableStream
|
|
16922
|
+
* where each item is a JSON value.
|
|
16923
|
+
*/
|
|
16924
|
+
static fromReadableStream(readableStream, controller, client) {
|
|
16925
|
+
let consumed = false;
|
|
16926
|
+
function iterLines() {
|
|
16927
|
+
return __asyncGenerator(this, arguments, function* iterLines_1() {
|
|
16928
|
+
var _a, e_2, _b, _c;
|
|
16929
|
+
const lineDecoder = new LineDecoder();
|
|
16930
|
+
const iter = ReadableStreamToAsyncIterable(readableStream);
|
|
16931
|
+
try {
|
|
16932
|
+
for (var _d = true, iter_1 = __asyncValues(iter), iter_1_1; iter_1_1 = yield __await(iter_1.next()), _a = iter_1_1.done, !_a; _d = true) {
|
|
16933
|
+
_c = iter_1_1.value;
|
|
16934
|
+
_d = false;
|
|
16935
|
+
const chunk = _c;
|
|
16936
|
+
for (const line of lineDecoder.decode(chunk)) {
|
|
16937
|
+
yield yield __await(line);
|
|
16938
|
+
}
|
|
16939
|
+
}
|
|
16940
|
+
}
|
|
16941
|
+
catch (e_2_1) { e_2 = { error: e_2_1 }; }
|
|
16942
|
+
finally {
|
|
16943
|
+
try {
|
|
16944
|
+
if (!_d && !_a && (_b = iter_1.return)) yield __await(_b.call(iter_1));
|
|
16945
|
+
}
|
|
16946
|
+
finally { if (e_2) throw e_2.error; }
|
|
16947
|
+
}
|
|
16948
|
+
for (const line of lineDecoder.flush()) {
|
|
16949
|
+
yield yield __await(line);
|
|
16950
|
+
}
|
|
16951
|
+
});
|
|
16952
|
+
}
|
|
16953
|
+
function iterator() {
|
|
16954
|
+
return __asyncGenerator(this, arguments, function* iterator_2() {
|
|
16955
|
+
var _a, e_3, _b, _c;
|
|
16956
|
+
if (consumed) {
|
|
16957
|
+
throw new GeminiNextGenAPIClientError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
|
|
16958
|
+
}
|
|
16959
|
+
consumed = true;
|
|
16960
|
+
let done = false;
|
|
16961
|
+
try {
|
|
16962
|
+
try {
|
|
16963
|
+
for (var _d = true, _e = __asyncValues(iterLines()), _f; _f = yield __await(_e.next()), _a = _f.done, !_a; _d = true) {
|
|
16964
|
+
_c = _f.value;
|
|
16965
|
+
_d = false;
|
|
16966
|
+
const line = _c;
|
|
16967
|
+
if (done)
|
|
16968
|
+
continue;
|
|
16969
|
+
// @ts-ignore
|
|
16970
|
+
if (line)
|
|
16971
|
+
yield yield __await(JSON.parse(line));
|
|
16972
|
+
}
|
|
16973
|
+
}
|
|
16974
|
+
catch (e_3_1) { e_3 = { error: e_3_1 }; }
|
|
16975
|
+
finally {
|
|
16976
|
+
try {
|
|
16977
|
+
if (!_d && !_a && (_b = _e.return)) yield __await(_b.call(_e));
|
|
16978
|
+
}
|
|
16979
|
+
finally { if (e_3) throw e_3.error; }
|
|
16980
|
+
}
|
|
16981
|
+
done = true;
|
|
16982
|
+
}
|
|
16983
|
+
catch (e) {
|
|
16984
|
+
// If the user calls `stream.controller.abort()`, we should exit without throwing.
|
|
16985
|
+
if (isAbortError(e))
|
|
16986
|
+
return yield __await(void 0);
|
|
16987
|
+
throw e;
|
|
16988
|
+
}
|
|
16989
|
+
finally {
|
|
16990
|
+
// If the user `break`s, abort the ongoing request.
|
|
16991
|
+
if (!done)
|
|
16992
|
+
controller.abort();
|
|
16993
|
+
}
|
|
16994
|
+
});
|
|
16995
|
+
}
|
|
16996
|
+
return new Stream(iterator, controller, client);
|
|
16997
|
+
}
|
|
16998
|
+
[Symbol.asyncIterator]() {
|
|
16999
|
+
return this.iterator();
|
|
17000
|
+
}
|
|
17001
|
+
/**
|
|
17002
|
+
* Splits the stream into two streams which can be
|
|
17003
|
+
* independently read from at different speeds.
|
|
17004
|
+
*/
|
|
17005
|
+
tee() {
|
|
17006
|
+
const left = [];
|
|
17007
|
+
const right = [];
|
|
17008
|
+
const iterator = this.iterator();
|
|
17009
|
+
const teeIterator = (queue) => {
|
|
17010
|
+
return {
|
|
17011
|
+
next: () => {
|
|
17012
|
+
if (queue.length === 0) {
|
|
17013
|
+
const result = iterator.next();
|
|
17014
|
+
left.push(result);
|
|
17015
|
+
right.push(result);
|
|
17016
|
+
}
|
|
17017
|
+
return queue.shift();
|
|
17018
|
+
},
|
|
17019
|
+
};
|
|
17020
|
+
};
|
|
17021
|
+
return [
|
|
17022
|
+
new Stream(() => teeIterator(left), this.controller, this.client),
|
|
17023
|
+
new Stream(() => teeIterator(right), this.controller, this.client),
|
|
17024
|
+
];
|
|
17025
|
+
}
|
|
17026
|
+
/**
|
|
17027
|
+
* Converts this stream to a newline-separated ReadableStream of
|
|
17028
|
+
* JSON stringified values in the stream
|
|
17029
|
+
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
|
|
17030
|
+
*/
|
|
17031
|
+
toReadableStream() {
|
|
17032
|
+
const self = this;
|
|
17033
|
+
let iter;
|
|
17034
|
+
return makeReadableStream({
|
|
17035
|
+
async start() {
|
|
17036
|
+
iter = self[Symbol.asyncIterator]();
|
|
17037
|
+
},
|
|
17038
|
+
async pull(ctrl) {
|
|
17039
|
+
try {
|
|
17040
|
+
const { value, done } = await iter.next();
|
|
17041
|
+
if (done)
|
|
17042
|
+
return ctrl.close();
|
|
17043
|
+
const bytes = encodeUTF8(JSON.stringify(value) + '\n');
|
|
17044
|
+
ctrl.enqueue(bytes);
|
|
17045
|
+
}
|
|
17046
|
+
catch (err) {
|
|
17047
|
+
ctrl.error(err);
|
|
17048
|
+
}
|
|
17049
|
+
},
|
|
17050
|
+
async cancel() {
|
|
17051
|
+
var _a;
|
|
17052
|
+
await ((_a = iter.return) === null || _a === void 0 ? void 0 : _a.call(iter));
|
|
17053
|
+
},
|
|
17054
|
+
});
|
|
17055
|
+
}
|
|
17056
|
+
}
|
|
17057
|
+
function _iterSSEMessages(response, controller) {
|
|
17058
|
+
return __asyncGenerator(this, arguments, function* _iterSSEMessages_1() {
|
|
17059
|
+
var _a, e_4, _b, _c;
|
|
17060
|
+
if (!response.body) {
|
|
17061
|
+
controller.abort();
|
|
17062
|
+
if (typeof globalThis.navigator !== 'undefined' &&
|
|
17063
|
+
globalThis.navigator.product === 'ReactNative') {
|
|
17064
|
+
throw new GeminiNextGenAPIClientError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
|
|
17065
|
+
}
|
|
17066
|
+
throw new GeminiNextGenAPIClientError(`Attempted to iterate over a response with no body`);
|
|
17067
|
+
}
|
|
17068
|
+
const sseDecoder = new SSEDecoder();
|
|
17069
|
+
const lineDecoder = new LineDecoder();
|
|
17070
|
+
const iter = ReadableStreamToAsyncIterable(response.body);
|
|
17071
|
+
try {
|
|
17072
|
+
for (var _d = true, _e = __asyncValues(iterSSEChunks(iter)), _f; _f = yield __await(_e.next()), _a = _f.done, !_a; _d = true) {
|
|
17073
|
+
_c = _f.value;
|
|
17074
|
+
_d = false;
|
|
17075
|
+
const sseChunk = _c;
|
|
17076
|
+
for (const line of lineDecoder.decode(sseChunk)) {
|
|
17077
|
+
const sse = sseDecoder.decode(line);
|
|
17078
|
+
if (sse)
|
|
17079
|
+
yield yield __await(sse);
|
|
17080
|
+
}
|
|
17081
|
+
}
|
|
17082
|
+
}
|
|
17083
|
+
catch (e_4_1) { e_4 = { error: e_4_1 }; }
|
|
17084
|
+
finally {
|
|
17085
|
+
try {
|
|
17086
|
+
if (!_d && !_a && (_b = _e.return)) yield __await(_b.call(_e));
|
|
17087
|
+
}
|
|
17088
|
+
finally { if (e_4) throw e_4.error; }
|
|
17089
|
+
}
|
|
17090
|
+
for (const line of lineDecoder.flush()) {
|
|
17091
|
+
const sse = sseDecoder.decode(line);
|
|
17092
|
+
if (sse)
|
|
17093
|
+
yield yield __await(sse);
|
|
17094
|
+
}
|
|
17095
|
+
});
|
|
17096
|
+
}
|
|
17097
|
+
/**
|
|
17098
|
+
* Given an async iterable iterator, iterates over it and yields full
|
|
17099
|
+
* SSE chunks, i.e. yields when a double new-line is encountered.
|
|
17100
|
+
*/
|
|
17101
|
+
function iterSSEChunks(iterator) {
|
|
17102
|
+
return __asyncGenerator(this, arguments, function* iterSSEChunks_1() {
|
|
17103
|
+
var _a, e_5, _b, _c;
|
|
17104
|
+
let data = new Uint8Array();
|
|
17105
|
+
try {
|
|
17106
|
+
for (var _d = true, iterator_3 = __asyncValues(iterator), iterator_3_1; iterator_3_1 = yield __await(iterator_3.next()), _a = iterator_3_1.done, !_a; _d = true) {
|
|
17107
|
+
_c = iterator_3_1.value;
|
|
17108
|
+
_d = false;
|
|
17109
|
+
const chunk = _c;
|
|
17110
|
+
if (chunk == null) {
|
|
17111
|
+
continue;
|
|
17112
|
+
}
|
|
17113
|
+
const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
|
|
17114
|
+
: typeof chunk === 'string' ? encodeUTF8(chunk)
|
|
17115
|
+
: chunk;
|
|
17116
|
+
let newData = new Uint8Array(data.length + binaryChunk.length);
|
|
17117
|
+
newData.set(data);
|
|
17118
|
+
newData.set(binaryChunk, data.length);
|
|
17119
|
+
data = newData;
|
|
17120
|
+
let patternIndex;
|
|
17121
|
+
while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
|
|
17122
|
+
yield yield __await(data.slice(0, patternIndex));
|
|
17123
|
+
data = data.slice(patternIndex);
|
|
17124
|
+
}
|
|
17125
|
+
}
|
|
17126
|
+
}
|
|
17127
|
+
catch (e_5_1) { e_5 = { error: e_5_1 }; }
|
|
17128
|
+
finally {
|
|
17129
|
+
try {
|
|
17130
|
+
if (!_d && !_a && (_b = iterator_3.return)) yield __await(_b.call(iterator_3));
|
|
17131
|
+
}
|
|
17132
|
+
finally { if (e_5) throw e_5.error; }
|
|
17133
|
+
}
|
|
17134
|
+
if (data.length > 0) {
|
|
17135
|
+
yield yield __await(data);
|
|
17136
|
+
}
|
|
17137
|
+
});
|
|
17138
|
+
}
|
|
17139
|
+
class SSEDecoder {
|
|
17140
|
+
constructor() {
|
|
17141
|
+
this.event = null;
|
|
17142
|
+
this.data = [];
|
|
17143
|
+
this.chunks = [];
|
|
17144
|
+
}
|
|
17145
|
+
decode(line) {
|
|
17146
|
+
if (line.endsWith('\r')) {
|
|
17147
|
+
line = line.substring(0, line.length - 1);
|
|
17148
|
+
}
|
|
17149
|
+
if (!line) {
|
|
17150
|
+
// empty line and we didn't previously encounter any messages
|
|
17151
|
+
if (!this.event && !this.data.length)
|
|
17152
|
+
return null;
|
|
17153
|
+
const sse = {
|
|
17154
|
+
event: this.event,
|
|
17155
|
+
data: this.data.join('\n'),
|
|
17156
|
+
raw: this.chunks,
|
|
17157
|
+
};
|
|
17158
|
+
this.event = null;
|
|
17159
|
+
this.data = [];
|
|
17160
|
+
this.chunks = [];
|
|
17161
|
+
return sse;
|
|
17162
|
+
}
|
|
17163
|
+
this.chunks.push(line);
|
|
17164
|
+
if (line.startsWith(':')) {
|
|
17165
|
+
return null;
|
|
17166
|
+
}
|
|
17167
|
+
let [fieldname, _, value] = partition(line, ':');
|
|
17168
|
+
if (value.startsWith(' ')) {
|
|
17169
|
+
value = value.substring(1);
|
|
17170
|
+
}
|
|
17171
|
+
if (fieldname === 'event') {
|
|
17172
|
+
this.event = value;
|
|
17173
|
+
}
|
|
17174
|
+
else if (fieldname === 'data') {
|
|
17175
|
+
this.data.push(value);
|
|
17176
|
+
}
|
|
17177
|
+
return null;
|
|
17178
|
+
}
|
|
17179
|
+
}
|
|
17180
|
+
function partition(str, delimiter) {
|
|
17181
|
+
const index = str.indexOf(delimiter);
|
|
17182
|
+
if (index !== -1) {
|
|
17183
|
+
return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
|
|
17184
|
+
}
|
|
17185
|
+
return [str, '', ''];
|
|
17186
|
+
}
|
|
17187
|
+
|
|
17188
|
+
/**
|
|
17189
|
+
* @license
|
|
17190
|
+
* Copyright 2025 Google LLC
|
|
17191
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
17192
|
+
*/
|
|
17193
|
+
async function defaultParseResponse(client, props) {
|
|
17194
|
+
const { response, requestLogID, retryOfRequestLogID, startTime } = props;
|
|
17195
|
+
const body = await (async () => {
|
|
17196
|
+
var _a;
|
|
17197
|
+
if (props.options.stream) {
|
|
17198
|
+
loggerFor(client).debug('response', response.status, response.url, response.headers, response.body);
|
|
17199
|
+
// Note: there is an invariant here that isn't represented in the type system
|
|
17200
|
+
// that if you set `stream: true` the response type must also be `Stream<T>`
|
|
17201
|
+
if (props.options.__streamClass) {
|
|
17202
|
+
return props.options.__streamClass.fromSSEResponse(response, props.controller, client);
|
|
17203
|
+
}
|
|
17204
|
+
return Stream.fromSSEResponse(response, props.controller, client);
|
|
17205
|
+
}
|
|
17206
|
+
// fetch refuses to read the body when the status code is 204.
|
|
17207
|
+
if (response.status === 204) {
|
|
17208
|
+
return null;
|
|
17209
|
+
}
|
|
17210
|
+
if (props.options.__binaryResponse) {
|
|
17211
|
+
return response;
|
|
17212
|
+
}
|
|
17213
|
+
const contentType = response.headers.get('content-type');
|
|
17214
|
+
const mediaType = (_a = contentType === null || contentType === void 0 ? void 0 : contentType.split(';')[0]) === null || _a === void 0 ? void 0 : _a.trim();
|
|
17215
|
+
const isJSON = (mediaType === null || mediaType === void 0 ? void 0 : mediaType.includes('application/json')) || (mediaType === null || mediaType === void 0 ? void 0 : mediaType.endsWith('+json'));
|
|
17216
|
+
if (isJSON) {
|
|
17217
|
+
const json = await response.json();
|
|
17218
|
+
return json;
|
|
17219
|
+
}
|
|
17220
|
+
const text = await response.text();
|
|
17221
|
+
return text;
|
|
17222
|
+
})();
|
|
17223
|
+
loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({
|
|
17224
|
+
retryOfRequestLogID,
|
|
17225
|
+
url: response.url,
|
|
17226
|
+
status: response.status,
|
|
17227
|
+
body,
|
|
17228
|
+
durationMs: Date.now() - startTime,
|
|
17229
|
+
}));
|
|
17230
|
+
return body;
|
|
17231
|
+
}
|
|
17232
|
+
|
|
17233
|
+
/**
|
|
17234
|
+
* @license
|
|
17235
|
+
* Copyright 2025 Google LLC
|
|
17236
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
17237
|
+
*/
|
|
17238
|
+
/**
|
|
17239
|
+
* A subclass of `Promise` providing additional helper methods
|
|
17240
|
+
* for interacting with the SDK.
|
|
17241
|
+
*/
|
|
17242
|
+
class APIPromise extends Promise {
|
|
17243
|
+
constructor(client, responsePromise, parseResponse = defaultParseResponse) {
|
|
17244
|
+
super((resolve) => {
|
|
17245
|
+
// this is maybe a bit weird but this has to be a no-op to not implicitly
|
|
17246
|
+
// parse the response body; instead .then, .catch, .finally are overridden
|
|
17247
|
+
// to parse the response
|
|
17248
|
+
resolve(null);
|
|
17249
|
+
});
|
|
17250
|
+
this.responsePromise = responsePromise;
|
|
17251
|
+
this.parseResponse = parseResponse;
|
|
17252
|
+
this.client = client;
|
|
17253
|
+
}
|
|
17254
|
+
_thenUnwrap(transform) {
|
|
17255
|
+
return new APIPromise(this.client, this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props));
|
|
17256
|
+
}
|
|
17257
|
+
/**
|
|
17258
|
+
* Gets the raw `Response` instance instead of parsing the response
|
|
17259
|
+
* data.
|
|
17260
|
+
*
|
|
17261
|
+
* If you want to parse the response body but still get the `Response`
|
|
17262
|
+
* instance, you can use {@link withResponse()}.
|
|
17263
|
+
*
|
|
17264
|
+
* 👋 Getting the wrong TypeScript type for `Response`?
|
|
17265
|
+
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
|
|
17266
|
+
* to your `tsconfig.json`.
|
|
17267
|
+
*/
|
|
17268
|
+
asResponse() {
|
|
17269
|
+
return this.responsePromise.then((p) => p.response);
|
|
17270
|
+
}
|
|
17271
|
+
/**
|
|
17272
|
+
* Gets the parsed response data and the raw `Response` instance.
|
|
17273
|
+
*
|
|
17274
|
+
* If you just want to get the raw `Response` instance without parsing it,
|
|
17275
|
+
* you can use {@link asResponse()}.
|
|
17276
|
+
*
|
|
17277
|
+
* 👋 Getting the wrong TypeScript type for `Response`?
|
|
17278
|
+
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
|
|
17279
|
+
* to your `tsconfig.json`.
|
|
17280
|
+
*/
|
|
17281
|
+
async withResponse() {
|
|
17282
|
+
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
|
|
17283
|
+
return { data, response };
|
|
17284
|
+
}
|
|
17285
|
+
parse() {
|
|
17286
|
+
if (!this.parsedPromise) {
|
|
17287
|
+
this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(this.client, data));
|
|
17288
|
+
}
|
|
17289
|
+
return this.parsedPromise;
|
|
17290
|
+
}
|
|
17291
|
+
then(onfulfilled, onrejected) {
|
|
17292
|
+
return this.parse().then(onfulfilled, onrejected);
|
|
17293
|
+
}
|
|
17294
|
+
catch(onrejected) {
|
|
17295
|
+
return this.parse().catch(onrejected);
|
|
17296
|
+
}
|
|
17297
|
+
finally(onfinally) {
|
|
17298
|
+
return this.parse().finally(onfinally);
|
|
17299
|
+
}
|
|
17300
|
+
}
|
|
17301
|
+
|
|
17302
|
+
/**
|
|
17303
|
+
* @license
|
|
17304
|
+
* Copyright 2025 Google LLC
|
|
17305
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
17306
|
+
*/
|
|
17307
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
17308
|
+
const brand_privateNullableHeaders = /* @__PURE__ */ Symbol('brand.privateNullableHeaders');
|
|
17309
|
+
function* iterateHeaders(headers) {
|
|
17310
|
+
if (!headers)
|
|
17311
|
+
return;
|
|
17312
|
+
if (brand_privateNullableHeaders in headers) {
|
|
17313
|
+
const { values, nulls } = headers;
|
|
17314
|
+
yield* values.entries();
|
|
17315
|
+
for (const name of nulls) {
|
|
17316
|
+
yield [name, null];
|
|
17317
|
+
}
|
|
17318
|
+
return;
|
|
17319
|
+
}
|
|
17320
|
+
let shouldClear = false;
|
|
17321
|
+
let iter;
|
|
17322
|
+
if (headers instanceof Headers) {
|
|
17323
|
+
iter = headers.entries();
|
|
17324
|
+
}
|
|
17325
|
+
else if (isReadonlyArray(headers)) {
|
|
17326
|
+
iter = headers;
|
|
17327
|
+
}
|
|
17328
|
+
else {
|
|
17329
|
+
shouldClear = true;
|
|
17330
|
+
iter = Object.entries(headers !== null && headers !== void 0 ? headers : {});
|
|
17331
|
+
}
|
|
17332
|
+
for (let row of iter) {
|
|
17333
|
+
const name = row[0];
|
|
17334
|
+
if (typeof name !== 'string')
|
|
17335
|
+
throw new TypeError('expected header name to be a string');
|
|
17336
|
+
const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];
|
|
17337
|
+
let didClear = false;
|
|
17338
|
+
for (const value of values) {
|
|
17339
|
+
if (value === undefined)
|
|
17340
|
+
continue;
|
|
17341
|
+
// Objects keys always overwrite older headers, they never append.
|
|
17342
|
+
// Yield a null to clear the header before adding the new values.
|
|
17343
|
+
if (shouldClear && !didClear) {
|
|
17344
|
+
didClear = true;
|
|
17345
|
+
yield [name, null];
|
|
17346
|
+
}
|
|
17347
|
+
yield [name, value];
|
|
17348
|
+
}
|
|
17349
|
+
}
|
|
17350
|
+
}
|
|
17351
|
+
const buildHeaders = (newHeaders) => {
|
|
17352
|
+
const targetHeaders = new Headers();
|
|
17353
|
+
const nullHeaders = new Set();
|
|
17354
|
+
for (const headers of newHeaders) {
|
|
17355
|
+
const seenHeaders = new Set();
|
|
17356
|
+
for (const [name, value] of iterateHeaders(headers)) {
|
|
17357
|
+
const lowerName = name.toLowerCase();
|
|
17358
|
+
if (!seenHeaders.has(lowerName)) {
|
|
17359
|
+
targetHeaders.delete(name);
|
|
17360
|
+
seenHeaders.add(lowerName);
|
|
17361
|
+
}
|
|
17362
|
+
if (value === null) {
|
|
17363
|
+
targetHeaders.delete(name);
|
|
17364
|
+
nullHeaders.add(lowerName);
|
|
17365
|
+
}
|
|
17366
|
+
else {
|
|
17367
|
+
targetHeaders.append(name, value);
|
|
17368
|
+
nullHeaders.delete(lowerName);
|
|
17369
|
+
}
|
|
17370
|
+
}
|
|
17371
|
+
}
|
|
17372
|
+
return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };
|
|
17373
|
+
};
|
|
17374
|
+
|
|
17375
|
+
/**
|
|
17376
|
+
* @license
|
|
17377
|
+
* Copyright 2025 Google LLC
|
|
17378
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
17379
|
+
*/
|
|
17380
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
17381
|
+
/**
|
|
17382
|
+
* Read an environment variable.
|
|
17383
|
+
*
|
|
17384
|
+
* Trims beginning and trailing whitespace.
|
|
17385
|
+
*
|
|
17386
|
+
* Will return undefined if the environment variable doesn't exist or cannot be accessed.
|
|
17387
|
+
*/
|
|
17388
|
+
const readEnv = (env) => {
|
|
17389
|
+
var _a, _b, _c, _d, _e, _f;
|
|
17390
|
+
if (typeof globalThis.process !== 'undefined') {
|
|
17391
|
+
return (_c = (_b = (_a = globalThis.process.env) === null || _a === void 0 ? void 0 : _a[env]) === null || _b === void 0 ? void 0 : _b.trim()) !== null && _c !== void 0 ? _c : undefined;
|
|
17392
|
+
}
|
|
17393
|
+
if (typeof globalThis.Deno !== 'undefined') {
|
|
17394
|
+
return (_f = (_e = (_d = globalThis.Deno.env) === null || _d === void 0 ? void 0 : _d.get) === null || _e === void 0 ? void 0 : _e.call(_d, env)) === null || _f === void 0 ? void 0 : _f.trim();
|
|
17395
|
+
}
|
|
17396
|
+
return undefined;
|
|
17397
|
+
};
|
|
17398
|
+
|
|
17399
|
+
/**
|
|
17400
|
+
* @license
|
|
17401
|
+
* Copyright 2025 Google LLC
|
|
17402
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
17403
|
+
*/
|
|
17404
|
+
var _a;
|
|
17405
|
+
/**
|
|
17406
|
+
* Base class for Gemini Next Gen API API clients.
|
|
17407
|
+
*/
|
|
17408
|
+
class BaseGeminiNextGenAPIClient {
|
|
17409
|
+
/**
|
|
17410
|
+
* API Client for interfacing with the Gemini Next Gen API API.
|
|
17411
|
+
*
|
|
17412
|
+
* @param {string | null | undefined} [opts.apiKey=process.env['GEMINI_API_KEY'] ?? null]
|
|
17413
|
+
* @param {string | undefined} [opts.apiVersion=v1beta]
|
|
17414
|
+
* @param {string} [opts.baseURL=process.env['GEMINI_NEXT_GEN_API_BASE_URL'] ?? https://generativelanguage.googleapis.com] - Override the default base URL for the API.
|
|
17415
|
+
* @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
|
|
17416
|
+
* @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
|
|
17417
|
+
* @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
|
|
17418
|
+
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
|
|
17419
|
+
* @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
|
|
17420
|
+
* @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
|
|
17421
|
+
*/
|
|
17422
|
+
constructor(_b) {
|
|
17423
|
+
var _c, _d, _e, _f, _g, _h, _j;
|
|
17424
|
+
var { baseURL = readEnv('GEMINI_NEXT_GEN_API_BASE_URL'), apiKey = (_c = readEnv('GEMINI_API_KEY')) !== null && _c !== void 0 ? _c : null, apiVersion = 'v1beta' } = _b, opts = __rest(_b, ["baseURL", "apiKey", "apiVersion"]);
|
|
17425
|
+
const options = Object.assign(Object.assign({ apiKey,
|
|
17426
|
+
apiVersion }, opts), { baseURL: baseURL || `https://generativelanguage.googleapis.com` });
|
|
17427
|
+
this.baseURL = options.baseURL;
|
|
17428
|
+
this.timeout = (_d = options.timeout) !== null && _d !== void 0 ? _d : BaseGeminiNextGenAPIClient.DEFAULT_TIMEOUT /* 1 minute */;
|
|
17429
|
+
this.logger = (_e = options.logger) !== null && _e !== void 0 ? _e : console;
|
|
17430
|
+
const defaultLogLevel = 'warn';
|
|
17431
|
+
// Set default logLevel early so that we can log a warning in parseLogLevel.
|
|
17432
|
+
this.logLevel = defaultLogLevel;
|
|
17433
|
+
this.logLevel =
|
|
17434
|
+
(_g = (_f = parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this)) !== null && _f !== void 0 ? _f : parseLogLevel(readEnv('GEMINI_NEXT_GEN_API_LOG'), "process.env['GEMINI_NEXT_GEN_API_LOG']", this)) !== null && _g !== void 0 ? _g : defaultLogLevel;
|
|
17435
|
+
this.fetchOptions = options.fetchOptions;
|
|
17436
|
+
this.maxRetries = (_h = options.maxRetries) !== null && _h !== void 0 ? _h : 2;
|
|
17437
|
+
this.fetch = (_j = options.fetch) !== null && _j !== void 0 ? _j : getDefaultFetch();
|
|
17438
|
+
this.encoder = FallbackEncoder;
|
|
17439
|
+
this._options = options;
|
|
17440
|
+
this.apiKey = apiKey;
|
|
17441
|
+
this.apiVersion = apiVersion;
|
|
17442
|
+
this.clientAdapter = options.clientAdapter;
|
|
17443
|
+
}
|
|
17444
|
+
/**
|
|
17445
|
+
* Create a new client instance re-using the same options given to the current client with optional overriding.
|
|
17446
|
+
*/
|
|
17447
|
+
withOptions(options) {
|
|
17448
|
+
const client = new this.constructor(Object.assign(Object.assign(Object.assign({}, this._options), { baseURL: this.baseURL, maxRetries: this.maxRetries, timeout: this.timeout, logger: this.logger, logLevel: this.logLevel, fetch: this.fetch, fetchOptions: this.fetchOptions, apiKey: this.apiKey, apiVersion: this.apiVersion }), options));
|
|
17449
|
+
return client;
|
|
17450
|
+
}
|
|
17451
|
+
/**
|
|
17452
|
+
* Check whether the base URL is set to its default.
|
|
17453
|
+
*/
|
|
17454
|
+
baseURLOverridden() {
|
|
17455
|
+
return this.baseURL !== 'https://generativelanguage.googleapis.com';
|
|
17456
|
+
}
|
|
17457
|
+
defaultQuery() {
|
|
17458
|
+
return this._options.defaultQuery;
|
|
17459
|
+
}
|
|
17460
|
+
validateHeaders({ values, nulls }) {
|
|
17461
|
+
// The headers object handles case insensitivity.
|
|
17462
|
+
if (values.has('authorization') || values.has('x-goog-api-key')) {
|
|
17463
|
+
return;
|
|
17464
|
+
}
|
|
17465
|
+
if (this.apiKey && values.get('x-goog-api-key')) {
|
|
17466
|
+
return;
|
|
17467
|
+
}
|
|
17468
|
+
if (nulls.has('x-goog-api-key')) {
|
|
17469
|
+
return;
|
|
17470
|
+
}
|
|
17471
|
+
throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted');
|
|
17472
|
+
}
|
|
17473
|
+
async authHeaders(opts) {
|
|
17474
|
+
const existingHeaders = buildHeaders([opts.headers]);
|
|
17475
|
+
if (existingHeaders.values.has('authorization') || existingHeaders.values.has('x-goog-api-key')) {
|
|
17476
|
+
return undefined;
|
|
17477
|
+
}
|
|
17478
|
+
if (this.apiKey) {
|
|
17479
|
+
return buildHeaders([{ 'x-goog-api-key': this.apiKey }]);
|
|
17480
|
+
}
|
|
17481
|
+
if (this.clientAdapter.isVertexAI()) {
|
|
17482
|
+
return buildHeaders([await this.clientAdapter.getAuthHeaders()]);
|
|
17483
|
+
}
|
|
17484
|
+
return undefined;
|
|
17485
|
+
}
|
|
17486
|
+
/**
|
|
17487
|
+
* Basic re-implementation of `qs.stringify` for primitive types.
|
|
17488
|
+
*/
|
|
17489
|
+
stringifyQuery(query) {
|
|
17490
|
+
return Object.entries(query)
|
|
17491
|
+
.filter(([_, value]) => typeof value !== 'undefined')
|
|
17492
|
+
.map(([key, value]) => {
|
|
17493
|
+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
|
17494
|
+
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
|
17495
|
+
}
|
|
17496
|
+
if (value === null) {
|
|
17497
|
+
return `${encodeURIComponent(key)}=`;
|
|
17498
|
+
}
|
|
17499
|
+
throw new GeminiNextGenAPIClientError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
|
|
17500
|
+
})
|
|
17501
|
+
.join('&');
|
|
17502
|
+
}
|
|
17503
|
+
getUserAgent() {
|
|
17504
|
+
return `${this.constructor.name}/JS ${VERSION}`;
|
|
17505
|
+
}
|
|
17506
|
+
defaultIdempotencyKey() {
|
|
17507
|
+
return `stainless-node-retry-${uuid4()}`;
|
|
17508
|
+
}
|
|
17509
|
+
makeStatusError(status, error, message, headers) {
|
|
17510
|
+
return APIError.generate(status, error, message, headers);
|
|
17511
|
+
}
|
|
17512
|
+
buildURL(path, query, defaultBaseURL) {
|
|
17513
|
+
const baseURL = (!this.baseURLOverridden() && defaultBaseURL) || this.baseURL;
|
|
17514
|
+
const url = isAbsoluteURL(path) ?
|
|
17515
|
+
new URL(path)
|
|
17516
|
+
: new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
|
|
17517
|
+
const defaultQuery = this.defaultQuery();
|
|
17518
|
+
if (!isEmptyObj(defaultQuery)) {
|
|
17519
|
+
query = Object.assign(Object.assign({}, defaultQuery), query);
|
|
17520
|
+
}
|
|
17521
|
+
if (typeof query === 'object' && query && !Array.isArray(query)) {
|
|
17522
|
+
url.search = this.stringifyQuery(query);
|
|
17523
|
+
}
|
|
17524
|
+
return url.toString();
|
|
17525
|
+
}
|
|
17526
|
+
/**
|
|
17527
|
+
* Used as a callback for mutating the given `FinalRequestOptions` object.
|
|
17528
|
+
|
|
17529
|
+
*/
|
|
17530
|
+
async prepareOptions(options) {
|
|
17531
|
+
if (this.clientAdapter &&
|
|
17532
|
+
this.clientAdapter.isVertexAI() &&
|
|
17533
|
+
!options.path.startsWith(`/${this.apiVersion}/projects/`)) {
|
|
17534
|
+
const oldPath = options.path.slice(this.apiVersion.length + 1);
|
|
17535
|
+
options.path = `/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${oldPath}`;
|
|
17536
|
+
}
|
|
17537
|
+
}
|
|
17538
|
+
/**
|
|
17539
|
+
* Used as a callback for mutating the given `RequestInit` object.
|
|
17540
|
+
*
|
|
17541
|
+
* This is useful for cases where you want to add certain headers based off of
|
|
17542
|
+
* the request properties, e.g. `method` or `url`.
|
|
17543
|
+
*/
|
|
17544
|
+
async prepareRequest(request, { url, options }) { }
|
|
17545
|
+
get(path, opts) {
|
|
17546
|
+
return this.methodRequest('get', path, opts);
|
|
17547
|
+
}
|
|
17548
|
+
post(path, opts) {
|
|
17549
|
+
return this.methodRequest('post', path, opts);
|
|
17550
|
+
}
|
|
17551
|
+
patch(path, opts) {
|
|
17552
|
+
return this.methodRequest('patch', path, opts);
|
|
17553
|
+
}
|
|
17554
|
+
put(path, opts) {
|
|
17555
|
+
return this.methodRequest('put', path, opts);
|
|
17556
|
+
}
|
|
17557
|
+
delete(path, opts) {
|
|
17558
|
+
return this.methodRequest('delete', path, opts);
|
|
17559
|
+
}
|
|
17560
|
+
methodRequest(method, path, opts) {
|
|
17561
|
+
return this.request(Promise.resolve(opts).then((opts) => {
|
|
17562
|
+
return Object.assign({ method, path }, opts);
|
|
17563
|
+
}));
|
|
17564
|
+
}
|
|
17565
|
+
request(options, remainingRetries = null) {
|
|
17566
|
+
return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
|
|
17567
|
+
}
|
|
17568
|
+
async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
|
|
17569
|
+
var _b, _c, _d;
|
|
17570
|
+
const options = await optionsInput;
|
|
17571
|
+
const maxRetries = (_b = options.maxRetries) !== null && _b !== void 0 ? _b : this.maxRetries;
|
|
17572
|
+
if (retriesRemaining == null) {
|
|
17573
|
+
retriesRemaining = maxRetries;
|
|
17574
|
+
}
|
|
17575
|
+
await this.prepareOptions(options);
|
|
17576
|
+
const { req, url, timeout } = await this.buildRequest(options, {
|
|
17577
|
+
retryCount: maxRetries - retriesRemaining,
|
|
17578
|
+
});
|
|
17579
|
+
await this.prepareRequest(req, { url, options });
|
|
17580
|
+
/** Not an API request ID, just for correlating local log entries. */
|
|
17581
|
+
const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
|
|
17582
|
+
const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
|
|
17583
|
+
const startTime = Date.now();
|
|
17584
|
+
loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
|
|
17585
|
+
retryOfRequestLogID,
|
|
17586
|
+
method: options.method,
|
|
17587
|
+
url,
|
|
17588
|
+
options,
|
|
17589
|
+
headers: req.headers,
|
|
17590
|
+
}));
|
|
17591
|
+
if ((_c = options.signal) === null || _c === void 0 ? void 0 : _c.aborted) {
|
|
17592
|
+
throw new APIUserAbortError();
|
|
17593
|
+
}
|
|
17594
|
+
const controller = new AbortController();
|
|
17595
|
+
const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
|
|
17596
|
+
const headersTime = Date.now();
|
|
17597
|
+
if (response instanceof globalThis.Error) {
|
|
17598
|
+
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
|
|
17599
|
+
if ((_d = options.signal) === null || _d === void 0 ? void 0 : _d.aborted) {
|
|
17600
|
+
throw new APIUserAbortError();
|
|
17601
|
+
}
|
|
17602
|
+
// detect native connection timeout errors
|
|
17603
|
+
// deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
|
|
17604
|
+
// undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
|
|
17605
|
+
// others do not provide enough information to distinguish timeouts from other connection errors
|
|
17606
|
+
const isTimeout = isAbortError(response) ||
|
|
17607
|
+
/timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
|
|
17608
|
+
if (retriesRemaining) {
|
|
17609
|
+
loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
|
|
17610
|
+
loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
|
|
17611
|
+
retryOfRequestLogID,
|
|
17612
|
+
url,
|
|
17613
|
+
durationMs: headersTime - startTime,
|
|
17614
|
+
message: response.message,
|
|
17615
|
+
}));
|
|
17616
|
+
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID !== null && retryOfRequestLogID !== void 0 ? retryOfRequestLogID : requestLogID);
|
|
17617
|
+
}
|
|
17618
|
+
loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
|
|
17619
|
+
loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
|
|
17620
|
+
retryOfRequestLogID,
|
|
17621
|
+
url,
|
|
17622
|
+
durationMs: headersTime - startTime,
|
|
17623
|
+
message: response.message,
|
|
17624
|
+
}));
|
|
17625
|
+
if (isTimeout) {
|
|
17626
|
+
throw new APIConnectionTimeoutError();
|
|
17627
|
+
}
|
|
17628
|
+
throw new APIConnectionError({ cause: response });
|
|
17629
|
+
}
|
|
17630
|
+
const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
|
|
17631
|
+
if (!response.ok) {
|
|
17632
|
+
const shouldRetry = await this.shouldRetry(response);
|
|
17633
|
+
if (retriesRemaining && shouldRetry) {
|
|
17634
|
+
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
|
|
17635
|
+
// We don't need the body of this response.
|
|
17636
|
+
await CancelReadableStream(response.body);
|
|
17637
|
+
loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
|
|
17638
|
+
loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
|
|
17639
|
+
retryOfRequestLogID,
|
|
17640
|
+
url: response.url,
|
|
17641
|
+
status: response.status,
|
|
17642
|
+
headers: response.headers,
|
|
17643
|
+
durationMs: headersTime - startTime,
|
|
17644
|
+
}));
|
|
17645
|
+
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID !== null && retryOfRequestLogID !== void 0 ? retryOfRequestLogID : requestLogID, response.headers);
|
|
17646
|
+
}
|
|
17647
|
+
const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
|
|
17648
|
+
loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
|
|
17649
|
+
const errText = await response.text().catch((err) => castToError(err).message);
|
|
17650
|
+
const errJSON = safeJSON(errText);
|
|
17651
|
+
const errMessage = errJSON ? undefined : errText;
|
|
17652
|
+
loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
|
|
17653
|
+
retryOfRequestLogID,
|
|
17654
|
+
url: response.url,
|
|
17655
|
+
status: response.status,
|
|
17656
|
+
headers: response.headers,
|
|
17657
|
+
message: errMessage,
|
|
17658
|
+
durationMs: Date.now() - startTime,
|
|
17659
|
+
}));
|
|
17660
|
+
// @ts-ignore
|
|
17661
|
+
const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
|
|
17662
|
+
throw err;
|
|
17663
|
+
}
|
|
17664
|
+
loggerFor(this).info(responseInfo);
|
|
17665
|
+
loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
|
|
17666
|
+
retryOfRequestLogID,
|
|
17667
|
+
url: response.url,
|
|
17668
|
+
status: response.status,
|
|
17669
|
+
headers: response.headers,
|
|
17670
|
+
durationMs: headersTime - startTime,
|
|
17671
|
+
}));
|
|
17672
|
+
return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
|
|
17673
|
+
}
|
|
17674
|
+
async fetchWithTimeout(url, init, ms, controller) {
|
|
17675
|
+
const _b = init || {}, { signal, method } = _b, options = __rest(_b, ["signal", "method"]);
|
|
17676
|
+
if (signal)
|
|
17677
|
+
signal.addEventListener('abort', () => controller.abort());
|
|
17678
|
+
const timeout = setTimeout(() => controller.abort(), ms);
|
|
17679
|
+
const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
|
|
17680
|
+
(typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
|
|
17681
|
+
const fetchOptions = Object.assign(Object.assign(Object.assign({ signal: controller.signal }, (isReadableBody ? { duplex: 'half' } : {})), { method: 'GET' }), options);
|
|
17682
|
+
if (method) {
|
|
17683
|
+
// Custom methods like 'patch' need to be uppercased
|
|
17684
|
+
// See https://github.com/nodejs/undici/issues/2294
|
|
17685
|
+
fetchOptions.method = method.toUpperCase();
|
|
17686
|
+
}
|
|
17687
|
+
try {
|
|
17688
|
+
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
|
|
17689
|
+
return await this.fetch.call(undefined, url, fetchOptions);
|
|
17690
|
+
}
|
|
17691
|
+
finally {
|
|
17692
|
+
clearTimeout(timeout);
|
|
17693
|
+
}
|
|
17694
|
+
}
|
|
17695
|
+
async shouldRetry(response) {
|
|
17696
|
+
// Note this is not a standard header.
|
|
17697
|
+
const shouldRetryHeader = response.headers.get('x-should-retry');
|
|
17698
|
+
// If the server explicitly says whether or not to retry, obey.
|
|
17699
|
+
if (shouldRetryHeader === 'true')
|
|
17700
|
+
return true;
|
|
17701
|
+
if (shouldRetryHeader === 'false')
|
|
17702
|
+
return false;
|
|
17703
|
+
// Retry on request timeouts.
|
|
17704
|
+
if (response.status === 408)
|
|
17705
|
+
return true;
|
|
17706
|
+
// Retry on lock timeouts.
|
|
17707
|
+
if (response.status === 409)
|
|
17708
|
+
return true;
|
|
17709
|
+
// Retry on rate limits.
|
|
17710
|
+
if (response.status === 429)
|
|
17711
|
+
return true;
|
|
17712
|
+
// Retry internal errors.
|
|
17713
|
+
if (response.status >= 500)
|
|
17714
|
+
return true;
|
|
17715
|
+
return false;
|
|
17716
|
+
}
|
|
17717
|
+
async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
|
|
17718
|
+
var _b;
|
|
17719
|
+
let timeoutMillis;
|
|
17720
|
+
// Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
|
|
17721
|
+
const retryAfterMillisHeader = responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders.get('retry-after-ms');
|
|
17722
|
+
if (retryAfterMillisHeader) {
|
|
17723
|
+
const timeoutMs = parseFloat(retryAfterMillisHeader);
|
|
17724
|
+
if (!Number.isNaN(timeoutMs)) {
|
|
17725
|
+
timeoutMillis = timeoutMs;
|
|
17726
|
+
}
|
|
17727
|
+
}
|
|
17728
|
+
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
|
|
17729
|
+
const retryAfterHeader = responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders.get('retry-after');
|
|
17730
|
+
if (retryAfterHeader && !timeoutMillis) {
|
|
17731
|
+
const timeoutSeconds = parseFloat(retryAfterHeader);
|
|
17732
|
+
if (!Number.isNaN(timeoutSeconds)) {
|
|
17733
|
+
timeoutMillis = timeoutSeconds * 1000;
|
|
17734
|
+
}
|
|
17735
|
+
else {
|
|
17736
|
+
timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
|
|
17737
|
+
}
|
|
17738
|
+
}
|
|
17739
|
+
// If the API asks us to wait a certain amount of time (and it's a reasonable amount),
|
|
17740
|
+
// just do what it says, but otherwise calculate a default
|
|
17741
|
+
if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
|
|
17742
|
+
const maxRetries = (_b = options.maxRetries) !== null && _b !== void 0 ? _b : this.maxRetries;
|
|
17743
|
+
timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
|
|
17744
|
+
}
|
|
17745
|
+
await sleep$1(timeoutMillis);
|
|
17746
|
+
return this.makeRequest(options, retriesRemaining - 1, requestLogID);
|
|
17747
|
+
}
|
|
17748
|
+
calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
|
|
17749
|
+
const initialRetryDelay = 0.5;
|
|
17750
|
+
const maxRetryDelay = 8.0;
|
|
17751
|
+
const numRetries = maxRetries - retriesRemaining;
|
|
17752
|
+
// Apply exponential backoff, but not more than the max.
|
|
17753
|
+
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
|
|
17754
|
+
// Apply some jitter, take up to at most 25 percent of the retry time.
|
|
17755
|
+
const jitter = 1 - Math.random() * 0.25;
|
|
17756
|
+
return sleepSeconds * jitter * 1000;
|
|
17757
|
+
}
|
|
17758
|
+
async buildRequest(inputOptions, { retryCount = 0 } = {}) {
|
|
17759
|
+
var _b, _c, _d;
|
|
17760
|
+
const options = Object.assign({}, inputOptions);
|
|
17761
|
+
const { method, path, query, defaultBaseURL } = options;
|
|
17762
|
+
const url = this.buildURL(path, query, defaultBaseURL);
|
|
17763
|
+
if ('timeout' in options)
|
|
17764
|
+
validatePositiveInteger('timeout', options.timeout);
|
|
17765
|
+
options.timeout = (_b = options.timeout) !== null && _b !== void 0 ? _b : this.timeout;
|
|
17766
|
+
const { bodyHeaders, body } = this.buildBody({ options });
|
|
17767
|
+
const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
|
|
17768
|
+
const req = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ method, headers: reqHeaders }, (options.signal && { signal: options.signal })), (globalThis.ReadableStream &&
|
|
17769
|
+
body instanceof globalThis.ReadableStream && { duplex: 'half' })), (body && { body })), ((_c = this.fetchOptions) !== null && _c !== void 0 ? _c : {})), ((_d = options.fetchOptions) !== null && _d !== void 0 ? _d : {}));
|
|
17770
|
+
return { req, url, timeout: options.timeout };
|
|
17771
|
+
}
|
|
17772
|
+
async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
|
|
17773
|
+
let idempotencyHeaders = {};
|
|
17774
|
+
if (this.idempotencyHeader && method !== 'get') {
|
|
17775
|
+
if (!options.idempotencyKey)
|
|
17776
|
+
options.idempotencyKey = this.defaultIdempotencyKey();
|
|
17777
|
+
idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
|
|
17778
|
+
}
|
|
17779
|
+
const authHeaders = await this.authHeaders(options);
|
|
17780
|
+
let headers = buildHeaders([
|
|
17781
|
+
idempotencyHeaders,
|
|
17782
|
+
Object.assign(Object.assign({ Accept: 'application/json', 'User-Agent': this.getUserAgent(), 'X-Stainless-Retry-Count': String(retryCount) }, (options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {})), getPlatformHeaders()),
|
|
17783
|
+
this._options.defaultHeaders,
|
|
17784
|
+
bodyHeaders,
|
|
17785
|
+
options.headers,
|
|
17786
|
+
authHeaders,
|
|
17787
|
+
]);
|
|
17788
|
+
this.validateHeaders(headers);
|
|
17789
|
+
return headers.values;
|
|
17790
|
+
}
|
|
17791
|
+
buildBody({ options: { body, headers: rawHeaders } }) {
|
|
17792
|
+
if (!body) {
|
|
17793
|
+
return { bodyHeaders: undefined, body: undefined };
|
|
17794
|
+
}
|
|
17795
|
+
const headers = buildHeaders([rawHeaders]);
|
|
17796
|
+
if (
|
|
17797
|
+
// Pass raw type verbatim
|
|
17798
|
+
ArrayBuffer.isView(body) ||
|
|
17799
|
+
body instanceof ArrayBuffer ||
|
|
17800
|
+
body instanceof DataView ||
|
|
17801
|
+
(typeof body === 'string' &&
|
|
17802
|
+
// Preserve legacy string encoding behavior for now
|
|
17803
|
+
headers.values.has('content-type')) ||
|
|
17804
|
+
// `Blob` is superset of `File`
|
|
17805
|
+
(globalThis.Blob && body instanceof globalThis.Blob) ||
|
|
17806
|
+
// `FormData` -> `multipart/form-data`
|
|
17807
|
+
body instanceof FormData ||
|
|
17808
|
+
// `URLSearchParams` -> `application/x-www-form-urlencoded`
|
|
17809
|
+
body instanceof URLSearchParams ||
|
|
17810
|
+
// Send chunked stream (each chunk has own `length`)
|
|
17811
|
+
(globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
|
|
17812
|
+
return { bodyHeaders: undefined, body: body };
|
|
17813
|
+
}
|
|
17814
|
+
else if (typeof body === 'object' &&
|
|
17815
|
+
(Symbol.asyncIterator in body ||
|
|
17816
|
+
(Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
|
|
17817
|
+
return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
|
|
17818
|
+
}
|
|
17819
|
+
else {
|
|
17820
|
+
return this.encoder({ body, headers });
|
|
17821
|
+
}
|
|
17822
|
+
}
|
|
17823
|
+
}
|
|
17824
|
+
BaseGeminiNextGenAPIClient.DEFAULT_TIMEOUT = 60000; // 1 minute
|
|
17825
|
+
/**
|
|
17826
|
+
* API Client for interfacing with the Gemini Next Gen API API.
|
|
17827
|
+
*/
|
|
17828
|
+
class GeminiNextGenAPIClient extends BaseGeminiNextGenAPIClient {
|
|
17829
|
+
constructor() {
|
|
17830
|
+
super(...arguments);
|
|
17831
|
+
this.interactions = new Interactions(this);
|
|
17832
|
+
}
|
|
17833
|
+
}
|
|
17834
|
+
_a = GeminiNextGenAPIClient;
|
|
17835
|
+
GeminiNextGenAPIClient.GeminiNextGenAPIClient = _a;
|
|
17836
|
+
GeminiNextGenAPIClient.GeminiNextGenAPIClientError = GeminiNextGenAPIClientError;
|
|
17837
|
+
GeminiNextGenAPIClient.APIError = APIError;
|
|
17838
|
+
GeminiNextGenAPIClient.APIConnectionError = APIConnectionError;
|
|
17839
|
+
GeminiNextGenAPIClient.APIConnectionTimeoutError = APIConnectionTimeoutError;
|
|
17840
|
+
GeminiNextGenAPIClient.APIUserAbortError = APIUserAbortError;
|
|
17841
|
+
GeminiNextGenAPIClient.NotFoundError = NotFoundError;
|
|
17842
|
+
GeminiNextGenAPIClient.ConflictError = ConflictError;
|
|
17843
|
+
GeminiNextGenAPIClient.RateLimitError = RateLimitError;
|
|
17844
|
+
GeminiNextGenAPIClient.BadRequestError = BadRequestError;
|
|
17845
|
+
GeminiNextGenAPIClient.AuthenticationError = AuthenticationError;
|
|
17846
|
+
GeminiNextGenAPIClient.InternalServerError = InternalServerError;
|
|
17847
|
+
GeminiNextGenAPIClient.PermissionDeniedError = PermissionDeniedError;
|
|
17848
|
+
GeminiNextGenAPIClient.UnprocessableEntityError = UnprocessableEntityError;
|
|
17849
|
+
GeminiNextGenAPIClient.toFile = toFile;
|
|
17850
|
+
GeminiNextGenAPIClient.Interactions = Interactions;
|
|
17851
|
+
|
|
17852
|
+
/**
|
|
17853
|
+
* @license
|
|
17854
|
+
* Copyright 2025 Google LLC
|
|
17855
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
17856
|
+
*/
|
|
17857
|
+
// Code generated by the Google Gen AI SDK generator DO NOT EDIT.
|
|
17858
|
+
function cancelTuningJobParametersToMldev(fromObject, _rootObject) {
|
|
17859
|
+
const toObject = {};
|
|
17860
|
+
const fromName = getValueByPath(fromObject, ['name']);
|
|
17861
|
+
if (fromName != null) {
|
|
17862
|
+
setValueByPath(toObject, ['_url', 'name'], fromName);
|
|
17863
|
+
}
|
|
17864
|
+
return toObject;
|
|
17865
|
+
}
|
|
17866
|
+
function cancelTuningJobParametersToVertex(fromObject, _rootObject) {
|
|
17867
|
+
const toObject = {};
|
|
17868
|
+
const fromName = getValueByPath(fromObject, ['name']);
|
|
17869
|
+
if (fromName != null) {
|
|
17870
|
+
setValueByPath(toObject, ['_url', 'name'], fromName);
|
|
17871
|
+
}
|
|
17872
|
+
return toObject;
|
|
17873
|
+
}
|
|
17874
|
+
function cancelTuningJobResponseFromMldev(fromObject, _rootObject) {
|
|
17875
|
+
const toObject = {};
|
|
17876
|
+
const fromSdkHttpResponse = getValueByPath(fromObject, [
|
|
17877
|
+
'sdkHttpResponse',
|
|
17878
|
+
]);
|
|
17879
|
+
if (fromSdkHttpResponse != null) {
|
|
17880
|
+
setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);
|
|
17881
|
+
}
|
|
17882
|
+
return toObject;
|
|
17883
|
+
}
|
|
17884
|
+
function cancelTuningJobResponseFromVertex(fromObject, _rootObject) {
|
|
17885
|
+
const toObject = {};
|
|
17886
|
+
const fromSdkHttpResponse = getValueByPath(fromObject, [
|
|
17887
|
+
'sdkHttpResponse',
|
|
17888
|
+
]);
|
|
17889
|
+
if (fromSdkHttpResponse != null) {
|
|
17890
|
+
setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);
|
|
17891
|
+
}
|
|
17892
|
+
return toObject;
|
|
17893
|
+
}
|
|
17894
|
+
function createTuningJobConfigToMldev(fromObject, parentObject, _rootObject) {
|
|
17895
|
+
const toObject = {};
|
|
17896
|
+
if (getValueByPath(fromObject, ['validationDataset']) !== undefined) {
|
|
17897
|
+
throw new Error('validationDataset parameter is not supported in Gemini API.');
|
|
17898
|
+
}
|
|
17899
|
+
const fromTunedModelDisplayName = getValueByPath(fromObject, [
|
|
17900
|
+
'tunedModelDisplayName',
|
|
17901
|
+
]);
|
|
17902
|
+
if (parentObject !== undefined && fromTunedModelDisplayName != null) {
|
|
17903
|
+
setValueByPath(parentObject, ['displayName'], fromTunedModelDisplayName);
|
|
17904
|
+
}
|
|
17905
|
+
if (getValueByPath(fromObject, ['description']) !== undefined) {
|
|
17906
|
+
throw new Error('description parameter is not supported in Gemini API.');
|
|
17907
|
+
}
|
|
17908
|
+
const fromEpochCount = getValueByPath(fromObject, ['epochCount']);
|
|
17909
|
+
if (parentObject !== undefined && fromEpochCount != null) {
|
|
17910
|
+
setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'epochCount'], fromEpochCount);
|
|
17911
|
+
}
|
|
17912
|
+
const fromLearningRateMultiplier = getValueByPath(fromObject, [
|
|
17913
|
+
'learningRateMultiplier',
|
|
17914
|
+
]);
|
|
17915
|
+
if (fromLearningRateMultiplier != null) {
|
|
17916
|
+
setValueByPath(toObject, ['tuningTask', 'hyperparameters', 'learningRateMultiplier'], fromLearningRateMultiplier);
|
|
17917
|
+
}
|
|
17918
|
+
if (getValueByPath(fromObject, ['exportLastCheckpointOnly']) !==
|
|
17919
|
+
undefined) {
|
|
17920
|
+
throw new Error('exportLastCheckpointOnly parameter is not supported in Gemini API.');
|
|
17921
|
+
}
|
|
17922
|
+
if (getValueByPath(fromObject, ['preTunedModelCheckpointId']) !==
|
|
17923
|
+
undefined) {
|
|
17924
|
+
throw new Error('preTunedModelCheckpointId parameter is not supported in Gemini API.');
|
|
17925
|
+
}
|
|
17926
|
+
if (getValueByPath(fromObject, ['adapterSize']) !== undefined) {
|
|
17927
|
+
throw new Error('adapterSize parameter is not supported in Gemini API.');
|
|
17928
|
+
}
|
|
17929
|
+
const fromBatchSize = getValueByPath(fromObject, ['batchSize']);
|
|
17930
|
+
if (parentObject !== undefined && fromBatchSize != null) {
|
|
17931
|
+
setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'batchSize'], fromBatchSize);
|
|
17932
|
+
}
|
|
17933
|
+
const fromLearningRate = getValueByPath(fromObject, ['learningRate']);
|
|
17934
|
+
if (parentObject !== undefined && fromLearningRate != null) {
|
|
17935
|
+
setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'learningRate'], fromLearningRate);
|
|
17936
|
+
}
|
|
17937
|
+
if (getValueByPath(fromObject, ['labels']) !== undefined) {
|
|
17938
|
+
throw new Error('labels parameter is not supported in Gemini API.');
|
|
17939
|
+
}
|
|
17940
|
+
if (getValueByPath(fromObject, ['beta']) !== undefined) {
|
|
17941
|
+
throw new Error('beta parameter is not supported in Gemini API.');
|
|
17942
|
+
}
|
|
17943
|
+
return toObject;
|
|
17944
|
+
}
|
|
17945
|
+
function createTuningJobConfigToVertex(fromObject, parentObject, rootObject) {
|
|
17946
|
+
const toObject = {};
|
|
17947
|
+
let discriminatorValidationDataset = getValueByPath(rootObject, [
|
|
17948
|
+
'config',
|
|
17949
|
+
'method',
|
|
17950
|
+
]);
|
|
17951
|
+
if (discriminatorValidationDataset === undefined) {
|
|
17952
|
+
discriminatorValidationDataset = 'SUPERVISED_FINE_TUNING';
|
|
17953
|
+
}
|
|
17954
|
+
if (discriminatorValidationDataset === 'SUPERVISED_FINE_TUNING') {
|
|
17955
|
+
const fromValidationDataset = getValueByPath(fromObject, [
|
|
17956
|
+
'validationDataset',
|
|
17957
|
+
]);
|
|
17958
|
+
if (parentObject !== undefined && fromValidationDataset != null) {
|
|
17959
|
+
setValueByPath(parentObject, ['supervisedTuningSpec'], tuningValidationDatasetToVertex(fromValidationDataset));
|
|
17960
|
+
}
|
|
17961
|
+
}
|
|
17962
|
+
else if (discriminatorValidationDataset === 'PREFERENCE_TUNING') {
|
|
17963
|
+
const fromValidationDataset = getValueByPath(fromObject, [
|
|
17964
|
+
'validationDataset',
|
|
17965
|
+
]);
|
|
15933
17966
|
if (parentObject !== undefined && fromValidationDataset != null) {
|
|
15934
17967
|
setValueByPath(parentObject, ['preferenceOptimizationSpec'], tuningValidationDatasetToVertex(fromValidationDataset));
|
|
15935
17968
|
}
|
|
@@ -17110,6 +19143,27 @@ const LANGUAGE_LABEL_PREFIX = 'gl-node/';
|
|
|
17110
19143
|
*
|
|
17111
19144
|
*/
|
|
17112
19145
|
class GoogleGenAI {
|
|
19146
|
+
get interactions() {
|
|
19147
|
+
if (this._interactions !== undefined) {
|
|
19148
|
+
return this._interactions;
|
|
19149
|
+
}
|
|
19150
|
+
console.warn('GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions.');
|
|
19151
|
+
const httpOpts = this.httpOptions;
|
|
19152
|
+
// Unsupported Options Warnings
|
|
19153
|
+
if (httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.extraBody) {
|
|
19154
|
+
console.warn('GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.');
|
|
19155
|
+
}
|
|
19156
|
+
const nextGenClient = new GeminiNextGenAPIClient({
|
|
19157
|
+
baseURL: this.apiClient.getBaseUrl(),
|
|
19158
|
+
apiKey: this.apiKey,
|
|
19159
|
+
apiVersion: this.apiClient.getApiVersion(),
|
|
19160
|
+
clientAdapter: this.apiClient,
|
|
19161
|
+
defaultHeaders: this.apiClient.getDefaultHeaders(),
|
|
19162
|
+
timeout: httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.timeout,
|
|
19163
|
+
});
|
|
19164
|
+
this._interactions = nextGenClient.interactions;
|
|
19165
|
+
return this._interactions;
|
|
19166
|
+
}
|
|
17113
19167
|
constructor(options) {
|
|
17114
19168
|
var _a;
|
|
17115
19169
|
if (options.apiKey == null) {
|
|
@@ -17158,5 +19212,5 @@ class GoogleGenAI {
|
|
|
17158
19212
|
}
|
|
17159
19213
|
}
|
|
17160
19214
|
|
|
17161
|
-
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 };
|
|
19215
|
+
export { ActivityHandling, AdapterSize, ApiError, ApiSpec, AuthType, Batches, Behavior, BlockedReason, Caches, CancelTuningJobResponse, Chat, Chats, ComputeTokensResponse, ContentReferenceImage, ControlReferenceImage, ControlReferenceType, CountTokensResponse, CreateFileResponse, DeleteCachedContentResponse, DeleteFileResponse, DeleteModelResponse, DocumentState, DynamicRetrievalConfigMode, EditImageResponse, EditMode, EmbedContentResponse, EndSensitivity, Environment, FeatureSelectionPreference, FileSource, FileState, Files, FinishReason, FunctionCallingConfigMode, FunctionResponse, FunctionResponseBlob, FunctionResponseFileData, FunctionResponsePart, FunctionResponseScheduling, GenerateContentResponse, GenerateContentResponsePromptFeedback, GenerateContentResponseUsageMetadata, GenerateImagesResponse, GenerateVideosOperation, GenerateVideosResponse, GoogleGenAI, HarmBlockMethod, HarmBlockThreshold, HarmCategory, HarmProbability, HarmSeverity, HttpElementLocation, HttpResponse, ImagePromptLanguage, ImportFileOperation, ImportFileResponse, InlinedEmbedContentResponse, InlinedResponse, JobState, Language, ListBatchJobsResponse, ListCachedContentsResponse, ListDocumentsResponse, ListFileSearchStoresResponse, ListFilesResponse, ListModelsResponse, ListTuningJobsResponse, Live, LiveClientToolResponse, LiveMusicPlaybackControl, LiveMusicServerMessage, LiveSendToolResponseParameters, LiveServerMessage, MaskReferenceImage, MaskReferenceMode, MediaModality, MediaResolution, Modality, Mode, Models, MusicGenerationMode, Operations, Outcome, PagedItem, Pager, PartMediaResolutionLevel, PersonGeneration, PhishBlockThreshold, RawReferenceImage, RecontextImageResponse, ReplayResponse, SafetyFilterLevel, Scale, SegmentImageResponse, SegmentMode, Session, SingleEmbedContentResponse, StartSensitivity, StyleReferenceImage, SubjectReferenceImage, SubjectReferenceType, ThinkingLevel, Tokens, TrafficType, TuningMethod, TuningMode, TuningTask, TurnCompleteReason, TurnCoverage, Type, UploadToFileSearchStoreOperation, UploadToFileSearchStoreResponse, UploadToFileSearchStoreResumableResponse, UpscaleImageResponse, UrlRetrievalStatus, VadSignalType, VideoCompressionQuality, VideoGenerationMaskMode, VideoGenerationReferenceType, createFunctionResponsePartFromBase64, createFunctionResponsePartFromUri, createModelContent, createPartFromBase64, createPartFromCodeExecutionResult, createPartFromExecutableCode, createPartFromFunctionCall, createPartFromFunctionResponse, createPartFromText, createPartFromUri, createUserContent, mcpToTool, setDefaultBaseUrls };
|
|
17162
19216
|
//# sourceMappingURL=index.mjs.map
|