@google/genai 1.31.0 → 1.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/genai.d.ts +2176 -10
- package/dist/index.cjs +2282 -199
- package/dist/index.mjs +2283 -200
- package/dist/index.mjs.map +1 -1
- package/dist/node/index.cjs +2288 -205
- package/dist/node/index.mjs +2289 -206
- package/dist/node/index.mjs.map +1 -1
- package/dist/node/node.d.ts +2176 -10
- package/dist/web/index.mjs +2203 -120
- package/dist/web/index.mjs.map +1 -1
- package/dist/web/web.d.ts +2176 -10
- package/package.json +7 -6
package/dist/web/index.mjs
CHANGED
|
@@ -959,6 +959,14 @@ var FinishReason;
|
|
|
959
959
|
* The model was expected to generate an image, but none was generated.
|
|
960
960
|
*/
|
|
961
961
|
FinishReason["NO_IMAGE"] = "NO_IMAGE";
|
|
962
|
+
/**
|
|
963
|
+
* Image generation stopped because the generated image may be a recitation from a source.
|
|
964
|
+
*/
|
|
965
|
+
FinishReason["IMAGE_RECITATION"] = "IMAGE_RECITATION";
|
|
966
|
+
/**
|
|
967
|
+
* Image generation stopped for a reason not otherwise specified.
|
|
968
|
+
*/
|
|
969
|
+
FinishReason["IMAGE_OTHER"] = "IMAGE_OTHER";
|
|
962
970
|
})(FinishReason || (FinishReason = {}));
|
|
963
971
|
/** Output only. Harm probability levels in the content. */
|
|
964
972
|
var HarmProbability;
|
|
@@ -1581,6 +1589,22 @@ var MediaModality;
|
|
|
1581
1589
|
*/
|
|
1582
1590
|
MediaModality["DOCUMENT"] = "DOCUMENT";
|
|
1583
1591
|
})(MediaModality || (MediaModality = {}));
|
|
1592
|
+
/** The type of the VAD signal. */
|
|
1593
|
+
var VadSignalType;
|
|
1594
|
+
(function (VadSignalType) {
|
|
1595
|
+
/**
|
|
1596
|
+
* The default is VAD_SIGNAL_TYPE_UNSPECIFIED.
|
|
1597
|
+
*/
|
|
1598
|
+
VadSignalType["VAD_SIGNAL_TYPE_UNSPECIFIED"] = "VAD_SIGNAL_TYPE_UNSPECIFIED";
|
|
1599
|
+
/**
|
|
1600
|
+
* Start of sentence signal.
|
|
1601
|
+
*/
|
|
1602
|
+
VadSignalType["VAD_SIGNAL_TYPE_SOS"] = "VAD_SIGNAL_TYPE_SOS";
|
|
1603
|
+
/**
|
|
1604
|
+
* End of sentence signal.
|
|
1605
|
+
*/
|
|
1606
|
+
VadSignalType["VAD_SIGNAL_TYPE_EOS"] = "VAD_SIGNAL_TYPE_EOS";
|
|
1607
|
+
})(VadSignalType || (VadSignalType = {}));
|
|
1584
1608
|
/** Start of speech sensitivity. */
|
|
1585
1609
|
var StartSensitivity;
|
|
1586
1610
|
(function (StartSensitivity) {
|
|
@@ -4113,6 +4137,12 @@ function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) {
|
|
|
4113
4137
|
if (fromImageConfig != null) {
|
|
4114
4138
|
setValueByPath(toObject, ['imageConfig'], imageConfigToMldev$1(fromImageConfig));
|
|
4115
4139
|
}
|
|
4140
|
+
const fromEnableEnhancedCivicAnswers = getValueByPath(fromObject, [
|
|
4141
|
+
'enableEnhancedCivicAnswers',
|
|
4142
|
+
]);
|
|
4143
|
+
if (fromEnableEnhancedCivicAnswers != null) {
|
|
4144
|
+
setValueByPath(toObject, ['enableEnhancedCivicAnswers'], fromEnableEnhancedCivicAnswers);
|
|
4145
|
+
}
|
|
4116
4146
|
return toObject;
|
|
4117
4147
|
}
|
|
4118
4148
|
function generateContentResponseFromMldev$1(fromObject) {
|
|
@@ -6245,6 +6275,18 @@ PERFORMANCE OF THIS SOFTWARE.
|
|
|
6245
6275
|
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
|
|
6246
6276
|
|
|
6247
6277
|
|
|
6278
|
+
function __rest(s, e) {
|
|
6279
|
+
var t = {};
|
|
6280
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
|
6281
|
+
t[p] = s[p];
|
|
6282
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
|
6283
|
+
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
6284
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
|
6285
|
+
t[p[i]] = s[p[i]];
|
|
6286
|
+
}
|
|
6287
|
+
return t;
|
|
6288
|
+
}
|
|
6289
|
+
|
|
6248
6290
|
function __values(o) {
|
|
6249
6291
|
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
|
|
6250
6292
|
if (m) return m.call(o);
|
|
@@ -6557,17 +6599,17 @@ class Chat {
|
|
|
6557
6599
|
return structuredClone(history);
|
|
6558
6600
|
}
|
|
6559
6601
|
processStreamResponse(streamResponse, inputContent) {
|
|
6560
|
-
var _a, _b;
|
|
6561
6602
|
return __asyncGenerator(this, arguments, function* processStreamResponse_1() {
|
|
6562
|
-
var
|
|
6603
|
+
var _a, e_1, _b, _c;
|
|
6604
|
+
var _d, _e;
|
|
6563
6605
|
const outputContent = [];
|
|
6564
6606
|
try {
|
|
6565
|
-
for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()),
|
|
6566
|
-
|
|
6607
|
+
for (var _f = true, streamResponse_1 = __asyncValues(streamResponse), streamResponse_1_1; streamResponse_1_1 = yield __await(streamResponse_1.next()), _a = streamResponse_1_1.done, !_a; _f = true) {
|
|
6608
|
+
_c = streamResponse_1_1.value;
|
|
6567
6609
|
_f = false;
|
|
6568
|
-
const chunk =
|
|
6610
|
+
const chunk = _c;
|
|
6569
6611
|
if (isValidResponse(chunk)) {
|
|
6570
|
-
const content = (
|
|
6612
|
+
const content = (_e = (_d = chunk.candidates) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.content;
|
|
6571
6613
|
if (content !== undefined) {
|
|
6572
6614
|
outputContent.push(content);
|
|
6573
6615
|
}
|
|
@@ -6578,7 +6620,7 @@ class Chat {
|
|
|
6578
6620
|
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
6579
6621
|
finally {
|
|
6580
6622
|
try {
|
|
6581
|
-
if (!_f && !
|
|
6623
|
+
if (!_f && !_a && (_b = streamResponse_1.return)) yield __await(_b.call(streamResponse_1));
|
|
6582
6624
|
}
|
|
6583
6625
|
finally { if (e_1) throw e_1.error; }
|
|
6584
6626
|
}
|
|
@@ -7371,6 +7413,9 @@ function liveConnectConfigToMldev$1(fromObject, parentObject) {
|
|
|
7371
7413
|
if (parentObject !== undefined && fromProactivity != null) {
|
|
7372
7414
|
setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity);
|
|
7373
7415
|
}
|
|
7416
|
+
if (getValueByPath(fromObject, ['explicitVadSignal']) !== undefined) {
|
|
7417
|
+
throw new Error('explicitVadSignal parameter is not supported in Gemini API.');
|
|
7418
|
+
}
|
|
7374
7419
|
return toObject;
|
|
7375
7420
|
}
|
|
7376
7421
|
function liveConnectConfigToVertex(fromObject, parentObject) {
|
|
@@ -7481,6 +7526,12 @@ function liveConnectConfigToVertex(fromObject, parentObject) {
|
|
|
7481
7526
|
if (parentObject !== undefined && fromProactivity != null) {
|
|
7482
7527
|
setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity);
|
|
7483
7528
|
}
|
|
7529
|
+
const fromExplicitVadSignal = getValueByPath(fromObject, [
|
|
7530
|
+
'explicitVadSignal',
|
|
7531
|
+
]);
|
|
7532
|
+
if (parentObject !== undefined && fromExplicitVadSignal != null) {
|
|
7533
|
+
setValueByPath(parentObject, ['setup', 'explicitVadSignal'], fromExplicitVadSignal);
|
|
7534
|
+
}
|
|
7484
7535
|
return toObject;
|
|
7485
7536
|
}
|
|
7486
7537
|
function liveConnectParametersToMldev(apiClient, fromObject) {
|
|
@@ -7657,6 +7708,12 @@ function liveServerMessageFromVertex(fromObject) {
|
|
|
7657
7708
|
if (fromSessionResumptionUpdate != null) {
|
|
7658
7709
|
setValueByPath(toObject, ['sessionResumptionUpdate'], fromSessionResumptionUpdate);
|
|
7659
7710
|
}
|
|
7711
|
+
const fromVoiceActivityDetectionSignal = getValueByPath(fromObject, [
|
|
7712
|
+
'voiceActivityDetectionSignal',
|
|
7713
|
+
]);
|
|
7714
|
+
if (fromVoiceActivityDetectionSignal != null) {
|
|
7715
|
+
setValueByPath(toObject, ['voiceActivityDetectionSignal'], fromVoiceActivityDetectionSignal);
|
|
7716
|
+
}
|
|
7660
7717
|
return toObject;
|
|
7661
7718
|
}
|
|
7662
7719
|
function partToMldev$2(fromObject) {
|
|
@@ -7732,14 +7789,14 @@ function sessionResumptionConfigToMldev$1(fromObject) {
|
|
|
7732
7789
|
}
|
|
7733
7790
|
function speechConfigToVertex$1(fromObject) {
|
|
7734
7791
|
const toObject = {};
|
|
7735
|
-
const fromLanguageCode = getValueByPath(fromObject, ['languageCode']);
|
|
7736
|
-
if (fromLanguageCode != null) {
|
|
7737
|
-
setValueByPath(toObject, ['languageCode'], fromLanguageCode);
|
|
7738
|
-
}
|
|
7739
7792
|
const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']);
|
|
7740
7793
|
if (fromVoiceConfig != null) {
|
|
7741
7794
|
setValueByPath(toObject, ['voiceConfig'], fromVoiceConfig);
|
|
7742
7795
|
}
|
|
7796
|
+
const fromLanguageCode = getValueByPath(fromObject, ['languageCode']);
|
|
7797
|
+
if (fromLanguageCode != null) {
|
|
7798
|
+
setValueByPath(toObject, ['languageCode'], fromLanguageCode);
|
|
7799
|
+
}
|
|
7743
7800
|
if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) {
|
|
7744
7801
|
throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.');
|
|
7745
7802
|
}
|
|
@@ -8835,6 +8892,12 @@ function generateContentConfigToMldev(apiClient, fromObject, parentObject) {
|
|
|
8835
8892
|
if (fromImageConfig != null) {
|
|
8836
8893
|
setValueByPath(toObject, ['imageConfig'], imageConfigToMldev(fromImageConfig));
|
|
8837
8894
|
}
|
|
8895
|
+
const fromEnableEnhancedCivicAnswers = getValueByPath(fromObject, [
|
|
8896
|
+
'enableEnhancedCivicAnswers',
|
|
8897
|
+
]);
|
|
8898
|
+
if (fromEnableEnhancedCivicAnswers != null) {
|
|
8899
|
+
setValueByPath(toObject, ['enableEnhancedCivicAnswers'], fromEnableEnhancedCivicAnswers);
|
|
8900
|
+
}
|
|
8838
8901
|
return toObject;
|
|
8839
8902
|
}
|
|
8840
8903
|
function generateContentConfigToVertex(apiClient, fromObject, parentObject) {
|
|
@@ -8999,6 +9062,10 @@ function generateContentConfigToVertex(apiClient, fromObject, parentObject) {
|
|
|
8999
9062
|
if (fromImageConfig != null) {
|
|
9000
9063
|
setValueByPath(toObject, ['imageConfig'], imageConfigToVertex(fromImageConfig));
|
|
9001
9064
|
}
|
|
9065
|
+
if (getValueByPath(fromObject, ['enableEnhancedCivicAnswers']) !==
|
|
9066
|
+
undefined) {
|
|
9067
|
+
throw new Error('enableEnhancedCivicAnswers parameter is not supported in Vertex AI.');
|
|
9068
|
+
}
|
|
9002
9069
|
return toObject;
|
|
9003
9070
|
}
|
|
9004
9071
|
function generateContentParametersToMldev(apiClient, fromObject) {
|
|
@@ -10727,14 +10794,14 @@ function segmentImageSourceToVertex(fromObject, parentObject) {
|
|
|
10727
10794
|
}
|
|
10728
10795
|
function speechConfigToVertex(fromObject) {
|
|
10729
10796
|
const toObject = {};
|
|
10730
|
-
const fromLanguageCode = getValueByPath(fromObject, ['languageCode']);
|
|
10731
|
-
if (fromLanguageCode != null) {
|
|
10732
|
-
setValueByPath(toObject, ['languageCode'], fromLanguageCode);
|
|
10733
|
-
}
|
|
10734
10797
|
const fromVoiceConfig = getValueByPath(fromObject, ['voiceConfig']);
|
|
10735
10798
|
if (fromVoiceConfig != null) {
|
|
10736
10799
|
setValueByPath(toObject, ['voiceConfig'], fromVoiceConfig);
|
|
10737
10800
|
}
|
|
10801
|
+
const fromLanguageCode = getValueByPath(fromObject, ['languageCode']);
|
|
10802
|
+
if (fromLanguageCode != null) {
|
|
10803
|
+
setValueByPath(toObject, ['languageCode'], fromLanguageCode);
|
|
10804
|
+
}
|
|
10738
10805
|
if (getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined) {
|
|
10739
10806
|
throw new Error('multiSpeakerVoiceConfig parameter is not supported in Vertex AI.');
|
|
10740
10807
|
}
|
|
@@ -11421,11 +11488,10 @@ const CONTENT_TYPE_HEADER = 'Content-Type';
|
|
|
11421
11488
|
const SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';
|
|
11422
11489
|
const USER_AGENT_HEADER = 'User-Agent';
|
|
11423
11490
|
const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';
|
|
11424
|
-
const SDK_VERSION = '1.
|
|
11491
|
+
const SDK_VERSION = '1.33.0'; // x-release-please-version
|
|
11425
11492
|
const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;
|
|
11426
11493
|
const VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';
|
|
11427
11494
|
const GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';
|
|
11428
|
-
const responseLineRE = /^\s*data: (.*)(?:\n\n|\r\r|\r\n\r\n)/;
|
|
11429
11495
|
/**
|
|
11430
11496
|
* The ApiClient class is used to send requests to the Gemini API or Vertex AI
|
|
11431
11497
|
* endpoints.
|
|
@@ -11705,8 +11771,8 @@ class ApiClient {
|
|
|
11705
11771
|
});
|
|
11706
11772
|
}
|
|
11707
11773
|
processStreamResponse(response) {
|
|
11708
|
-
var _a;
|
|
11709
11774
|
return __asyncGenerator(this, arguments, function* processStreamResponse_1() {
|
|
11775
|
+
var _a;
|
|
11710
11776
|
const reader = (_a = response === null || response === void 0 ? void 0 : response.body) === null || _a === void 0 ? void 0 : _a.getReader();
|
|
11711
11777
|
const decoder = new TextDecoder('utf-8');
|
|
11712
11778
|
if (!reader) {
|
|
@@ -11714,6 +11780,8 @@ class ApiClient {
|
|
|
11714
11780
|
}
|
|
11715
11781
|
try {
|
|
11716
11782
|
let buffer = '';
|
|
11783
|
+
const dataPrefix = 'data:';
|
|
11784
|
+
const delimiters = ['\n\n', '\r\r', '\r\n\r\n'];
|
|
11717
11785
|
while (true) {
|
|
11718
11786
|
const { done, value } = yield __await(reader.read());
|
|
11719
11787
|
if (done) {
|
|
@@ -11747,21 +11815,40 @@ class ApiClient {
|
|
|
11747
11815
|
}
|
|
11748
11816
|
}
|
|
11749
11817
|
buffer += chunkString;
|
|
11750
|
-
let
|
|
11751
|
-
|
|
11752
|
-
|
|
11753
|
-
|
|
11754
|
-
|
|
11755
|
-
|
|
11756
|
-
|
|
11757
|
-
|
|
11758
|
-
|
|
11759
|
-
|
|
11760
|
-
|
|
11761
|
-
|
|
11818
|
+
let delimiterIndex = -1;
|
|
11819
|
+
let delimiterLength = 0;
|
|
11820
|
+
while (true) {
|
|
11821
|
+
delimiterIndex = -1;
|
|
11822
|
+
delimiterLength = 0;
|
|
11823
|
+
for (const delimiter of delimiters) {
|
|
11824
|
+
const index = buffer.indexOf(delimiter);
|
|
11825
|
+
if (index !== -1 &&
|
|
11826
|
+
(delimiterIndex === -1 || index < delimiterIndex)) {
|
|
11827
|
+
delimiterIndex = index;
|
|
11828
|
+
delimiterLength = delimiter.length;
|
|
11829
|
+
}
|
|
11830
|
+
}
|
|
11831
|
+
if (delimiterIndex === -1) {
|
|
11832
|
+
break; // No complete event in buffer
|
|
11762
11833
|
}
|
|
11763
|
-
|
|
11764
|
-
|
|
11834
|
+
const eventString = buffer.substring(0, delimiterIndex);
|
|
11835
|
+
buffer = buffer.substring(delimiterIndex + delimiterLength);
|
|
11836
|
+
const trimmedEvent = eventString.trim();
|
|
11837
|
+
if (trimmedEvent.startsWith(dataPrefix)) {
|
|
11838
|
+
const processedChunkString = trimmedEvent
|
|
11839
|
+
.substring(dataPrefix.length)
|
|
11840
|
+
.trim();
|
|
11841
|
+
try {
|
|
11842
|
+
const partialResponse = new Response(processedChunkString, {
|
|
11843
|
+
headers: response === null || response === void 0 ? void 0 : response.headers,
|
|
11844
|
+
status: response === null || response === void 0 ? void 0 : response.status,
|
|
11845
|
+
statusText: response === null || response === void 0 ? void 0 : response.statusText,
|
|
11846
|
+
});
|
|
11847
|
+
yield yield __await(new HttpResponse(partialResponse));
|
|
11848
|
+
}
|
|
11849
|
+
catch (e) {
|
|
11850
|
+
throw new Error(`exception parsing stream chunk ${processedChunkString}. ${e}`);
|
|
11851
|
+
}
|
|
11765
11852
|
}
|
|
11766
11853
|
}
|
|
11767
11854
|
}
|
|
@@ -11894,7 +11981,7 @@ class ApiClient {
|
|
|
11894
11981
|
}
|
|
11895
11982
|
else {
|
|
11896
11983
|
httpOptions = {
|
|
11897
|
-
apiVersion: '',
|
|
11984
|
+
apiVersion: '', // api-version is set in the path.
|
|
11898
11985
|
headers: Object.assign({ 'Content-Type': 'application/json', 'X-Goog-Upload-Protocol': 'resumable', 'X-Goog-Upload-Command': 'start', 'X-Goog-Upload-Header-Content-Length': `${sizeBytes}`, 'X-Goog-Upload-Header-Content-Type': `${mimeType}` }, (fileName ? { 'X-Goog-Upload-File-Name': fileName } : {})),
|
|
11899
11986
|
};
|
|
11900
11987
|
}
|
|
@@ -12056,8 +12143,8 @@ function isMcpCallableTool(object) {
|
|
|
12056
12143
|
object instanceof McpCallableTool);
|
|
12057
12144
|
}
|
|
12058
12145
|
// List all tools from the MCP client.
|
|
12059
|
-
function listAllTools(
|
|
12060
|
-
return __asyncGenerator(this, arguments, function* listAllTools_1() {
|
|
12146
|
+
function listAllTools(mcpClient_1) {
|
|
12147
|
+
return __asyncGenerator(this, arguments, function* listAllTools_1(mcpClient, maxTools = 100) {
|
|
12061
12148
|
let cursor = undefined;
|
|
12062
12149
|
let numTools = 0;
|
|
12063
12150
|
while (numTools < maxTools) {
|
|
@@ -13377,9 +13464,9 @@ class Models extends BaseModule {
|
|
|
13377
13464
|
let remoteCallCount = 0;
|
|
13378
13465
|
const afcToolsMap = await this.initAfcToolsMap(params);
|
|
13379
13466
|
return (function (models, afcTools, params) {
|
|
13380
|
-
var _a, _b;
|
|
13381
13467
|
return __asyncGenerator(this, arguments, function* () {
|
|
13382
|
-
var
|
|
13468
|
+
var _a, e_1, _b, _c;
|
|
13469
|
+
var _d, _e;
|
|
13383
13470
|
while (remoteCallCount < maxRemoteCalls) {
|
|
13384
13471
|
if (wereFunctionsCalled) {
|
|
13385
13472
|
remoteCallCount++;
|
|
@@ -13390,14 +13477,14 @@ class Models extends BaseModule {
|
|
|
13390
13477
|
const functionResponses = [];
|
|
13391
13478
|
const responseContents = [];
|
|
13392
13479
|
try {
|
|
13393
|
-
for (var _f = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()),
|
|
13394
|
-
|
|
13480
|
+
for (var _f = true, response_1 = (e_1 = void 0, __asyncValues(response)), response_1_1; response_1_1 = yield __await(response_1.next()), _a = response_1_1.done, !_a; _f = true) {
|
|
13481
|
+
_c = response_1_1.value;
|
|
13395
13482
|
_f = false;
|
|
13396
|
-
const chunk =
|
|
13483
|
+
const chunk = _c;
|
|
13397
13484
|
yield yield __await(chunk);
|
|
13398
|
-
if (chunk.candidates && ((
|
|
13485
|
+
if (chunk.candidates && ((_d = chunk.candidates[0]) === null || _d === void 0 ? void 0 : _d.content)) {
|
|
13399
13486
|
responseContents.push(chunk.candidates[0].content);
|
|
13400
|
-
for (const part of (
|
|
13487
|
+
for (const part of (_e = chunk.candidates[0].content.parts) !== null && _e !== void 0 ? _e : []) {
|
|
13401
13488
|
if (remoteCallCount < maxRemoteCalls && part.functionCall) {
|
|
13402
13489
|
if (!part.functionCall.name) {
|
|
13403
13490
|
throw new Error('Function call name was not returned by the model.');
|
|
@@ -13419,7 +13506,7 @@ class Models extends BaseModule {
|
|
|
13419
13506
|
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
13420
13507
|
finally {
|
|
13421
13508
|
try {
|
|
13422
|
-
if (!_f && !
|
|
13509
|
+
if (!_f && !_a && (_b = response_1.return)) yield __await(_b.call(response_1));
|
|
13423
13510
|
}
|
|
13424
13511
|
finally { if (e_1) throw e_1.error; }
|
|
13425
13512
|
}
|
|
@@ -14873,6 +14960,9 @@ function liveConnectConfigToMldev(fromObject, parentObject) {
|
|
|
14873
14960
|
if (parentObject !== undefined && fromProactivity != null) {
|
|
14874
14961
|
setValueByPath(parentObject, ['setup', 'proactivity'], fromProactivity);
|
|
14875
14962
|
}
|
|
14963
|
+
if (getValueByPath(fromObject, ['explicitVadSignal']) !== undefined) {
|
|
14964
|
+
throw new Error('explicitVadSignal parameter is not supported in Gemini API.');
|
|
14965
|
+
}
|
|
14876
14966
|
return toObject;
|
|
14877
14967
|
}
|
|
14878
14968
|
function liveConnectConstraintsToMldev(apiClient, fromObject) {
|
|
@@ -15785,104 +15875,2075 @@ class FileSearchStores extends BaseModule {
|
|
|
15785
15875
|
* Copyright 2025 Google LLC
|
|
15786
15876
|
* SPDX-License-Identifier: Apache-2.0
|
|
15787
15877
|
*/
|
|
15788
|
-
//
|
|
15789
|
-
|
|
15790
|
-
|
|
15791
|
-
|
|
15792
|
-
|
|
15793
|
-
|
|
15878
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
15879
|
+
/**
|
|
15880
|
+
* https://stackoverflow.com/a/2117523
|
|
15881
|
+
*/
|
|
15882
|
+
let uuid4Internal = function () {
|
|
15883
|
+
const { crypto } = globalThis;
|
|
15884
|
+
if (crypto === null || crypto === void 0 ? void 0 : crypto.randomUUID) {
|
|
15885
|
+
uuid4Internal = crypto.randomUUID.bind(crypto);
|
|
15886
|
+
return crypto.randomUUID();
|
|
15887
|
+
}
|
|
15888
|
+
const u8 = new Uint8Array(1);
|
|
15889
|
+
const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff;
|
|
15890
|
+
return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16));
|
|
15891
|
+
};
|
|
15892
|
+
const uuid4 = () => uuid4Internal();
|
|
15893
|
+
|
|
15894
|
+
/**
|
|
15895
|
+
* @license
|
|
15896
|
+
* Copyright 2025 Google LLC
|
|
15897
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
15898
|
+
*/
|
|
15899
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
15900
|
+
function isAbortError(err) {
|
|
15901
|
+
return (typeof err === 'object' &&
|
|
15902
|
+
err !== null &&
|
|
15903
|
+
// Spec-compliant fetch implementations
|
|
15904
|
+
(('name' in err && err.name === 'AbortError') ||
|
|
15905
|
+
// Expo fetch
|
|
15906
|
+
('message' in err && String(err.message).includes('FetchRequestCanceledException'))));
|
|
15907
|
+
}
|
|
15908
|
+
const castToError = (err) => {
|
|
15909
|
+
if (err instanceof Error)
|
|
15910
|
+
return err;
|
|
15911
|
+
if (typeof err === 'object' && err !== null) {
|
|
15912
|
+
try {
|
|
15913
|
+
if (Object.prototype.toString.call(err) === '[object Error]') {
|
|
15914
|
+
// @ts-ignore - not all envs have native support for cause yet
|
|
15915
|
+
const error = new Error(err.message, err.cause ? { cause: err.cause } : {});
|
|
15916
|
+
if (err.stack)
|
|
15917
|
+
error.stack = err.stack;
|
|
15918
|
+
// @ts-ignore - not all envs have native support for cause yet
|
|
15919
|
+
if (err.cause && !error.cause)
|
|
15920
|
+
error.cause = err.cause;
|
|
15921
|
+
if (err.name)
|
|
15922
|
+
error.name = err.name;
|
|
15923
|
+
return error;
|
|
15924
|
+
}
|
|
15925
|
+
}
|
|
15926
|
+
catch (_a) { }
|
|
15927
|
+
try {
|
|
15928
|
+
return new Error(JSON.stringify(err));
|
|
15929
|
+
}
|
|
15930
|
+
catch (_b) { }
|
|
15794
15931
|
}
|
|
15795
|
-
return
|
|
15932
|
+
return new Error(err);
|
|
15933
|
+
};
|
|
15934
|
+
|
|
15935
|
+
/**
|
|
15936
|
+
* @license
|
|
15937
|
+
* Copyright 2025 Google LLC
|
|
15938
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
15939
|
+
*/
|
|
15940
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
15941
|
+
class GeminiNextGenAPIClientError extends Error {
|
|
15796
15942
|
}
|
|
15797
|
-
|
|
15798
|
-
|
|
15799
|
-
|
|
15800
|
-
|
|
15801
|
-
|
|
15943
|
+
class APIError extends GeminiNextGenAPIClientError {
|
|
15944
|
+
constructor(status, error, message, headers) {
|
|
15945
|
+
super(`${APIError.makeMessage(status, error, message)}`);
|
|
15946
|
+
this.status = status;
|
|
15947
|
+
this.headers = headers;
|
|
15948
|
+
this.error = error;
|
|
15949
|
+
}
|
|
15950
|
+
static makeMessage(status, error, message) {
|
|
15951
|
+
const msg = (error === null || error === void 0 ? void 0 : error.message) ?
|
|
15952
|
+
typeof error.message === 'string' ?
|
|
15953
|
+
error.message
|
|
15954
|
+
: JSON.stringify(error.message)
|
|
15955
|
+
: error ? JSON.stringify(error)
|
|
15956
|
+
: message;
|
|
15957
|
+
if (status && msg) {
|
|
15958
|
+
return `${status} ${msg}`;
|
|
15959
|
+
}
|
|
15960
|
+
if (status) {
|
|
15961
|
+
return `${status} status code (no body)`;
|
|
15962
|
+
}
|
|
15963
|
+
if (msg) {
|
|
15964
|
+
return msg;
|
|
15965
|
+
}
|
|
15966
|
+
return '(no status code or body)';
|
|
15967
|
+
}
|
|
15968
|
+
static generate(status, errorResponse, message, headers) {
|
|
15969
|
+
if (!status || !headers) {
|
|
15970
|
+
return new APIConnectionError({ message, cause: castToError(errorResponse) });
|
|
15971
|
+
}
|
|
15972
|
+
const error = errorResponse;
|
|
15973
|
+
if (status === 400) {
|
|
15974
|
+
return new BadRequestError(status, error, message, headers);
|
|
15975
|
+
}
|
|
15976
|
+
if (status === 401) {
|
|
15977
|
+
return new AuthenticationError(status, error, message, headers);
|
|
15978
|
+
}
|
|
15979
|
+
if (status === 403) {
|
|
15980
|
+
return new PermissionDeniedError(status, error, message, headers);
|
|
15981
|
+
}
|
|
15982
|
+
if (status === 404) {
|
|
15983
|
+
return new NotFoundError(status, error, message, headers);
|
|
15984
|
+
}
|
|
15985
|
+
if (status === 409) {
|
|
15986
|
+
return new ConflictError(status, error, message, headers);
|
|
15987
|
+
}
|
|
15988
|
+
if (status === 422) {
|
|
15989
|
+
return new UnprocessableEntityError(status, error, message, headers);
|
|
15990
|
+
}
|
|
15991
|
+
if (status === 429) {
|
|
15992
|
+
return new RateLimitError(status, error, message, headers);
|
|
15993
|
+
}
|
|
15994
|
+
if (status >= 500) {
|
|
15995
|
+
return new InternalServerError(status, error, message, headers);
|
|
15996
|
+
}
|
|
15997
|
+
return new APIError(status, error, message, headers);
|
|
15802
15998
|
}
|
|
15803
|
-
return toObject;
|
|
15804
15999
|
}
|
|
15805
|
-
|
|
15806
|
-
|
|
15807
|
-
|
|
15808
|
-
'sdkHttpResponse',
|
|
15809
|
-
]);
|
|
15810
|
-
if (fromSdkHttpResponse != null) {
|
|
15811
|
-
setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);
|
|
16000
|
+
class APIUserAbortError extends APIError {
|
|
16001
|
+
constructor({ message } = {}) {
|
|
16002
|
+
super(undefined, undefined, message || 'Request was aborted.', undefined);
|
|
15812
16003
|
}
|
|
15813
|
-
return toObject;
|
|
15814
16004
|
}
|
|
15815
|
-
|
|
15816
|
-
|
|
15817
|
-
|
|
15818
|
-
'
|
|
15819
|
-
|
|
15820
|
-
|
|
15821
|
-
|
|
16005
|
+
class APIConnectionError extends APIError {
|
|
16006
|
+
constructor({ message, cause }) {
|
|
16007
|
+
super(undefined, undefined, message || 'Connection error.', undefined);
|
|
16008
|
+
// in some environments the 'cause' property is already declared
|
|
16009
|
+
// @ts-ignore
|
|
16010
|
+
if (cause)
|
|
16011
|
+
this.cause = cause;
|
|
15822
16012
|
}
|
|
15823
|
-
return toObject;
|
|
15824
16013
|
}
|
|
15825
|
-
|
|
15826
|
-
|
|
15827
|
-
|
|
15828
|
-
throw new Error('validationDataset parameter is not supported in Gemini API.');
|
|
16014
|
+
class APIConnectionTimeoutError extends APIConnectionError {
|
|
16015
|
+
constructor({ message } = {}) {
|
|
16016
|
+
super({ message: message !== null && message !== void 0 ? message : 'Request timed out.' });
|
|
15829
16017
|
}
|
|
15830
|
-
|
|
15831
|
-
|
|
15832
|
-
|
|
15833
|
-
|
|
15834
|
-
|
|
16018
|
+
}
|
|
16019
|
+
class BadRequestError extends APIError {
|
|
16020
|
+
}
|
|
16021
|
+
class AuthenticationError extends APIError {
|
|
16022
|
+
}
|
|
16023
|
+
class PermissionDeniedError extends APIError {
|
|
16024
|
+
}
|
|
16025
|
+
class NotFoundError extends APIError {
|
|
16026
|
+
}
|
|
16027
|
+
class ConflictError extends APIError {
|
|
16028
|
+
}
|
|
16029
|
+
class UnprocessableEntityError extends APIError {
|
|
16030
|
+
}
|
|
16031
|
+
class RateLimitError extends APIError {
|
|
16032
|
+
}
|
|
16033
|
+
class InternalServerError extends APIError {
|
|
16034
|
+
}
|
|
16035
|
+
|
|
16036
|
+
/**
|
|
16037
|
+
* @license
|
|
16038
|
+
* Copyright 2025 Google LLC
|
|
16039
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16040
|
+
*/
|
|
16041
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
16042
|
+
// https://url.spec.whatwg.org/#url-scheme-string
|
|
16043
|
+
const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
|
|
16044
|
+
const isAbsoluteURL = (url) => {
|
|
16045
|
+
return startsWithSchemeRegexp.test(url);
|
|
16046
|
+
};
|
|
16047
|
+
let isArrayInternal = (val) => ((isArrayInternal = Array.isArray), isArrayInternal(val));
|
|
16048
|
+
const isArray = isArrayInternal;
|
|
16049
|
+
let isReadonlyArrayInternal = isArray;
|
|
16050
|
+
const isReadonlyArray = isReadonlyArrayInternal;
|
|
16051
|
+
// https://stackoverflow.com/a/34491287
|
|
16052
|
+
function isEmptyObj(obj) {
|
|
16053
|
+
if (!obj)
|
|
16054
|
+
return true;
|
|
16055
|
+
for (const _k in obj)
|
|
16056
|
+
return false;
|
|
16057
|
+
return true;
|
|
16058
|
+
}
|
|
16059
|
+
// https://eslint.org/docs/latest/rules/no-prototype-builtins
|
|
16060
|
+
function hasOwn(obj, key) {
|
|
16061
|
+
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
16062
|
+
}
|
|
16063
|
+
const validatePositiveInteger = (name, n) => {
|
|
16064
|
+
if (typeof n !== 'number' || !Number.isInteger(n)) {
|
|
16065
|
+
throw new GeminiNextGenAPIClientError(`${name} must be an integer`);
|
|
15835
16066
|
}
|
|
15836
|
-
if (
|
|
15837
|
-
throw new
|
|
16067
|
+
if (n < 0) {
|
|
16068
|
+
throw new GeminiNextGenAPIClientError(`${name} must be a positive integer`);
|
|
15838
16069
|
}
|
|
15839
|
-
|
|
15840
|
-
|
|
15841
|
-
|
|
16070
|
+
return n;
|
|
16071
|
+
};
|
|
16072
|
+
const safeJSON = (text) => {
|
|
16073
|
+
try {
|
|
16074
|
+
return JSON.parse(text);
|
|
15842
16075
|
}
|
|
15843
|
-
|
|
15844
|
-
|
|
15845
|
-
]);
|
|
15846
|
-
if (fromLearningRateMultiplier != null) {
|
|
15847
|
-
setValueByPath(toObject, ['tuningTask', 'hyperparameters', 'learningRateMultiplier'], fromLearningRateMultiplier);
|
|
16076
|
+
catch (err) {
|
|
16077
|
+
return undefined;
|
|
15848
16078
|
}
|
|
15849
|
-
|
|
15850
|
-
|
|
15851
|
-
|
|
16079
|
+
};
|
|
16080
|
+
|
|
16081
|
+
/**
|
|
16082
|
+
* @license
|
|
16083
|
+
* Copyright 2025 Google LLC
|
|
16084
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16085
|
+
*/
|
|
16086
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
16087
|
+
const sleep$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
16088
|
+
|
|
16089
|
+
/**
|
|
16090
|
+
* @license
|
|
16091
|
+
* Copyright 2025 Google LLC
|
|
16092
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16093
|
+
*/
|
|
16094
|
+
const VERSION = '0.0.1';
|
|
16095
|
+
|
|
16096
|
+
/**
|
|
16097
|
+
* @license
|
|
16098
|
+
* Copyright 2025 Google LLC
|
|
16099
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16100
|
+
*/
|
|
16101
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
16102
|
+
/**
|
|
16103
|
+
* Note this does not detect 'browser'; for that, use getBrowserInfo().
|
|
16104
|
+
*/
|
|
16105
|
+
function getDetectedPlatform() {
|
|
16106
|
+
if (typeof Deno !== 'undefined' && Deno.build != null) {
|
|
16107
|
+
return 'deno';
|
|
15852
16108
|
}
|
|
15853
|
-
if (
|
|
15854
|
-
|
|
15855
|
-
throw new Error('preTunedModelCheckpointId parameter is not supported in Gemini API.');
|
|
16109
|
+
if (typeof EdgeRuntime !== 'undefined') {
|
|
16110
|
+
return 'edge';
|
|
15856
16111
|
}
|
|
15857
|
-
if (
|
|
15858
|
-
|
|
16112
|
+
if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') {
|
|
16113
|
+
return 'node';
|
|
15859
16114
|
}
|
|
15860
|
-
|
|
15861
|
-
|
|
15862
|
-
|
|
16115
|
+
return 'unknown';
|
|
16116
|
+
}
|
|
16117
|
+
const getPlatformProperties = () => {
|
|
16118
|
+
var _a, _b, _c, _d, _e;
|
|
16119
|
+
const detectedPlatform = getDetectedPlatform();
|
|
16120
|
+
if (detectedPlatform === 'deno') {
|
|
16121
|
+
return {
|
|
16122
|
+
'X-Stainless-Lang': 'js',
|
|
16123
|
+
'X-Stainless-Package-Version': VERSION,
|
|
16124
|
+
'X-Stainless-OS': normalizePlatform(Deno.build.os),
|
|
16125
|
+
'X-Stainless-Arch': normalizeArch(Deno.build.arch),
|
|
16126
|
+
'X-Stainless-Runtime': 'deno',
|
|
16127
|
+
'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',
|
|
16128
|
+
};
|
|
15863
16129
|
}
|
|
15864
|
-
|
|
15865
|
-
|
|
15866
|
-
|
|
16130
|
+
if (typeof EdgeRuntime !== 'undefined') {
|
|
16131
|
+
return {
|
|
16132
|
+
'X-Stainless-Lang': 'js',
|
|
16133
|
+
'X-Stainless-Package-Version': VERSION,
|
|
16134
|
+
'X-Stainless-OS': 'Unknown',
|
|
16135
|
+
'X-Stainless-Arch': `other:${EdgeRuntime}`,
|
|
16136
|
+
'X-Stainless-Runtime': 'edge',
|
|
16137
|
+
'X-Stainless-Runtime-Version': globalThis.process.version,
|
|
16138
|
+
};
|
|
15867
16139
|
}
|
|
15868
|
-
|
|
15869
|
-
|
|
16140
|
+
// Check if Node.js
|
|
16141
|
+
if (detectedPlatform === 'node') {
|
|
16142
|
+
return {
|
|
16143
|
+
'X-Stainless-Lang': 'js',
|
|
16144
|
+
'X-Stainless-Package-Version': VERSION,
|
|
16145
|
+
'X-Stainless-OS': normalizePlatform((_c = globalThis.process.platform) !== null && _c !== void 0 ? _c : 'unknown'),
|
|
16146
|
+
'X-Stainless-Arch': normalizeArch((_d = globalThis.process.arch) !== null && _d !== void 0 ? _d : 'unknown'),
|
|
16147
|
+
'X-Stainless-Runtime': 'node',
|
|
16148
|
+
'X-Stainless-Runtime-Version': (_e = globalThis.process.version) !== null && _e !== void 0 ? _e : 'unknown',
|
|
16149
|
+
};
|
|
15870
16150
|
}
|
|
15871
|
-
|
|
15872
|
-
|
|
16151
|
+
const browserInfo = getBrowserInfo();
|
|
16152
|
+
if (browserInfo) {
|
|
16153
|
+
return {
|
|
16154
|
+
'X-Stainless-Lang': 'js',
|
|
16155
|
+
'X-Stainless-Package-Version': VERSION,
|
|
16156
|
+
'X-Stainless-OS': 'Unknown',
|
|
16157
|
+
'X-Stainless-Arch': 'unknown',
|
|
16158
|
+
'X-Stainless-Runtime': `browser:${browserInfo.browser}`,
|
|
16159
|
+
'X-Stainless-Runtime-Version': browserInfo.version,
|
|
16160
|
+
};
|
|
15873
16161
|
}
|
|
15874
|
-
|
|
16162
|
+
// TODO add support for Cloudflare workers, etc.
|
|
16163
|
+
return {
|
|
16164
|
+
'X-Stainless-Lang': 'js',
|
|
16165
|
+
'X-Stainless-Package-Version': VERSION,
|
|
16166
|
+
'X-Stainless-OS': 'Unknown',
|
|
16167
|
+
'X-Stainless-Arch': 'unknown',
|
|
16168
|
+
'X-Stainless-Runtime': 'unknown',
|
|
16169
|
+
'X-Stainless-Runtime-Version': 'unknown',
|
|
16170
|
+
};
|
|
16171
|
+
};
|
|
16172
|
+
// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts
|
|
16173
|
+
function getBrowserInfo() {
|
|
16174
|
+
if (typeof navigator === 'undefined' || !navigator) {
|
|
16175
|
+
return null;
|
|
16176
|
+
}
|
|
16177
|
+
// NOTE: The order matters here!
|
|
16178
|
+
const browserPatterns = [
|
|
16179
|
+
{ key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
16180
|
+
{ key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
16181
|
+
{ key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
16182
|
+
{ key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
16183
|
+
{ key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ },
|
|
16184
|
+
{ key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ },
|
|
16185
|
+
];
|
|
16186
|
+
// Find the FIRST matching browser
|
|
16187
|
+
for (const { key, pattern } of browserPatterns) {
|
|
16188
|
+
const match = pattern.exec(navigator.userAgent);
|
|
16189
|
+
if (match) {
|
|
16190
|
+
const major = match[1] || 0;
|
|
16191
|
+
const minor = match[2] || 0;
|
|
16192
|
+
const patch = match[3] || 0;
|
|
16193
|
+
return { browser: key, version: `${major}.${minor}.${patch}` };
|
|
16194
|
+
}
|
|
16195
|
+
}
|
|
16196
|
+
return null;
|
|
16197
|
+
}
|
|
16198
|
+
const normalizeArch = (arch) => {
|
|
16199
|
+
// Node docs:
|
|
16200
|
+
// - https://nodejs.org/api/process.html#processarch
|
|
16201
|
+
// Deno docs:
|
|
16202
|
+
// - https://doc.deno.land/deno/stable/~/Deno.build
|
|
16203
|
+
if (arch === 'x32')
|
|
16204
|
+
return 'x32';
|
|
16205
|
+
if (arch === 'x86_64' || arch === 'x64')
|
|
16206
|
+
return 'x64';
|
|
16207
|
+
if (arch === 'arm')
|
|
16208
|
+
return 'arm';
|
|
16209
|
+
if (arch === 'aarch64' || arch === 'arm64')
|
|
16210
|
+
return 'arm64';
|
|
16211
|
+
if (arch)
|
|
16212
|
+
return `other:${arch}`;
|
|
16213
|
+
return 'unknown';
|
|
16214
|
+
};
|
|
16215
|
+
const normalizePlatform = (platform) => {
|
|
16216
|
+
// Node platforms:
|
|
16217
|
+
// - https://nodejs.org/api/process.html#processplatform
|
|
16218
|
+
// Deno platforms:
|
|
16219
|
+
// - https://doc.deno.land/deno/stable/~/Deno.build
|
|
16220
|
+
// - https://github.com/denoland/deno/issues/14799
|
|
16221
|
+
platform = platform.toLowerCase();
|
|
16222
|
+
// NOTE: this iOS check is untested and may not work
|
|
16223
|
+
// Node does not work natively on IOS, there is a fork at
|
|
16224
|
+
// https://github.com/nodejs-mobile/nodejs-mobile
|
|
16225
|
+
// however it is unknown at the time of writing how to detect if it is running
|
|
16226
|
+
if (platform.includes('ios'))
|
|
16227
|
+
return 'iOS';
|
|
16228
|
+
if (platform === 'android')
|
|
16229
|
+
return 'Android';
|
|
16230
|
+
if (platform === 'darwin')
|
|
16231
|
+
return 'MacOS';
|
|
16232
|
+
if (platform === 'win32')
|
|
16233
|
+
return 'Windows';
|
|
16234
|
+
if (platform === 'freebsd')
|
|
16235
|
+
return 'FreeBSD';
|
|
16236
|
+
if (platform === 'openbsd')
|
|
16237
|
+
return 'OpenBSD';
|
|
16238
|
+
if (platform === 'linux')
|
|
16239
|
+
return 'Linux';
|
|
16240
|
+
if (platform)
|
|
16241
|
+
return `Other:${platform}`;
|
|
16242
|
+
return 'Unknown';
|
|
16243
|
+
};
|
|
16244
|
+
let _platformHeaders;
|
|
16245
|
+
const getPlatformHeaders = () => {
|
|
16246
|
+
return (_platformHeaders !== null && _platformHeaders !== void 0 ? _platformHeaders : (_platformHeaders = getPlatformProperties()));
|
|
16247
|
+
};
|
|
16248
|
+
|
|
16249
|
+
/**
|
|
16250
|
+
* @license
|
|
16251
|
+
* Copyright 2025 Google LLC
|
|
16252
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16253
|
+
*/
|
|
16254
|
+
function getDefaultFetch() {
|
|
16255
|
+
if (typeof fetch !== 'undefined') {
|
|
16256
|
+
return fetch;
|
|
16257
|
+
}
|
|
16258
|
+
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`');
|
|
16259
|
+
}
|
|
16260
|
+
function makeReadableStream(...args) {
|
|
16261
|
+
const ReadableStream = globalThis.ReadableStream;
|
|
16262
|
+
if (typeof ReadableStream === 'undefined') {
|
|
16263
|
+
// Note: All of the platforms / runtimes we officially support already define
|
|
16264
|
+
// `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes.
|
|
16265
|
+
throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`');
|
|
16266
|
+
}
|
|
16267
|
+
return new ReadableStream(...args);
|
|
16268
|
+
}
|
|
16269
|
+
function ReadableStreamFrom(iterable) {
|
|
16270
|
+
let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
|
|
16271
|
+
return makeReadableStream({
|
|
16272
|
+
start() { },
|
|
16273
|
+
async pull(controller) {
|
|
16274
|
+
const { done, value } = await iter.next();
|
|
16275
|
+
if (done) {
|
|
16276
|
+
controller.close();
|
|
16277
|
+
}
|
|
16278
|
+
else {
|
|
16279
|
+
controller.enqueue(value);
|
|
16280
|
+
}
|
|
16281
|
+
},
|
|
16282
|
+
async cancel() {
|
|
16283
|
+
var _a;
|
|
16284
|
+
await ((_a = iter.return) === null || _a === void 0 ? void 0 : _a.call(iter));
|
|
16285
|
+
},
|
|
16286
|
+
});
|
|
15875
16287
|
}
|
|
15876
|
-
|
|
15877
|
-
|
|
15878
|
-
|
|
15879
|
-
|
|
15880
|
-
|
|
15881
|
-
|
|
15882
|
-
|
|
15883
|
-
|
|
16288
|
+
/**
|
|
16289
|
+
* Most browsers don't yet have async iterable support for ReadableStream,
|
|
16290
|
+
* and Node has a very different way of reading bytes from its "ReadableStream".
|
|
16291
|
+
*
|
|
16292
|
+
* This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
|
|
16293
|
+
*/
|
|
16294
|
+
function ReadableStreamToAsyncIterable(stream) {
|
|
16295
|
+
if (stream[Symbol.asyncIterator])
|
|
16296
|
+
return stream;
|
|
16297
|
+
const reader = stream.getReader();
|
|
16298
|
+
return {
|
|
16299
|
+
async next() {
|
|
16300
|
+
try {
|
|
16301
|
+
const result = await reader.read();
|
|
16302
|
+
if (result === null || result === void 0 ? void 0 : result.done)
|
|
16303
|
+
reader.releaseLock(); // release lock when stream becomes closed
|
|
16304
|
+
return result;
|
|
16305
|
+
}
|
|
16306
|
+
catch (e) {
|
|
16307
|
+
reader.releaseLock(); // release lock when stream becomes errored
|
|
16308
|
+
throw e;
|
|
16309
|
+
}
|
|
16310
|
+
},
|
|
16311
|
+
async return() {
|
|
16312
|
+
const cancelPromise = reader.cancel();
|
|
16313
|
+
reader.releaseLock();
|
|
16314
|
+
await cancelPromise;
|
|
16315
|
+
return { done: true, value: undefined };
|
|
16316
|
+
},
|
|
16317
|
+
[Symbol.asyncIterator]() {
|
|
16318
|
+
return this;
|
|
16319
|
+
},
|
|
16320
|
+
};
|
|
16321
|
+
}
|
|
16322
|
+
/**
|
|
16323
|
+
* Cancels a ReadableStream we don't need to consume.
|
|
16324
|
+
* See https://undici.nodejs.org/#/?id=garbage-collection
|
|
16325
|
+
*/
|
|
16326
|
+
async function CancelReadableStream(stream) {
|
|
16327
|
+
var _a, _b;
|
|
16328
|
+
if (stream === null || typeof stream !== 'object')
|
|
16329
|
+
return;
|
|
16330
|
+
if (stream[Symbol.asyncIterator]) {
|
|
16331
|
+
await ((_b = (_a = stream[Symbol.asyncIterator]()).return) === null || _b === void 0 ? void 0 : _b.call(_a));
|
|
16332
|
+
return;
|
|
15884
16333
|
}
|
|
15885
|
-
|
|
16334
|
+
const reader = stream.getReader();
|
|
16335
|
+
const cancelPromise = reader.cancel();
|
|
16336
|
+
reader.releaseLock();
|
|
16337
|
+
await cancelPromise;
|
|
16338
|
+
}
|
|
16339
|
+
|
|
16340
|
+
/**
|
|
16341
|
+
* @license
|
|
16342
|
+
* Copyright 2025 Google LLC
|
|
16343
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16344
|
+
*/
|
|
16345
|
+
const FallbackEncoder = ({ headers, body }) => {
|
|
16346
|
+
return {
|
|
16347
|
+
bodyHeaders: {
|
|
16348
|
+
'content-type': 'application/json',
|
|
16349
|
+
},
|
|
16350
|
+
body: JSON.stringify(body),
|
|
16351
|
+
};
|
|
16352
|
+
};
|
|
16353
|
+
|
|
16354
|
+
/**
|
|
16355
|
+
* @license
|
|
16356
|
+
* Copyright 2025 Google LLC
|
|
16357
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16358
|
+
*/
|
|
16359
|
+
const checkFileSupport = () => {
|
|
16360
|
+
var _a;
|
|
16361
|
+
if (typeof File === 'undefined') {
|
|
16362
|
+
const { process } = globalThis;
|
|
16363
|
+
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;
|
|
16364
|
+
throw new Error('`File` is not defined as a global, which is required for file uploads.' +
|
|
16365
|
+
(isOldNode ?
|
|
16366
|
+
" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`."
|
|
16367
|
+
: ''));
|
|
16368
|
+
}
|
|
16369
|
+
};
|
|
16370
|
+
/**
|
|
16371
|
+
* Construct a `File` instance. This is used to ensure a helpful error is thrown
|
|
16372
|
+
* for environments that don't define a global `File` yet.
|
|
16373
|
+
*/
|
|
16374
|
+
function makeFile(fileBits, fileName, options) {
|
|
16375
|
+
checkFileSupport();
|
|
16376
|
+
return new File(fileBits, fileName !== null && fileName !== void 0 ? fileName : 'unknown_file', options);
|
|
16377
|
+
}
|
|
16378
|
+
function getName(value) {
|
|
16379
|
+
return (((typeof value === 'object' &&
|
|
16380
|
+
value !== null &&
|
|
16381
|
+
(('name' in value && value.name && String(value.name)) ||
|
|
16382
|
+
('url' in value && value.url && String(value.url)) ||
|
|
16383
|
+
('filename' in value && value.filename && String(value.filename)) ||
|
|
16384
|
+
('path' in value && value.path && String(value.path)))) ||
|
|
16385
|
+
'')
|
|
16386
|
+
.split(/[\\/]/)
|
|
16387
|
+
.pop() || undefined);
|
|
16388
|
+
}
|
|
16389
|
+
const isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';
|
|
16390
|
+
|
|
16391
|
+
/**
|
|
16392
|
+
* @license
|
|
16393
|
+
* Copyright 2025 Google LLC
|
|
16394
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16395
|
+
*/
|
|
16396
|
+
/**
|
|
16397
|
+
* This check adds the arrayBuffer() method type because it is available and used at runtime
|
|
16398
|
+
*/
|
|
16399
|
+
const isBlobLike = (value) => value != null &&
|
|
16400
|
+
typeof value === 'object' &&
|
|
16401
|
+
typeof value.size === 'number' &&
|
|
16402
|
+
typeof value.type === 'string' &&
|
|
16403
|
+
typeof value.text === 'function' &&
|
|
16404
|
+
typeof value.slice === 'function' &&
|
|
16405
|
+
typeof value.arrayBuffer === 'function';
|
|
16406
|
+
/**
|
|
16407
|
+
* This check adds the arrayBuffer() method type because it is available and used at runtime
|
|
16408
|
+
*/
|
|
16409
|
+
const isFileLike = (value) => value != null &&
|
|
16410
|
+
typeof value === 'object' &&
|
|
16411
|
+
typeof value.name === 'string' &&
|
|
16412
|
+
typeof value.lastModified === 'number' &&
|
|
16413
|
+
isBlobLike(value);
|
|
16414
|
+
const isResponseLike = (value) => value != null &&
|
|
16415
|
+
typeof value === 'object' &&
|
|
16416
|
+
typeof value.url === 'string' &&
|
|
16417
|
+
typeof value.blob === 'function';
|
|
16418
|
+
/**
|
|
16419
|
+
* Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats
|
|
16420
|
+
* @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts
|
|
16421
|
+
* @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible
|
|
16422
|
+
* @param {Object=} options additional properties
|
|
16423
|
+
* @param {string=} options.type the MIME type of the content
|
|
16424
|
+
* @param {number=} options.lastModified the last modified timestamp
|
|
16425
|
+
* @returns a {@link File} with the given properties
|
|
16426
|
+
*/
|
|
16427
|
+
async function toFile(value, name, options) {
|
|
16428
|
+
checkFileSupport();
|
|
16429
|
+
// If it's a promise, resolve it.
|
|
16430
|
+
value = await value;
|
|
16431
|
+
// If we've been given a `File` we don't need to do anything
|
|
16432
|
+
if (isFileLike(value)) {
|
|
16433
|
+
if (value instanceof File) {
|
|
16434
|
+
return value;
|
|
16435
|
+
}
|
|
16436
|
+
return makeFile([await value.arrayBuffer()], value.name);
|
|
16437
|
+
}
|
|
16438
|
+
if (isResponseLike(value)) {
|
|
16439
|
+
const blob = await value.blob();
|
|
16440
|
+
name || (name = new URL(value.url).pathname.split(/[\\/]/).pop());
|
|
16441
|
+
return makeFile(await getBytes(blob), name, options);
|
|
16442
|
+
}
|
|
16443
|
+
const parts = await getBytes(value);
|
|
16444
|
+
name || (name = getName(value));
|
|
16445
|
+
if (!(options === null || options === void 0 ? void 0 : options.type)) {
|
|
16446
|
+
const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type);
|
|
16447
|
+
if (typeof type === 'string') {
|
|
16448
|
+
options = Object.assign(Object.assign({}, options), { type });
|
|
16449
|
+
}
|
|
16450
|
+
}
|
|
16451
|
+
return makeFile(parts, name, options);
|
|
16452
|
+
}
|
|
16453
|
+
async function getBytes(value) {
|
|
16454
|
+
var _a, e_1, _b, _c;
|
|
16455
|
+
var _d;
|
|
16456
|
+
let parts = [];
|
|
16457
|
+
if (typeof value === 'string' ||
|
|
16458
|
+
ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.
|
|
16459
|
+
value instanceof ArrayBuffer) {
|
|
16460
|
+
parts.push(value);
|
|
16461
|
+
}
|
|
16462
|
+
else if (isBlobLike(value)) {
|
|
16463
|
+
parts.push(value instanceof Blob ? value : await value.arrayBuffer());
|
|
16464
|
+
}
|
|
16465
|
+
else if (isAsyncIterable(value) // includes Readable, ReadableStream, etc.
|
|
16466
|
+
) {
|
|
16467
|
+
try {
|
|
16468
|
+
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) {
|
|
16469
|
+
_c = value_1_1.value;
|
|
16470
|
+
_e = false;
|
|
16471
|
+
const chunk = _c;
|
|
16472
|
+
parts.push(...(await getBytes(chunk))); // TODO, consider validating?
|
|
16473
|
+
}
|
|
16474
|
+
}
|
|
16475
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
16476
|
+
finally {
|
|
16477
|
+
try {
|
|
16478
|
+
if (!_e && !_a && (_b = value_1.return)) await _b.call(value_1);
|
|
16479
|
+
}
|
|
16480
|
+
finally { if (e_1) throw e_1.error; }
|
|
16481
|
+
}
|
|
16482
|
+
}
|
|
16483
|
+
else {
|
|
16484
|
+
const constructor = (_d = value === null || value === void 0 ? void 0 : value.constructor) === null || _d === void 0 ? void 0 : _d.name;
|
|
16485
|
+
throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${propsForError(value)}`);
|
|
16486
|
+
}
|
|
16487
|
+
return parts;
|
|
16488
|
+
}
|
|
16489
|
+
function propsForError(value) {
|
|
16490
|
+
if (typeof value !== 'object' || value === null)
|
|
16491
|
+
return '';
|
|
16492
|
+
const props = Object.getOwnPropertyNames(value);
|
|
16493
|
+
return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`;
|
|
16494
|
+
}
|
|
16495
|
+
|
|
16496
|
+
/**
|
|
16497
|
+
* @license
|
|
16498
|
+
* Copyright 2025 Google LLC
|
|
16499
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16500
|
+
*/
|
|
16501
|
+
class APIResource {
|
|
16502
|
+
constructor(client) {
|
|
16503
|
+
this._client = client;
|
|
16504
|
+
}
|
|
16505
|
+
}
|
|
16506
|
+
/**
|
|
16507
|
+
* The key path from the client. For example, a resource accessible as `client.resource.subresource` would
|
|
16508
|
+
* have a property `static override readonly _key = Object.freeze(['resource', 'subresource'] as const);`.
|
|
16509
|
+
*/
|
|
16510
|
+
APIResource._key = [];
|
|
16511
|
+
|
|
16512
|
+
/**
|
|
16513
|
+
* @license
|
|
16514
|
+
* Copyright 2025 Google LLC
|
|
16515
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16516
|
+
*/
|
|
16517
|
+
/**
|
|
16518
|
+
* Percent-encode everything that isn't safe to have in a path without encoding safe chars.
|
|
16519
|
+
*
|
|
16520
|
+
* Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3:
|
|
16521
|
+
* > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
|
|
16522
|
+
* > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
|
|
16523
|
+
* > pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
|
|
16524
|
+
*/
|
|
16525
|
+
function encodeURIPath(str) {
|
|
16526
|
+
return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
|
|
16527
|
+
}
|
|
16528
|
+
const EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null));
|
|
16529
|
+
const createPathTagFunction = (pathEncoder = encodeURIPath) => (function path(statics, ...params) {
|
|
16530
|
+
// If there are no params, no processing is needed.
|
|
16531
|
+
if (statics.length === 1)
|
|
16532
|
+
return statics[0];
|
|
16533
|
+
let postPath = false;
|
|
16534
|
+
const invalidSegments = [];
|
|
16535
|
+
const path = statics.reduce((previousValue, currentValue, index) => {
|
|
16536
|
+
var _a, _b, _c;
|
|
16537
|
+
if (/[?#]/.test(currentValue)) {
|
|
16538
|
+
postPath = true;
|
|
16539
|
+
}
|
|
16540
|
+
const value = params[index];
|
|
16541
|
+
let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value);
|
|
16542
|
+
if (index !== params.length &&
|
|
16543
|
+
(value == null ||
|
|
16544
|
+
(typeof value === 'object' &&
|
|
16545
|
+
// handle values from other realms
|
|
16546
|
+
value.toString ===
|
|
16547
|
+
((_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)))) {
|
|
16548
|
+
encoded = value + '';
|
|
16549
|
+
invalidSegments.push({
|
|
16550
|
+
start: previousValue.length + currentValue.length,
|
|
16551
|
+
length: encoded.length,
|
|
16552
|
+
error: `Value of type ${Object.prototype.toString
|
|
16553
|
+
.call(value)
|
|
16554
|
+
.slice(8, -1)} is not a valid path parameter`,
|
|
16555
|
+
});
|
|
16556
|
+
}
|
|
16557
|
+
return previousValue + currentValue + (index === params.length ? '' : encoded);
|
|
16558
|
+
}, '');
|
|
16559
|
+
const pathOnly = path.split(/[?#]/, 1)[0];
|
|
16560
|
+
const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;
|
|
16561
|
+
let match;
|
|
16562
|
+
// Find all invalid segments
|
|
16563
|
+
while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) {
|
|
16564
|
+
invalidSegments.push({
|
|
16565
|
+
start: match.index,
|
|
16566
|
+
length: match[0].length,
|
|
16567
|
+
error: `Value "${match[0]}" can\'t be safely passed as a path parameter`,
|
|
16568
|
+
});
|
|
16569
|
+
}
|
|
16570
|
+
invalidSegments.sort((a, b) => a.start - b.start);
|
|
16571
|
+
if (invalidSegments.length > 0) {
|
|
16572
|
+
let lastEnd = 0;
|
|
16573
|
+
const underline = invalidSegments.reduce((acc, segment) => {
|
|
16574
|
+
const spaces = ' '.repeat(segment.start - lastEnd);
|
|
16575
|
+
const arrows = '^'.repeat(segment.length);
|
|
16576
|
+
lastEnd = segment.start + segment.length;
|
|
16577
|
+
return acc + spaces + arrows;
|
|
16578
|
+
}, '');
|
|
16579
|
+
throw new GeminiNextGenAPIClientError(`Path parameters result in path with invalid segments:\n${invalidSegments
|
|
16580
|
+
.map((e) => e.error)
|
|
16581
|
+
.join('\n')}\n${path}\n${underline}`);
|
|
16582
|
+
}
|
|
16583
|
+
return path;
|
|
16584
|
+
});
|
|
16585
|
+
/**
|
|
16586
|
+
* URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced.
|
|
16587
|
+
*/
|
|
16588
|
+
const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath);
|
|
16589
|
+
|
|
16590
|
+
/**
|
|
16591
|
+
* @license
|
|
16592
|
+
* Copyright 2025 Google LLC
|
|
16593
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16594
|
+
*/
|
|
16595
|
+
class BaseInteractions extends APIResource {
|
|
16596
|
+
create(params, options) {
|
|
16597
|
+
var _a;
|
|
16598
|
+
const { api_version = this._client.apiVersion } = params, body = __rest(params, ["api_version"]);
|
|
16599
|
+
if ('model' in body && 'agent_config' in body) {
|
|
16600
|
+
throw new GeminiNextGenAPIClientError(`Invalid request: specified \`model\` and \`agent_config\`. If specifying \`model\`, use \`generation_config\`.`);
|
|
16601
|
+
}
|
|
16602
|
+
if ('agent' in body && 'generation_config' in body) {
|
|
16603
|
+
throw new GeminiNextGenAPIClientError(`Invalid request: specified \`agent\` and \`generation_config\`. If specifying \`agent\`, use \`agent_config\`.`);
|
|
16604
|
+
}
|
|
16605
|
+
return this._client.post(path `/${api_version}/interactions`, Object.assign(Object.assign({ body }, options), { stream: (_a = params.stream) !== null && _a !== void 0 ? _a : false }));
|
|
16606
|
+
}
|
|
16607
|
+
/**
|
|
16608
|
+
* Deletes the interaction by id.
|
|
16609
|
+
*
|
|
16610
|
+
* @example
|
|
16611
|
+
* ```ts
|
|
16612
|
+
* const interaction = await client.interactions.delete('id');
|
|
16613
|
+
* ```
|
|
16614
|
+
*/
|
|
16615
|
+
delete(id, params = {}, options) {
|
|
16616
|
+
const { api_version = this._client.apiVersion } = params !== null && params !== void 0 ? params : {};
|
|
16617
|
+
return this._client.delete(path `/${api_version}/interactions/${id}`, options);
|
|
16618
|
+
}
|
|
16619
|
+
/**
|
|
16620
|
+
* Cancels an interaction by id. This only applies to background interactions that are still running.
|
|
16621
|
+
*
|
|
16622
|
+
* @example
|
|
16623
|
+
* ```ts
|
|
16624
|
+
* const interaction = await client.interactions.cancel('id');
|
|
16625
|
+
* ```
|
|
16626
|
+
*/
|
|
16627
|
+
cancel(id, params = {}, options) {
|
|
16628
|
+
const { api_version = this._client.apiVersion } = params !== null && params !== void 0 ? params : {};
|
|
16629
|
+
return this._client.post(path `/${api_version}/interactions/${id}/cancel`, options);
|
|
16630
|
+
}
|
|
16631
|
+
get(id, params = {}, options) {
|
|
16632
|
+
var _a;
|
|
16633
|
+
const _b = params !== null && params !== void 0 ? params : {}, { api_version = this._client.apiVersion } = _b, query = __rest(_b, ["api_version"]);
|
|
16634
|
+
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 }));
|
|
16635
|
+
}
|
|
16636
|
+
}
|
|
16637
|
+
BaseInteractions._key = Object.freeze(['interactions']);
|
|
16638
|
+
class Interactions extends BaseInteractions {
|
|
16639
|
+
}
|
|
16640
|
+
|
|
16641
|
+
/**
|
|
16642
|
+
* @license
|
|
16643
|
+
* Copyright 2025 Google LLC
|
|
16644
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16645
|
+
*/
|
|
16646
|
+
function concatBytes(buffers) {
|
|
16647
|
+
let length = 0;
|
|
16648
|
+
for (const buffer of buffers) {
|
|
16649
|
+
length += buffer.length;
|
|
16650
|
+
}
|
|
16651
|
+
const output = new Uint8Array(length);
|
|
16652
|
+
let index = 0;
|
|
16653
|
+
for (const buffer of buffers) {
|
|
16654
|
+
output.set(buffer, index);
|
|
16655
|
+
index += buffer.length;
|
|
16656
|
+
}
|
|
16657
|
+
return output;
|
|
16658
|
+
}
|
|
16659
|
+
let encodeUTF8_;
|
|
16660
|
+
function encodeUTF8(str) {
|
|
16661
|
+
let encoder;
|
|
16662
|
+
return (encodeUTF8_ !== null && encodeUTF8_ !== void 0 ? encodeUTF8_ : ((encoder = new globalThis.TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))))(str);
|
|
16663
|
+
}
|
|
16664
|
+
let decodeUTF8_;
|
|
16665
|
+
function decodeUTF8(bytes) {
|
|
16666
|
+
let decoder;
|
|
16667
|
+
return (decodeUTF8_ !== null && decodeUTF8_ !== void 0 ? decodeUTF8_ : ((decoder = new globalThis.TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))))(bytes);
|
|
16668
|
+
}
|
|
16669
|
+
|
|
16670
|
+
/**
|
|
16671
|
+
* @license
|
|
16672
|
+
* Copyright 2025 Google LLC
|
|
16673
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16674
|
+
*/
|
|
16675
|
+
/**
|
|
16676
|
+
* A re-implementation of httpx's `LineDecoder` in Python that handles incrementally
|
|
16677
|
+
* reading lines from text.
|
|
16678
|
+
*
|
|
16679
|
+
* https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258
|
|
16680
|
+
*/
|
|
16681
|
+
class LineDecoder {
|
|
16682
|
+
constructor() {
|
|
16683
|
+
this.buffer = new Uint8Array();
|
|
16684
|
+
this.carriageReturnIndex = null;
|
|
16685
|
+
}
|
|
16686
|
+
decode(chunk) {
|
|
16687
|
+
if (chunk == null) {
|
|
16688
|
+
return [];
|
|
16689
|
+
}
|
|
16690
|
+
const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
|
|
16691
|
+
: typeof chunk === 'string' ? encodeUTF8(chunk)
|
|
16692
|
+
: chunk;
|
|
16693
|
+
this.buffer = concatBytes([this.buffer, binaryChunk]);
|
|
16694
|
+
const lines = [];
|
|
16695
|
+
let patternIndex;
|
|
16696
|
+
while ((patternIndex = findNewlineIndex(this.buffer, this.carriageReturnIndex)) != null) {
|
|
16697
|
+
if (patternIndex.carriage && this.carriageReturnIndex == null) {
|
|
16698
|
+
// skip until we either get a corresponding `\n`, a new `\r` or nothing
|
|
16699
|
+
this.carriageReturnIndex = patternIndex.index;
|
|
16700
|
+
continue;
|
|
16701
|
+
}
|
|
16702
|
+
// we got double \r or \rtext\n
|
|
16703
|
+
if (this.carriageReturnIndex != null &&
|
|
16704
|
+
(patternIndex.index !== this.carriageReturnIndex + 1 || patternIndex.carriage)) {
|
|
16705
|
+
lines.push(decodeUTF8(this.buffer.subarray(0, this.carriageReturnIndex - 1)));
|
|
16706
|
+
this.buffer = this.buffer.subarray(this.carriageReturnIndex);
|
|
16707
|
+
this.carriageReturnIndex = null;
|
|
16708
|
+
continue;
|
|
16709
|
+
}
|
|
16710
|
+
const endIndex = this.carriageReturnIndex !== null ? patternIndex.preceding - 1 : patternIndex.preceding;
|
|
16711
|
+
const line = decodeUTF8(this.buffer.subarray(0, endIndex));
|
|
16712
|
+
lines.push(line);
|
|
16713
|
+
this.buffer = this.buffer.subarray(patternIndex.index);
|
|
16714
|
+
this.carriageReturnIndex = null;
|
|
16715
|
+
}
|
|
16716
|
+
return lines;
|
|
16717
|
+
}
|
|
16718
|
+
flush() {
|
|
16719
|
+
if (!this.buffer.length) {
|
|
16720
|
+
return [];
|
|
16721
|
+
}
|
|
16722
|
+
return this.decode('\n');
|
|
16723
|
+
}
|
|
16724
|
+
}
|
|
16725
|
+
// prettier-ignore
|
|
16726
|
+
LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']);
|
|
16727
|
+
LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
|
|
16728
|
+
/**
|
|
16729
|
+
* This function searches the buffer for the end patterns, (\r or \n)
|
|
16730
|
+
* and returns an object with the index preceding the matched newline and the
|
|
16731
|
+
* index after the newline char. `null` is returned if no new line is found.
|
|
16732
|
+
*
|
|
16733
|
+
* ```ts
|
|
16734
|
+
* findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 }
|
|
16735
|
+
* ```
|
|
16736
|
+
*/
|
|
16737
|
+
function findNewlineIndex(buffer, startIndex) {
|
|
16738
|
+
const newline = 0x0a; // \n
|
|
16739
|
+
const carriage = 0x0d; // \r
|
|
16740
|
+
for (let i = startIndex !== null && startIndex !== void 0 ? startIndex : 0; i < buffer.length; i++) {
|
|
16741
|
+
if (buffer[i] === newline) {
|
|
16742
|
+
return { preceding: i, index: i + 1, carriage: false };
|
|
16743
|
+
}
|
|
16744
|
+
if (buffer[i] === carriage) {
|
|
16745
|
+
return { preceding: i, index: i + 1, carriage: true };
|
|
16746
|
+
}
|
|
16747
|
+
}
|
|
16748
|
+
return null;
|
|
16749
|
+
}
|
|
16750
|
+
function findDoubleNewlineIndex(buffer) {
|
|
16751
|
+
// This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n)
|
|
16752
|
+
// and returns the index right after the first occurrence of any pattern,
|
|
16753
|
+
// or -1 if none of the patterns are found.
|
|
16754
|
+
const newline = 0x0a; // \n
|
|
16755
|
+
const carriage = 0x0d; // \r
|
|
16756
|
+
for (let i = 0; i < buffer.length - 1; i++) {
|
|
16757
|
+
if (buffer[i] === newline && buffer[i + 1] === newline) {
|
|
16758
|
+
// \n\n
|
|
16759
|
+
return i + 2;
|
|
16760
|
+
}
|
|
16761
|
+
if (buffer[i] === carriage && buffer[i + 1] === carriage) {
|
|
16762
|
+
// \r\r
|
|
16763
|
+
return i + 2;
|
|
16764
|
+
}
|
|
16765
|
+
if (buffer[i] === carriage &&
|
|
16766
|
+
buffer[i + 1] === newline &&
|
|
16767
|
+
i + 3 < buffer.length &&
|
|
16768
|
+
buffer[i + 2] === carriage &&
|
|
16769
|
+
buffer[i + 3] === newline) {
|
|
16770
|
+
// \r\n\r\n
|
|
16771
|
+
return i + 4;
|
|
16772
|
+
}
|
|
16773
|
+
}
|
|
16774
|
+
return -1;
|
|
16775
|
+
}
|
|
16776
|
+
|
|
16777
|
+
/**
|
|
16778
|
+
* @license
|
|
16779
|
+
* Copyright 2025 Google LLC
|
|
16780
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16781
|
+
*/
|
|
16782
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
16783
|
+
const levelNumbers = {
|
|
16784
|
+
off: 0,
|
|
16785
|
+
error: 200,
|
|
16786
|
+
warn: 300,
|
|
16787
|
+
info: 400,
|
|
16788
|
+
debug: 500,
|
|
16789
|
+
};
|
|
16790
|
+
const parseLogLevel = (maybeLevel, sourceName, client) => {
|
|
16791
|
+
if (!maybeLevel) {
|
|
16792
|
+
return undefined;
|
|
16793
|
+
}
|
|
16794
|
+
if (hasOwn(levelNumbers, maybeLevel)) {
|
|
16795
|
+
return maybeLevel;
|
|
16796
|
+
}
|
|
16797
|
+
loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);
|
|
16798
|
+
return undefined;
|
|
16799
|
+
};
|
|
16800
|
+
function noop() { }
|
|
16801
|
+
function makeLogFn(fnLevel, logger, logLevel) {
|
|
16802
|
+
if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) {
|
|
16803
|
+
return noop;
|
|
16804
|
+
}
|
|
16805
|
+
else {
|
|
16806
|
+
// Don't wrap logger functions, we want the stacktrace intact!
|
|
16807
|
+
return logger[fnLevel].bind(logger);
|
|
16808
|
+
}
|
|
16809
|
+
}
|
|
16810
|
+
const noopLogger = {
|
|
16811
|
+
error: noop,
|
|
16812
|
+
warn: noop,
|
|
16813
|
+
info: noop,
|
|
16814
|
+
debug: noop,
|
|
16815
|
+
};
|
|
16816
|
+
let cachedLoggers = /* @__PURE__ */ new WeakMap();
|
|
16817
|
+
function loggerFor(client) {
|
|
16818
|
+
var _a;
|
|
16819
|
+
const logger = client.logger;
|
|
16820
|
+
const logLevel = (_a = client.logLevel) !== null && _a !== void 0 ? _a : 'off';
|
|
16821
|
+
if (!logger) {
|
|
16822
|
+
return noopLogger;
|
|
16823
|
+
}
|
|
16824
|
+
const cachedLogger = cachedLoggers.get(logger);
|
|
16825
|
+
if (cachedLogger && cachedLogger[0] === logLevel) {
|
|
16826
|
+
return cachedLogger[1];
|
|
16827
|
+
}
|
|
16828
|
+
const levelLogger = {
|
|
16829
|
+
error: makeLogFn('error', logger, logLevel),
|
|
16830
|
+
warn: makeLogFn('warn', logger, logLevel),
|
|
16831
|
+
info: makeLogFn('info', logger, logLevel),
|
|
16832
|
+
debug: makeLogFn('debug', logger, logLevel),
|
|
16833
|
+
};
|
|
16834
|
+
cachedLoggers.set(logger, [logLevel, levelLogger]);
|
|
16835
|
+
return levelLogger;
|
|
16836
|
+
}
|
|
16837
|
+
const formatRequestDetails = (details) => {
|
|
16838
|
+
if (details.options) {
|
|
16839
|
+
details.options = Object.assign({}, details.options);
|
|
16840
|
+
delete details.options['headers']; // redundant + leaks internals
|
|
16841
|
+
}
|
|
16842
|
+
if (details.headers) {
|
|
16843
|
+
details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [
|
|
16844
|
+
name,
|
|
16845
|
+
(name.toLowerCase() === 'x-goog-api-key' ||
|
|
16846
|
+
name.toLowerCase() === 'authorization' ||
|
|
16847
|
+
name.toLowerCase() === 'cookie' ||
|
|
16848
|
+
name.toLowerCase() === 'set-cookie') ?
|
|
16849
|
+
'***'
|
|
16850
|
+
: value,
|
|
16851
|
+
]));
|
|
16852
|
+
}
|
|
16853
|
+
if ('retryOfRequestLogID' in details) {
|
|
16854
|
+
if (details.retryOfRequestLogID) {
|
|
16855
|
+
details.retryOf = details.retryOfRequestLogID;
|
|
16856
|
+
}
|
|
16857
|
+
delete details.retryOfRequestLogID;
|
|
16858
|
+
}
|
|
16859
|
+
return details;
|
|
16860
|
+
};
|
|
16861
|
+
|
|
16862
|
+
/**
|
|
16863
|
+
* @license
|
|
16864
|
+
* Copyright 2025 Google LLC
|
|
16865
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
16866
|
+
*/
|
|
16867
|
+
class Stream {
|
|
16868
|
+
constructor(iterator, controller, client) {
|
|
16869
|
+
this.iterator = iterator;
|
|
16870
|
+
this.controller = controller;
|
|
16871
|
+
this.client = client;
|
|
16872
|
+
}
|
|
16873
|
+
static fromSSEResponse(response, controller, client) {
|
|
16874
|
+
let consumed = false;
|
|
16875
|
+
const logger = client ? loggerFor(client) : console;
|
|
16876
|
+
function iterator() {
|
|
16877
|
+
return __asyncGenerator(this, arguments, function* iterator_1() {
|
|
16878
|
+
var _a, e_1, _b, _c;
|
|
16879
|
+
if (consumed) {
|
|
16880
|
+
throw new GeminiNextGenAPIClientError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
|
|
16881
|
+
}
|
|
16882
|
+
consumed = true;
|
|
16883
|
+
let done = false;
|
|
16884
|
+
try {
|
|
16885
|
+
try {
|
|
16886
|
+
for (var _d = true, _e = __asyncValues(_iterSSEMessages(response, controller)), _f; _f = yield __await(_e.next()), _a = _f.done, !_a; _d = true) {
|
|
16887
|
+
_c = _f.value;
|
|
16888
|
+
_d = false;
|
|
16889
|
+
const sse = _c;
|
|
16890
|
+
if (done)
|
|
16891
|
+
continue;
|
|
16892
|
+
if (sse.data.startsWith('[DONE]')) {
|
|
16893
|
+
done = true;
|
|
16894
|
+
continue;
|
|
16895
|
+
}
|
|
16896
|
+
else {
|
|
16897
|
+
try {
|
|
16898
|
+
// @ts-ignore
|
|
16899
|
+
yield yield __await(JSON.parse(sse.data));
|
|
16900
|
+
}
|
|
16901
|
+
catch (e) {
|
|
16902
|
+
logger.error(`Could not parse message into JSON:`, sse.data);
|
|
16903
|
+
logger.error(`From chunk:`, sse.raw);
|
|
16904
|
+
throw e;
|
|
16905
|
+
}
|
|
16906
|
+
}
|
|
16907
|
+
}
|
|
16908
|
+
}
|
|
16909
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
16910
|
+
finally {
|
|
16911
|
+
try {
|
|
16912
|
+
if (!_d && !_a && (_b = _e.return)) yield __await(_b.call(_e));
|
|
16913
|
+
}
|
|
16914
|
+
finally { if (e_1) throw e_1.error; }
|
|
16915
|
+
}
|
|
16916
|
+
done = true;
|
|
16917
|
+
}
|
|
16918
|
+
catch (e) {
|
|
16919
|
+
// If the user calls `stream.controller.abort()`, we should exit without throwing.
|
|
16920
|
+
if (isAbortError(e))
|
|
16921
|
+
return yield __await(void 0);
|
|
16922
|
+
throw e;
|
|
16923
|
+
}
|
|
16924
|
+
finally {
|
|
16925
|
+
// If the user `break`s, abort the ongoing request.
|
|
16926
|
+
if (!done)
|
|
16927
|
+
controller.abort();
|
|
16928
|
+
}
|
|
16929
|
+
});
|
|
16930
|
+
}
|
|
16931
|
+
return new Stream(iterator, controller, client);
|
|
16932
|
+
}
|
|
16933
|
+
/**
|
|
16934
|
+
* Generates a Stream from a newline-separated ReadableStream
|
|
16935
|
+
* where each item is a JSON value.
|
|
16936
|
+
*/
|
|
16937
|
+
static fromReadableStream(readableStream, controller, client) {
|
|
16938
|
+
let consumed = false;
|
|
16939
|
+
function iterLines() {
|
|
16940
|
+
return __asyncGenerator(this, arguments, function* iterLines_1() {
|
|
16941
|
+
var _a, e_2, _b, _c;
|
|
16942
|
+
const lineDecoder = new LineDecoder();
|
|
16943
|
+
const iter = ReadableStreamToAsyncIterable(readableStream);
|
|
16944
|
+
try {
|
|
16945
|
+
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) {
|
|
16946
|
+
_c = iter_1_1.value;
|
|
16947
|
+
_d = false;
|
|
16948
|
+
const chunk = _c;
|
|
16949
|
+
for (const line of lineDecoder.decode(chunk)) {
|
|
16950
|
+
yield yield __await(line);
|
|
16951
|
+
}
|
|
16952
|
+
}
|
|
16953
|
+
}
|
|
16954
|
+
catch (e_2_1) { e_2 = { error: e_2_1 }; }
|
|
16955
|
+
finally {
|
|
16956
|
+
try {
|
|
16957
|
+
if (!_d && !_a && (_b = iter_1.return)) yield __await(_b.call(iter_1));
|
|
16958
|
+
}
|
|
16959
|
+
finally { if (e_2) throw e_2.error; }
|
|
16960
|
+
}
|
|
16961
|
+
for (const line of lineDecoder.flush()) {
|
|
16962
|
+
yield yield __await(line);
|
|
16963
|
+
}
|
|
16964
|
+
});
|
|
16965
|
+
}
|
|
16966
|
+
function iterator() {
|
|
16967
|
+
return __asyncGenerator(this, arguments, function* iterator_2() {
|
|
16968
|
+
var _a, e_3, _b, _c;
|
|
16969
|
+
if (consumed) {
|
|
16970
|
+
throw new GeminiNextGenAPIClientError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
|
|
16971
|
+
}
|
|
16972
|
+
consumed = true;
|
|
16973
|
+
let done = false;
|
|
16974
|
+
try {
|
|
16975
|
+
try {
|
|
16976
|
+
for (var _d = true, _e = __asyncValues(iterLines()), _f; _f = yield __await(_e.next()), _a = _f.done, !_a; _d = true) {
|
|
16977
|
+
_c = _f.value;
|
|
16978
|
+
_d = false;
|
|
16979
|
+
const line = _c;
|
|
16980
|
+
if (done)
|
|
16981
|
+
continue;
|
|
16982
|
+
// @ts-ignore
|
|
16983
|
+
if (line)
|
|
16984
|
+
yield yield __await(JSON.parse(line));
|
|
16985
|
+
}
|
|
16986
|
+
}
|
|
16987
|
+
catch (e_3_1) { e_3 = { error: e_3_1 }; }
|
|
16988
|
+
finally {
|
|
16989
|
+
try {
|
|
16990
|
+
if (!_d && !_a && (_b = _e.return)) yield __await(_b.call(_e));
|
|
16991
|
+
}
|
|
16992
|
+
finally { if (e_3) throw e_3.error; }
|
|
16993
|
+
}
|
|
16994
|
+
done = true;
|
|
16995
|
+
}
|
|
16996
|
+
catch (e) {
|
|
16997
|
+
// If the user calls `stream.controller.abort()`, we should exit without throwing.
|
|
16998
|
+
if (isAbortError(e))
|
|
16999
|
+
return yield __await(void 0);
|
|
17000
|
+
throw e;
|
|
17001
|
+
}
|
|
17002
|
+
finally {
|
|
17003
|
+
// If the user `break`s, abort the ongoing request.
|
|
17004
|
+
if (!done)
|
|
17005
|
+
controller.abort();
|
|
17006
|
+
}
|
|
17007
|
+
});
|
|
17008
|
+
}
|
|
17009
|
+
return new Stream(iterator, controller, client);
|
|
17010
|
+
}
|
|
17011
|
+
[Symbol.asyncIterator]() {
|
|
17012
|
+
return this.iterator();
|
|
17013
|
+
}
|
|
17014
|
+
/**
|
|
17015
|
+
* Splits the stream into two streams which can be
|
|
17016
|
+
* independently read from at different speeds.
|
|
17017
|
+
*/
|
|
17018
|
+
tee() {
|
|
17019
|
+
const left = [];
|
|
17020
|
+
const right = [];
|
|
17021
|
+
const iterator = this.iterator();
|
|
17022
|
+
const teeIterator = (queue) => {
|
|
17023
|
+
return {
|
|
17024
|
+
next: () => {
|
|
17025
|
+
if (queue.length === 0) {
|
|
17026
|
+
const result = iterator.next();
|
|
17027
|
+
left.push(result);
|
|
17028
|
+
right.push(result);
|
|
17029
|
+
}
|
|
17030
|
+
return queue.shift();
|
|
17031
|
+
},
|
|
17032
|
+
};
|
|
17033
|
+
};
|
|
17034
|
+
return [
|
|
17035
|
+
new Stream(() => teeIterator(left), this.controller, this.client),
|
|
17036
|
+
new Stream(() => teeIterator(right), this.controller, this.client),
|
|
17037
|
+
];
|
|
17038
|
+
}
|
|
17039
|
+
/**
|
|
17040
|
+
* Converts this stream to a newline-separated ReadableStream of
|
|
17041
|
+
* JSON stringified values in the stream
|
|
17042
|
+
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
|
|
17043
|
+
*/
|
|
17044
|
+
toReadableStream() {
|
|
17045
|
+
const self = this;
|
|
17046
|
+
let iter;
|
|
17047
|
+
return makeReadableStream({
|
|
17048
|
+
async start() {
|
|
17049
|
+
iter = self[Symbol.asyncIterator]();
|
|
17050
|
+
},
|
|
17051
|
+
async pull(ctrl) {
|
|
17052
|
+
try {
|
|
17053
|
+
const { value, done } = await iter.next();
|
|
17054
|
+
if (done)
|
|
17055
|
+
return ctrl.close();
|
|
17056
|
+
const bytes = encodeUTF8(JSON.stringify(value) + '\n');
|
|
17057
|
+
ctrl.enqueue(bytes);
|
|
17058
|
+
}
|
|
17059
|
+
catch (err) {
|
|
17060
|
+
ctrl.error(err);
|
|
17061
|
+
}
|
|
17062
|
+
},
|
|
17063
|
+
async cancel() {
|
|
17064
|
+
var _a;
|
|
17065
|
+
await ((_a = iter.return) === null || _a === void 0 ? void 0 : _a.call(iter));
|
|
17066
|
+
},
|
|
17067
|
+
});
|
|
17068
|
+
}
|
|
17069
|
+
}
|
|
17070
|
+
function _iterSSEMessages(response, controller) {
|
|
17071
|
+
return __asyncGenerator(this, arguments, function* _iterSSEMessages_1() {
|
|
17072
|
+
var _a, e_4, _b, _c;
|
|
17073
|
+
if (!response.body) {
|
|
17074
|
+
controller.abort();
|
|
17075
|
+
if (typeof globalThis.navigator !== 'undefined' &&
|
|
17076
|
+
globalThis.navigator.product === 'ReactNative') {
|
|
17077
|
+
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`);
|
|
17078
|
+
}
|
|
17079
|
+
throw new GeminiNextGenAPIClientError(`Attempted to iterate over a response with no body`);
|
|
17080
|
+
}
|
|
17081
|
+
const sseDecoder = new SSEDecoder();
|
|
17082
|
+
const lineDecoder = new LineDecoder();
|
|
17083
|
+
const iter = ReadableStreamToAsyncIterable(response.body);
|
|
17084
|
+
try {
|
|
17085
|
+
for (var _d = true, _e = __asyncValues(iterSSEChunks(iter)), _f; _f = yield __await(_e.next()), _a = _f.done, !_a; _d = true) {
|
|
17086
|
+
_c = _f.value;
|
|
17087
|
+
_d = false;
|
|
17088
|
+
const sseChunk = _c;
|
|
17089
|
+
for (const line of lineDecoder.decode(sseChunk)) {
|
|
17090
|
+
const sse = sseDecoder.decode(line);
|
|
17091
|
+
if (sse)
|
|
17092
|
+
yield yield __await(sse);
|
|
17093
|
+
}
|
|
17094
|
+
}
|
|
17095
|
+
}
|
|
17096
|
+
catch (e_4_1) { e_4 = { error: e_4_1 }; }
|
|
17097
|
+
finally {
|
|
17098
|
+
try {
|
|
17099
|
+
if (!_d && !_a && (_b = _e.return)) yield __await(_b.call(_e));
|
|
17100
|
+
}
|
|
17101
|
+
finally { if (e_4) throw e_4.error; }
|
|
17102
|
+
}
|
|
17103
|
+
for (const line of lineDecoder.flush()) {
|
|
17104
|
+
const sse = sseDecoder.decode(line);
|
|
17105
|
+
if (sse)
|
|
17106
|
+
yield yield __await(sse);
|
|
17107
|
+
}
|
|
17108
|
+
});
|
|
17109
|
+
}
|
|
17110
|
+
/**
|
|
17111
|
+
* Given an async iterable iterator, iterates over it and yields full
|
|
17112
|
+
* SSE chunks, i.e. yields when a double new-line is encountered.
|
|
17113
|
+
*/
|
|
17114
|
+
function iterSSEChunks(iterator) {
|
|
17115
|
+
return __asyncGenerator(this, arguments, function* iterSSEChunks_1() {
|
|
17116
|
+
var _a, e_5, _b, _c;
|
|
17117
|
+
let data = new Uint8Array();
|
|
17118
|
+
try {
|
|
17119
|
+
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) {
|
|
17120
|
+
_c = iterator_3_1.value;
|
|
17121
|
+
_d = false;
|
|
17122
|
+
const chunk = _c;
|
|
17123
|
+
if (chunk == null) {
|
|
17124
|
+
continue;
|
|
17125
|
+
}
|
|
17126
|
+
const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
|
|
17127
|
+
: typeof chunk === 'string' ? encodeUTF8(chunk)
|
|
17128
|
+
: chunk;
|
|
17129
|
+
let newData = new Uint8Array(data.length + binaryChunk.length);
|
|
17130
|
+
newData.set(data);
|
|
17131
|
+
newData.set(binaryChunk, data.length);
|
|
17132
|
+
data = newData;
|
|
17133
|
+
let patternIndex;
|
|
17134
|
+
while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
|
|
17135
|
+
yield yield __await(data.slice(0, patternIndex));
|
|
17136
|
+
data = data.slice(patternIndex);
|
|
17137
|
+
}
|
|
17138
|
+
}
|
|
17139
|
+
}
|
|
17140
|
+
catch (e_5_1) { e_5 = { error: e_5_1 }; }
|
|
17141
|
+
finally {
|
|
17142
|
+
try {
|
|
17143
|
+
if (!_d && !_a && (_b = iterator_3.return)) yield __await(_b.call(iterator_3));
|
|
17144
|
+
}
|
|
17145
|
+
finally { if (e_5) throw e_5.error; }
|
|
17146
|
+
}
|
|
17147
|
+
if (data.length > 0) {
|
|
17148
|
+
yield yield __await(data);
|
|
17149
|
+
}
|
|
17150
|
+
});
|
|
17151
|
+
}
|
|
17152
|
+
class SSEDecoder {
|
|
17153
|
+
constructor() {
|
|
17154
|
+
this.event = null;
|
|
17155
|
+
this.data = [];
|
|
17156
|
+
this.chunks = [];
|
|
17157
|
+
}
|
|
17158
|
+
decode(line) {
|
|
17159
|
+
if (line.endsWith('\r')) {
|
|
17160
|
+
line = line.substring(0, line.length - 1);
|
|
17161
|
+
}
|
|
17162
|
+
if (!line) {
|
|
17163
|
+
// empty line and we didn't previously encounter any messages
|
|
17164
|
+
if (!this.event && !this.data.length)
|
|
17165
|
+
return null;
|
|
17166
|
+
const sse = {
|
|
17167
|
+
event: this.event,
|
|
17168
|
+
data: this.data.join('\n'),
|
|
17169
|
+
raw: this.chunks,
|
|
17170
|
+
};
|
|
17171
|
+
this.event = null;
|
|
17172
|
+
this.data = [];
|
|
17173
|
+
this.chunks = [];
|
|
17174
|
+
return sse;
|
|
17175
|
+
}
|
|
17176
|
+
this.chunks.push(line);
|
|
17177
|
+
if (line.startsWith(':')) {
|
|
17178
|
+
return null;
|
|
17179
|
+
}
|
|
17180
|
+
let [fieldname, _, value] = partition(line, ':');
|
|
17181
|
+
if (value.startsWith(' ')) {
|
|
17182
|
+
value = value.substring(1);
|
|
17183
|
+
}
|
|
17184
|
+
if (fieldname === 'event') {
|
|
17185
|
+
this.event = value;
|
|
17186
|
+
}
|
|
17187
|
+
else if (fieldname === 'data') {
|
|
17188
|
+
this.data.push(value);
|
|
17189
|
+
}
|
|
17190
|
+
return null;
|
|
17191
|
+
}
|
|
17192
|
+
}
|
|
17193
|
+
function partition(str, delimiter) {
|
|
17194
|
+
const index = str.indexOf(delimiter);
|
|
17195
|
+
if (index !== -1) {
|
|
17196
|
+
return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
|
|
17197
|
+
}
|
|
17198
|
+
return [str, '', ''];
|
|
17199
|
+
}
|
|
17200
|
+
|
|
17201
|
+
/**
|
|
17202
|
+
* @license
|
|
17203
|
+
* Copyright 2025 Google LLC
|
|
17204
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
17205
|
+
*/
|
|
17206
|
+
async function defaultParseResponse(client, props) {
|
|
17207
|
+
const { response, requestLogID, retryOfRequestLogID, startTime } = props;
|
|
17208
|
+
const body = await (async () => {
|
|
17209
|
+
var _a;
|
|
17210
|
+
if (props.options.stream) {
|
|
17211
|
+
loggerFor(client).debug('response', response.status, response.url, response.headers, response.body);
|
|
17212
|
+
// Note: there is an invariant here that isn't represented in the type system
|
|
17213
|
+
// that if you set `stream: true` the response type must also be `Stream<T>`
|
|
17214
|
+
if (props.options.__streamClass) {
|
|
17215
|
+
return props.options.__streamClass.fromSSEResponse(response, props.controller, client);
|
|
17216
|
+
}
|
|
17217
|
+
return Stream.fromSSEResponse(response, props.controller, client);
|
|
17218
|
+
}
|
|
17219
|
+
// fetch refuses to read the body when the status code is 204.
|
|
17220
|
+
if (response.status === 204) {
|
|
17221
|
+
return null;
|
|
17222
|
+
}
|
|
17223
|
+
if (props.options.__binaryResponse) {
|
|
17224
|
+
return response;
|
|
17225
|
+
}
|
|
17226
|
+
const contentType = response.headers.get('content-type');
|
|
17227
|
+
const mediaType = (_a = contentType === null || contentType === void 0 ? void 0 : contentType.split(';')[0]) === null || _a === void 0 ? void 0 : _a.trim();
|
|
17228
|
+
const isJSON = (mediaType === null || mediaType === void 0 ? void 0 : mediaType.includes('application/json')) || (mediaType === null || mediaType === void 0 ? void 0 : mediaType.endsWith('+json'));
|
|
17229
|
+
if (isJSON) {
|
|
17230
|
+
const json = await response.json();
|
|
17231
|
+
return json;
|
|
17232
|
+
}
|
|
17233
|
+
const text = await response.text();
|
|
17234
|
+
return text;
|
|
17235
|
+
})();
|
|
17236
|
+
loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({
|
|
17237
|
+
retryOfRequestLogID,
|
|
17238
|
+
url: response.url,
|
|
17239
|
+
status: response.status,
|
|
17240
|
+
body,
|
|
17241
|
+
durationMs: Date.now() - startTime,
|
|
17242
|
+
}));
|
|
17243
|
+
return body;
|
|
17244
|
+
}
|
|
17245
|
+
|
|
17246
|
+
/**
|
|
17247
|
+
* @license
|
|
17248
|
+
* Copyright 2025 Google LLC
|
|
17249
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
17250
|
+
*/
|
|
17251
|
+
/**
|
|
17252
|
+
* A subclass of `Promise` providing additional helper methods
|
|
17253
|
+
* for interacting with the SDK.
|
|
17254
|
+
*/
|
|
17255
|
+
class APIPromise extends Promise {
|
|
17256
|
+
constructor(client, responsePromise, parseResponse = defaultParseResponse) {
|
|
17257
|
+
super((resolve) => {
|
|
17258
|
+
// this is maybe a bit weird but this has to be a no-op to not implicitly
|
|
17259
|
+
// parse the response body; instead .then, .catch, .finally are overridden
|
|
17260
|
+
// to parse the response
|
|
17261
|
+
resolve(null);
|
|
17262
|
+
});
|
|
17263
|
+
this.responsePromise = responsePromise;
|
|
17264
|
+
this.parseResponse = parseResponse;
|
|
17265
|
+
this.client = client;
|
|
17266
|
+
}
|
|
17267
|
+
_thenUnwrap(transform) {
|
|
17268
|
+
return new APIPromise(this.client, this.responsePromise, async (client, props) => transform(await this.parseResponse(client, props), props));
|
|
17269
|
+
}
|
|
17270
|
+
/**
|
|
17271
|
+
* Gets the raw `Response` instance instead of parsing the response
|
|
17272
|
+
* data.
|
|
17273
|
+
*
|
|
17274
|
+
* If you want to parse the response body but still get the `Response`
|
|
17275
|
+
* instance, you can use {@link withResponse()}.
|
|
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
|
+
asResponse() {
|
|
17282
|
+
return this.responsePromise.then((p) => p.response);
|
|
17283
|
+
}
|
|
17284
|
+
/**
|
|
17285
|
+
* Gets the parsed response data and the raw `Response` instance.
|
|
17286
|
+
*
|
|
17287
|
+
* If you just want to get the raw `Response` instance without parsing it,
|
|
17288
|
+
* you can use {@link asResponse()}.
|
|
17289
|
+
*
|
|
17290
|
+
* 👋 Getting the wrong TypeScript type for `Response`?
|
|
17291
|
+
* Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]`
|
|
17292
|
+
* to your `tsconfig.json`.
|
|
17293
|
+
*/
|
|
17294
|
+
async withResponse() {
|
|
17295
|
+
const [data, response] = await Promise.all([this.parse(), this.asResponse()]);
|
|
17296
|
+
return { data, response };
|
|
17297
|
+
}
|
|
17298
|
+
parse() {
|
|
17299
|
+
if (!this.parsedPromise) {
|
|
17300
|
+
this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(this.client, data));
|
|
17301
|
+
}
|
|
17302
|
+
return this.parsedPromise;
|
|
17303
|
+
}
|
|
17304
|
+
then(onfulfilled, onrejected) {
|
|
17305
|
+
return this.parse().then(onfulfilled, onrejected);
|
|
17306
|
+
}
|
|
17307
|
+
catch(onrejected) {
|
|
17308
|
+
return this.parse().catch(onrejected);
|
|
17309
|
+
}
|
|
17310
|
+
finally(onfinally) {
|
|
17311
|
+
return this.parse().finally(onfinally);
|
|
17312
|
+
}
|
|
17313
|
+
}
|
|
17314
|
+
|
|
17315
|
+
/**
|
|
17316
|
+
* @license
|
|
17317
|
+
* Copyright 2025 Google LLC
|
|
17318
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
17319
|
+
*/
|
|
17320
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
17321
|
+
const brand_privateNullableHeaders = /* @__PURE__ */ Symbol('brand.privateNullableHeaders');
|
|
17322
|
+
function* iterateHeaders(headers) {
|
|
17323
|
+
if (!headers)
|
|
17324
|
+
return;
|
|
17325
|
+
if (brand_privateNullableHeaders in headers) {
|
|
17326
|
+
const { values, nulls } = headers;
|
|
17327
|
+
yield* values.entries();
|
|
17328
|
+
for (const name of nulls) {
|
|
17329
|
+
yield [name, null];
|
|
17330
|
+
}
|
|
17331
|
+
return;
|
|
17332
|
+
}
|
|
17333
|
+
let shouldClear = false;
|
|
17334
|
+
let iter;
|
|
17335
|
+
if (headers instanceof Headers) {
|
|
17336
|
+
iter = headers.entries();
|
|
17337
|
+
}
|
|
17338
|
+
else if (isReadonlyArray(headers)) {
|
|
17339
|
+
iter = headers;
|
|
17340
|
+
}
|
|
17341
|
+
else {
|
|
17342
|
+
shouldClear = true;
|
|
17343
|
+
iter = Object.entries(headers !== null && headers !== void 0 ? headers : {});
|
|
17344
|
+
}
|
|
17345
|
+
for (let row of iter) {
|
|
17346
|
+
const name = row[0];
|
|
17347
|
+
if (typeof name !== 'string')
|
|
17348
|
+
throw new TypeError('expected header name to be a string');
|
|
17349
|
+
const values = isReadonlyArray(row[1]) ? row[1] : [row[1]];
|
|
17350
|
+
let didClear = false;
|
|
17351
|
+
for (const value of values) {
|
|
17352
|
+
if (value === undefined)
|
|
17353
|
+
continue;
|
|
17354
|
+
// Objects keys always overwrite older headers, they never append.
|
|
17355
|
+
// Yield a null to clear the header before adding the new values.
|
|
17356
|
+
if (shouldClear && !didClear) {
|
|
17357
|
+
didClear = true;
|
|
17358
|
+
yield [name, null];
|
|
17359
|
+
}
|
|
17360
|
+
yield [name, value];
|
|
17361
|
+
}
|
|
17362
|
+
}
|
|
17363
|
+
}
|
|
17364
|
+
const buildHeaders = (newHeaders) => {
|
|
17365
|
+
const targetHeaders = new Headers();
|
|
17366
|
+
const nullHeaders = new Set();
|
|
17367
|
+
for (const headers of newHeaders) {
|
|
17368
|
+
const seenHeaders = new Set();
|
|
17369
|
+
for (const [name, value] of iterateHeaders(headers)) {
|
|
17370
|
+
const lowerName = name.toLowerCase();
|
|
17371
|
+
if (!seenHeaders.has(lowerName)) {
|
|
17372
|
+
targetHeaders.delete(name);
|
|
17373
|
+
seenHeaders.add(lowerName);
|
|
17374
|
+
}
|
|
17375
|
+
if (value === null) {
|
|
17376
|
+
targetHeaders.delete(name);
|
|
17377
|
+
nullHeaders.add(lowerName);
|
|
17378
|
+
}
|
|
17379
|
+
else {
|
|
17380
|
+
targetHeaders.append(name, value);
|
|
17381
|
+
nullHeaders.delete(lowerName);
|
|
17382
|
+
}
|
|
17383
|
+
}
|
|
17384
|
+
}
|
|
17385
|
+
return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders };
|
|
17386
|
+
};
|
|
17387
|
+
|
|
17388
|
+
/**
|
|
17389
|
+
* @license
|
|
17390
|
+
* Copyright 2025 Google LLC
|
|
17391
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
17392
|
+
*/
|
|
17393
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
17394
|
+
/**
|
|
17395
|
+
* Read an environment variable.
|
|
17396
|
+
*
|
|
17397
|
+
* Trims beginning and trailing whitespace.
|
|
17398
|
+
*
|
|
17399
|
+
* Will return undefined if the environment variable doesn't exist or cannot be accessed.
|
|
17400
|
+
*/
|
|
17401
|
+
const readEnv = (env) => {
|
|
17402
|
+
var _a, _b, _c, _d, _e, _f;
|
|
17403
|
+
if (typeof globalThis.process !== 'undefined') {
|
|
17404
|
+
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;
|
|
17405
|
+
}
|
|
17406
|
+
if (typeof globalThis.Deno !== 'undefined') {
|
|
17407
|
+
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();
|
|
17408
|
+
}
|
|
17409
|
+
return undefined;
|
|
17410
|
+
};
|
|
17411
|
+
|
|
17412
|
+
/**
|
|
17413
|
+
* @license
|
|
17414
|
+
* Copyright 2025 Google LLC
|
|
17415
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
17416
|
+
*/
|
|
17417
|
+
var _a;
|
|
17418
|
+
/**
|
|
17419
|
+
* Base class for Gemini Next Gen API API clients.
|
|
17420
|
+
*/
|
|
17421
|
+
class BaseGeminiNextGenAPIClient {
|
|
17422
|
+
/**
|
|
17423
|
+
* API Client for interfacing with the Gemini Next Gen API API.
|
|
17424
|
+
*
|
|
17425
|
+
* @param {string | null | undefined} [opts.apiKey=process.env['GEMINI_API_KEY'] ?? null]
|
|
17426
|
+
* @param {string | undefined} [opts.apiVersion=v1beta]
|
|
17427
|
+
* @param {string} [opts.baseURL=process.env['GEMINI_NEXT_GEN_API_BASE_URL'] ?? https://generativelanguage.googleapis.com] - Override the default base URL for the API.
|
|
17428
|
+
* @param {number} [opts.timeout=1 minute] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
|
|
17429
|
+
* @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
|
|
17430
|
+
* @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
|
|
17431
|
+
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
|
|
17432
|
+
* @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
|
|
17433
|
+
* @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
|
|
17434
|
+
*/
|
|
17435
|
+
constructor(_b) {
|
|
17436
|
+
var _c, _d, _e, _f, _g, _h, _j;
|
|
17437
|
+
var _k = _b === void 0 ? {} : _b, { baseURL = readEnv('GEMINI_NEXT_GEN_API_BASE_URL'), apiKey = (_c = readEnv('GEMINI_API_KEY')) !== null && _c !== void 0 ? _c : null, apiVersion = 'v1beta' } = _k, opts = __rest(_k, ["baseURL", "apiKey", "apiVersion"]);
|
|
17438
|
+
const options = Object.assign(Object.assign({ apiKey,
|
|
17439
|
+
apiVersion }, opts), { baseURL: baseURL || `https://generativelanguage.googleapis.com` });
|
|
17440
|
+
this.baseURL = options.baseURL;
|
|
17441
|
+
this.timeout = (_d = options.timeout) !== null && _d !== void 0 ? _d : BaseGeminiNextGenAPIClient.DEFAULT_TIMEOUT /* 1 minute */;
|
|
17442
|
+
this.logger = (_e = options.logger) !== null && _e !== void 0 ? _e : console;
|
|
17443
|
+
const defaultLogLevel = 'warn';
|
|
17444
|
+
// Set default logLevel early so that we can log a warning in parseLogLevel.
|
|
17445
|
+
this.logLevel = defaultLogLevel;
|
|
17446
|
+
this.logLevel =
|
|
17447
|
+
(_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;
|
|
17448
|
+
this.fetchOptions = options.fetchOptions;
|
|
17449
|
+
this.maxRetries = (_h = options.maxRetries) !== null && _h !== void 0 ? _h : 2;
|
|
17450
|
+
this.fetch = (_j = options.fetch) !== null && _j !== void 0 ? _j : getDefaultFetch();
|
|
17451
|
+
this.encoder = FallbackEncoder;
|
|
17452
|
+
this._options = options;
|
|
17453
|
+
this.apiKey = apiKey;
|
|
17454
|
+
this.apiVersion = apiVersion;
|
|
17455
|
+
}
|
|
17456
|
+
/**
|
|
17457
|
+
* Create a new client instance re-using the same options given to the current client with optional overriding.
|
|
17458
|
+
*/
|
|
17459
|
+
withOptions(options) {
|
|
17460
|
+
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));
|
|
17461
|
+
return client;
|
|
17462
|
+
}
|
|
17463
|
+
/**
|
|
17464
|
+
* Check whether the base URL is set to its default.
|
|
17465
|
+
*/
|
|
17466
|
+
baseURLOverridden() {
|
|
17467
|
+
return this.baseURL !== 'https://generativelanguage.googleapis.com';
|
|
17468
|
+
}
|
|
17469
|
+
defaultQuery() {
|
|
17470
|
+
return this._options.defaultQuery;
|
|
17471
|
+
}
|
|
17472
|
+
validateHeaders({ values, nulls }) {
|
|
17473
|
+
if (this.apiKey && values.get('x-goog-api-key')) {
|
|
17474
|
+
return;
|
|
17475
|
+
}
|
|
17476
|
+
if (nulls.has('x-goog-api-key')) {
|
|
17477
|
+
return;
|
|
17478
|
+
}
|
|
17479
|
+
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');
|
|
17480
|
+
}
|
|
17481
|
+
async authHeaders(opts) {
|
|
17482
|
+
if (this.apiKey == null) {
|
|
17483
|
+
return undefined;
|
|
17484
|
+
}
|
|
17485
|
+
return buildHeaders([{ 'x-goog-api-key': this.apiKey }]);
|
|
17486
|
+
}
|
|
17487
|
+
/**
|
|
17488
|
+
* Basic re-implementation of `qs.stringify` for primitive types.
|
|
17489
|
+
*/
|
|
17490
|
+
stringifyQuery(query) {
|
|
17491
|
+
return Object.entries(query)
|
|
17492
|
+
.filter(([_, value]) => typeof value !== 'undefined')
|
|
17493
|
+
.map(([key, value]) => {
|
|
17494
|
+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
|
17495
|
+
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
|
17496
|
+
}
|
|
17497
|
+
if (value === null) {
|
|
17498
|
+
return `${encodeURIComponent(key)}=`;
|
|
17499
|
+
}
|
|
17500
|
+
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.`);
|
|
17501
|
+
})
|
|
17502
|
+
.join('&');
|
|
17503
|
+
}
|
|
17504
|
+
getUserAgent() {
|
|
17505
|
+
return `${this.constructor.name}/JS ${VERSION}`;
|
|
17506
|
+
}
|
|
17507
|
+
defaultIdempotencyKey() {
|
|
17508
|
+
return `stainless-node-retry-${uuid4()}`;
|
|
17509
|
+
}
|
|
17510
|
+
makeStatusError(status, error, message, headers) {
|
|
17511
|
+
return APIError.generate(status, error, message, headers);
|
|
17512
|
+
}
|
|
17513
|
+
buildURL(path, query, defaultBaseURL) {
|
|
17514
|
+
const baseURL = (!this.baseURLOverridden() && defaultBaseURL) || this.baseURL;
|
|
17515
|
+
const url = isAbsoluteURL(path) ?
|
|
17516
|
+
new URL(path)
|
|
17517
|
+
: new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
|
|
17518
|
+
const defaultQuery = this.defaultQuery();
|
|
17519
|
+
if (!isEmptyObj(defaultQuery)) {
|
|
17520
|
+
query = Object.assign(Object.assign({}, defaultQuery), query);
|
|
17521
|
+
}
|
|
17522
|
+
if (typeof query === 'object' && query && !Array.isArray(query)) {
|
|
17523
|
+
url.search = this.stringifyQuery(query);
|
|
17524
|
+
}
|
|
17525
|
+
return url.toString();
|
|
17526
|
+
}
|
|
17527
|
+
/**
|
|
17528
|
+
* Used as a callback for mutating the given `FinalRequestOptions` object.
|
|
17529
|
+
*/
|
|
17530
|
+
async prepareOptions(options) { }
|
|
17531
|
+
/**
|
|
17532
|
+
* Used as a callback for mutating the given `RequestInit` object.
|
|
17533
|
+
*
|
|
17534
|
+
* This is useful for cases where you want to add certain headers based off of
|
|
17535
|
+
* the request properties, e.g. `method` or `url`.
|
|
17536
|
+
*/
|
|
17537
|
+
async prepareRequest(request, { url, options }) { }
|
|
17538
|
+
get(path, opts) {
|
|
17539
|
+
return this.methodRequest('get', path, opts);
|
|
17540
|
+
}
|
|
17541
|
+
post(path, opts) {
|
|
17542
|
+
return this.methodRequest('post', path, opts);
|
|
17543
|
+
}
|
|
17544
|
+
patch(path, opts) {
|
|
17545
|
+
return this.methodRequest('patch', path, opts);
|
|
17546
|
+
}
|
|
17547
|
+
put(path, opts) {
|
|
17548
|
+
return this.methodRequest('put', path, opts);
|
|
17549
|
+
}
|
|
17550
|
+
delete(path, opts) {
|
|
17551
|
+
return this.methodRequest('delete', path, opts);
|
|
17552
|
+
}
|
|
17553
|
+
methodRequest(method, path, opts) {
|
|
17554
|
+
return this.request(Promise.resolve(opts).then((opts) => {
|
|
17555
|
+
return Object.assign({ method, path }, opts);
|
|
17556
|
+
}));
|
|
17557
|
+
}
|
|
17558
|
+
request(options, remainingRetries = null) {
|
|
17559
|
+
return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
|
|
17560
|
+
}
|
|
17561
|
+
async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
|
|
17562
|
+
var _b, _c, _d;
|
|
17563
|
+
const options = await optionsInput;
|
|
17564
|
+
const maxRetries = (_b = options.maxRetries) !== null && _b !== void 0 ? _b : this.maxRetries;
|
|
17565
|
+
if (retriesRemaining == null) {
|
|
17566
|
+
retriesRemaining = maxRetries;
|
|
17567
|
+
}
|
|
17568
|
+
await this.prepareOptions(options);
|
|
17569
|
+
const { req, url, timeout } = await this.buildRequest(options, {
|
|
17570
|
+
retryCount: maxRetries - retriesRemaining,
|
|
17571
|
+
});
|
|
17572
|
+
await this.prepareRequest(req, { url, options });
|
|
17573
|
+
/** Not an API request ID, just for correlating local log entries. */
|
|
17574
|
+
const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
|
|
17575
|
+
const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
|
|
17576
|
+
const startTime = Date.now();
|
|
17577
|
+
loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
|
|
17578
|
+
retryOfRequestLogID,
|
|
17579
|
+
method: options.method,
|
|
17580
|
+
url,
|
|
17581
|
+
options,
|
|
17582
|
+
headers: req.headers,
|
|
17583
|
+
}));
|
|
17584
|
+
if ((_c = options.signal) === null || _c === void 0 ? void 0 : _c.aborted) {
|
|
17585
|
+
throw new APIUserAbortError();
|
|
17586
|
+
}
|
|
17587
|
+
const controller = new AbortController();
|
|
17588
|
+
const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
|
|
17589
|
+
const headersTime = Date.now();
|
|
17590
|
+
if (response instanceof globalThis.Error) {
|
|
17591
|
+
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
|
|
17592
|
+
if ((_d = options.signal) === null || _d === void 0 ? void 0 : _d.aborted) {
|
|
17593
|
+
throw new APIUserAbortError();
|
|
17594
|
+
}
|
|
17595
|
+
// detect native connection timeout errors
|
|
17596
|
+
// 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)"
|
|
17597
|
+
// undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
|
|
17598
|
+
// others do not provide enough information to distinguish timeouts from other connection errors
|
|
17599
|
+
const isTimeout = isAbortError(response) ||
|
|
17600
|
+
/timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
|
|
17601
|
+
if (retriesRemaining) {
|
|
17602
|
+
loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
|
|
17603
|
+
loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
|
|
17604
|
+
retryOfRequestLogID,
|
|
17605
|
+
url,
|
|
17606
|
+
durationMs: headersTime - startTime,
|
|
17607
|
+
message: response.message,
|
|
17608
|
+
}));
|
|
17609
|
+
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID !== null && retryOfRequestLogID !== void 0 ? retryOfRequestLogID : requestLogID);
|
|
17610
|
+
}
|
|
17611
|
+
loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
|
|
17612
|
+
loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
|
|
17613
|
+
retryOfRequestLogID,
|
|
17614
|
+
url,
|
|
17615
|
+
durationMs: headersTime - startTime,
|
|
17616
|
+
message: response.message,
|
|
17617
|
+
}));
|
|
17618
|
+
if (isTimeout) {
|
|
17619
|
+
throw new APIConnectionTimeoutError();
|
|
17620
|
+
}
|
|
17621
|
+
throw new APIConnectionError({ cause: response });
|
|
17622
|
+
}
|
|
17623
|
+
const responseInfo = `[${requestLogID}${retryLogStr}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
|
|
17624
|
+
if (!response.ok) {
|
|
17625
|
+
const shouldRetry = await this.shouldRetry(response);
|
|
17626
|
+
if (retriesRemaining && shouldRetry) {
|
|
17627
|
+
const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
|
|
17628
|
+
// We don't need the body of this response.
|
|
17629
|
+
await CancelReadableStream(response.body);
|
|
17630
|
+
loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
|
|
17631
|
+
loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
|
|
17632
|
+
retryOfRequestLogID,
|
|
17633
|
+
url: response.url,
|
|
17634
|
+
status: response.status,
|
|
17635
|
+
headers: response.headers,
|
|
17636
|
+
durationMs: headersTime - startTime,
|
|
17637
|
+
}));
|
|
17638
|
+
return this.retryRequest(options, retriesRemaining, retryOfRequestLogID !== null && retryOfRequestLogID !== void 0 ? retryOfRequestLogID : requestLogID, response.headers);
|
|
17639
|
+
}
|
|
17640
|
+
const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
|
|
17641
|
+
loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
|
|
17642
|
+
const errText = await response.text().catch((err) => castToError(err).message);
|
|
17643
|
+
const errJSON = safeJSON(errText);
|
|
17644
|
+
const errMessage = errJSON ? undefined : errText;
|
|
17645
|
+
loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
|
|
17646
|
+
retryOfRequestLogID,
|
|
17647
|
+
url: response.url,
|
|
17648
|
+
status: response.status,
|
|
17649
|
+
headers: response.headers,
|
|
17650
|
+
message: errMessage,
|
|
17651
|
+
durationMs: Date.now() - startTime,
|
|
17652
|
+
}));
|
|
17653
|
+
// @ts-ignore
|
|
17654
|
+
const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
|
|
17655
|
+
throw err;
|
|
17656
|
+
}
|
|
17657
|
+
loggerFor(this).info(responseInfo);
|
|
17658
|
+
loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
|
|
17659
|
+
retryOfRequestLogID,
|
|
17660
|
+
url: response.url,
|
|
17661
|
+
status: response.status,
|
|
17662
|
+
headers: response.headers,
|
|
17663
|
+
durationMs: headersTime - startTime,
|
|
17664
|
+
}));
|
|
17665
|
+
return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
|
|
17666
|
+
}
|
|
17667
|
+
async fetchWithTimeout(url, init, ms, controller) {
|
|
17668
|
+
const _b = init || {}, { signal, method } = _b, options = __rest(_b, ["signal", "method"]);
|
|
17669
|
+
if (signal)
|
|
17670
|
+
signal.addEventListener('abort', () => controller.abort());
|
|
17671
|
+
const timeout = setTimeout(() => controller.abort(), ms);
|
|
17672
|
+
const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
|
|
17673
|
+
(typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
|
|
17674
|
+
const fetchOptions = Object.assign(Object.assign(Object.assign({ signal: controller.signal }, (isReadableBody ? { duplex: 'half' } : {})), { method: 'GET' }), options);
|
|
17675
|
+
if (method) {
|
|
17676
|
+
// Custom methods like 'patch' need to be uppercased
|
|
17677
|
+
// See https://github.com/nodejs/undici/issues/2294
|
|
17678
|
+
fetchOptions.method = method.toUpperCase();
|
|
17679
|
+
}
|
|
17680
|
+
try {
|
|
17681
|
+
// use undefined this binding; fetch errors if bound to something else in browser/cloudflare
|
|
17682
|
+
return await this.fetch.call(undefined, url, fetchOptions);
|
|
17683
|
+
}
|
|
17684
|
+
finally {
|
|
17685
|
+
clearTimeout(timeout);
|
|
17686
|
+
}
|
|
17687
|
+
}
|
|
17688
|
+
async shouldRetry(response) {
|
|
17689
|
+
// Note this is not a standard header.
|
|
17690
|
+
const shouldRetryHeader = response.headers.get('x-should-retry');
|
|
17691
|
+
// If the server explicitly says whether or not to retry, obey.
|
|
17692
|
+
if (shouldRetryHeader === 'true')
|
|
17693
|
+
return true;
|
|
17694
|
+
if (shouldRetryHeader === 'false')
|
|
17695
|
+
return false;
|
|
17696
|
+
// Retry on request timeouts.
|
|
17697
|
+
if (response.status === 408)
|
|
17698
|
+
return true;
|
|
17699
|
+
// Retry on lock timeouts.
|
|
17700
|
+
if (response.status === 409)
|
|
17701
|
+
return true;
|
|
17702
|
+
// Retry on rate limits.
|
|
17703
|
+
if (response.status === 429)
|
|
17704
|
+
return true;
|
|
17705
|
+
// Retry internal errors.
|
|
17706
|
+
if (response.status >= 500)
|
|
17707
|
+
return true;
|
|
17708
|
+
return false;
|
|
17709
|
+
}
|
|
17710
|
+
async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
|
|
17711
|
+
var _b;
|
|
17712
|
+
let timeoutMillis;
|
|
17713
|
+
// Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
|
|
17714
|
+
const retryAfterMillisHeader = responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders.get('retry-after-ms');
|
|
17715
|
+
if (retryAfterMillisHeader) {
|
|
17716
|
+
const timeoutMs = parseFloat(retryAfterMillisHeader);
|
|
17717
|
+
if (!Number.isNaN(timeoutMs)) {
|
|
17718
|
+
timeoutMillis = timeoutMs;
|
|
17719
|
+
}
|
|
17720
|
+
}
|
|
17721
|
+
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
|
|
17722
|
+
const retryAfterHeader = responseHeaders === null || responseHeaders === void 0 ? void 0 : responseHeaders.get('retry-after');
|
|
17723
|
+
if (retryAfterHeader && !timeoutMillis) {
|
|
17724
|
+
const timeoutSeconds = parseFloat(retryAfterHeader);
|
|
17725
|
+
if (!Number.isNaN(timeoutSeconds)) {
|
|
17726
|
+
timeoutMillis = timeoutSeconds * 1000;
|
|
17727
|
+
}
|
|
17728
|
+
else {
|
|
17729
|
+
timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
|
|
17730
|
+
}
|
|
17731
|
+
}
|
|
17732
|
+
// If the API asks us to wait a certain amount of time (and it's a reasonable amount),
|
|
17733
|
+
// just do what it says, but otherwise calculate a default
|
|
17734
|
+
if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
|
|
17735
|
+
const maxRetries = (_b = options.maxRetries) !== null && _b !== void 0 ? _b : this.maxRetries;
|
|
17736
|
+
timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
|
|
17737
|
+
}
|
|
17738
|
+
await sleep$1(timeoutMillis);
|
|
17739
|
+
return this.makeRequest(options, retriesRemaining - 1, requestLogID);
|
|
17740
|
+
}
|
|
17741
|
+
calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
|
|
17742
|
+
const initialRetryDelay = 0.5;
|
|
17743
|
+
const maxRetryDelay = 8.0;
|
|
17744
|
+
const numRetries = maxRetries - retriesRemaining;
|
|
17745
|
+
// Apply exponential backoff, but not more than the max.
|
|
17746
|
+
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
|
|
17747
|
+
// Apply some jitter, take up to at most 25 percent of the retry time.
|
|
17748
|
+
const jitter = 1 - Math.random() * 0.25;
|
|
17749
|
+
return sleepSeconds * jitter * 1000;
|
|
17750
|
+
}
|
|
17751
|
+
async buildRequest(inputOptions, { retryCount = 0 } = {}) {
|
|
17752
|
+
var _b, _c, _d;
|
|
17753
|
+
const options = Object.assign({}, inputOptions);
|
|
17754
|
+
const { method, path, query, defaultBaseURL } = options;
|
|
17755
|
+
const url = this.buildURL(path, query, defaultBaseURL);
|
|
17756
|
+
if ('timeout' in options)
|
|
17757
|
+
validatePositiveInteger('timeout', options.timeout);
|
|
17758
|
+
options.timeout = (_b = options.timeout) !== null && _b !== void 0 ? _b : this.timeout;
|
|
17759
|
+
const { bodyHeaders, body } = this.buildBody({ options });
|
|
17760
|
+
const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
|
|
17761
|
+
const req = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ method, headers: reqHeaders }, (options.signal && { signal: options.signal })), (globalThis.ReadableStream &&
|
|
17762
|
+
body instanceof globalThis.ReadableStream && { duplex: 'half' })), (body && { body })), ((_c = this.fetchOptions) !== null && _c !== void 0 ? _c : {})), ((_d = options.fetchOptions) !== null && _d !== void 0 ? _d : {}));
|
|
17763
|
+
return { req, url, timeout: options.timeout };
|
|
17764
|
+
}
|
|
17765
|
+
async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
|
|
17766
|
+
let idempotencyHeaders = {};
|
|
17767
|
+
if (this.idempotencyHeader && method !== 'get') {
|
|
17768
|
+
if (!options.idempotencyKey)
|
|
17769
|
+
options.idempotencyKey = this.defaultIdempotencyKey();
|
|
17770
|
+
idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
|
|
17771
|
+
}
|
|
17772
|
+
const headers = buildHeaders([
|
|
17773
|
+
idempotencyHeaders,
|
|
17774
|
+
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()),
|
|
17775
|
+
await this.authHeaders(options),
|
|
17776
|
+
this._options.defaultHeaders,
|
|
17777
|
+
bodyHeaders,
|
|
17778
|
+
options.headers,
|
|
17779
|
+
]);
|
|
17780
|
+
this.validateHeaders(headers);
|
|
17781
|
+
return headers.values;
|
|
17782
|
+
}
|
|
17783
|
+
buildBody({ options: { body, headers: rawHeaders } }) {
|
|
17784
|
+
if (!body) {
|
|
17785
|
+
return { bodyHeaders: undefined, body: undefined };
|
|
17786
|
+
}
|
|
17787
|
+
const headers = buildHeaders([rawHeaders]);
|
|
17788
|
+
if (
|
|
17789
|
+
// Pass raw type verbatim
|
|
17790
|
+
ArrayBuffer.isView(body) ||
|
|
17791
|
+
body instanceof ArrayBuffer ||
|
|
17792
|
+
body instanceof DataView ||
|
|
17793
|
+
(typeof body === 'string' &&
|
|
17794
|
+
// Preserve legacy string encoding behavior for now
|
|
17795
|
+
headers.values.has('content-type')) ||
|
|
17796
|
+
// `Blob` is superset of `File`
|
|
17797
|
+
(globalThis.Blob && body instanceof globalThis.Blob) ||
|
|
17798
|
+
// `FormData` -> `multipart/form-data`
|
|
17799
|
+
body instanceof FormData ||
|
|
17800
|
+
// `URLSearchParams` -> `application/x-www-form-urlencoded`
|
|
17801
|
+
body instanceof URLSearchParams ||
|
|
17802
|
+
// Send chunked stream (each chunk has own `length`)
|
|
17803
|
+
(globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
|
|
17804
|
+
return { bodyHeaders: undefined, body: body };
|
|
17805
|
+
}
|
|
17806
|
+
else if (typeof body === 'object' &&
|
|
17807
|
+
(Symbol.asyncIterator in body ||
|
|
17808
|
+
(Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
|
|
17809
|
+
return { bodyHeaders: undefined, body: ReadableStreamFrom(body) };
|
|
17810
|
+
}
|
|
17811
|
+
else {
|
|
17812
|
+
return this.encoder({ body, headers });
|
|
17813
|
+
}
|
|
17814
|
+
}
|
|
17815
|
+
}
|
|
17816
|
+
BaseGeminiNextGenAPIClient.DEFAULT_TIMEOUT = 60000; // 1 minute
|
|
17817
|
+
/**
|
|
17818
|
+
* API Client for interfacing with the Gemini Next Gen API API.
|
|
17819
|
+
*/
|
|
17820
|
+
class GeminiNextGenAPIClient extends BaseGeminiNextGenAPIClient {
|
|
17821
|
+
constructor() {
|
|
17822
|
+
super(...arguments);
|
|
17823
|
+
this.interactions = new Interactions(this);
|
|
17824
|
+
}
|
|
17825
|
+
}
|
|
17826
|
+
_a = GeminiNextGenAPIClient;
|
|
17827
|
+
GeminiNextGenAPIClient.GeminiNextGenAPIClient = _a;
|
|
17828
|
+
GeminiNextGenAPIClient.GeminiNextGenAPIClientError = GeminiNextGenAPIClientError;
|
|
17829
|
+
GeminiNextGenAPIClient.APIError = APIError;
|
|
17830
|
+
GeminiNextGenAPIClient.APIConnectionError = APIConnectionError;
|
|
17831
|
+
GeminiNextGenAPIClient.APIConnectionTimeoutError = APIConnectionTimeoutError;
|
|
17832
|
+
GeminiNextGenAPIClient.APIUserAbortError = APIUserAbortError;
|
|
17833
|
+
GeminiNextGenAPIClient.NotFoundError = NotFoundError;
|
|
17834
|
+
GeminiNextGenAPIClient.ConflictError = ConflictError;
|
|
17835
|
+
GeminiNextGenAPIClient.RateLimitError = RateLimitError;
|
|
17836
|
+
GeminiNextGenAPIClient.BadRequestError = BadRequestError;
|
|
17837
|
+
GeminiNextGenAPIClient.AuthenticationError = AuthenticationError;
|
|
17838
|
+
GeminiNextGenAPIClient.InternalServerError = InternalServerError;
|
|
17839
|
+
GeminiNextGenAPIClient.PermissionDeniedError = PermissionDeniedError;
|
|
17840
|
+
GeminiNextGenAPIClient.UnprocessableEntityError = UnprocessableEntityError;
|
|
17841
|
+
GeminiNextGenAPIClient.toFile = toFile;
|
|
17842
|
+
GeminiNextGenAPIClient.Interactions = Interactions;
|
|
17843
|
+
|
|
17844
|
+
/**
|
|
17845
|
+
* @license
|
|
17846
|
+
* Copyright 2025 Google LLC
|
|
17847
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
17848
|
+
*/
|
|
17849
|
+
// Code generated by the Google Gen AI SDK generator DO NOT EDIT.
|
|
17850
|
+
function cancelTuningJobParametersToMldev(fromObject, _rootObject) {
|
|
17851
|
+
const toObject = {};
|
|
17852
|
+
const fromName = getValueByPath(fromObject, ['name']);
|
|
17853
|
+
if (fromName != null) {
|
|
17854
|
+
setValueByPath(toObject, ['_url', 'name'], fromName);
|
|
17855
|
+
}
|
|
17856
|
+
return toObject;
|
|
17857
|
+
}
|
|
17858
|
+
function cancelTuningJobParametersToVertex(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 cancelTuningJobResponseFromMldev(fromObject, _rootObject) {
|
|
17867
|
+
const toObject = {};
|
|
17868
|
+
const fromSdkHttpResponse = getValueByPath(fromObject, [
|
|
17869
|
+
'sdkHttpResponse',
|
|
17870
|
+
]);
|
|
17871
|
+
if (fromSdkHttpResponse != null) {
|
|
17872
|
+
setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);
|
|
17873
|
+
}
|
|
17874
|
+
return toObject;
|
|
17875
|
+
}
|
|
17876
|
+
function cancelTuningJobResponseFromVertex(fromObject, _rootObject) {
|
|
17877
|
+
const toObject = {};
|
|
17878
|
+
const fromSdkHttpResponse = getValueByPath(fromObject, [
|
|
17879
|
+
'sdkHttpResponse',
|
|
17880
|
+
]);
|
|
17881
|
+
if (fromSdkHttpResponse != null) {
|
|
17882
|
+
setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);
|
|
17883
|
+
}
|
|
17884
|
+
return toObject;
|
|
17885
|
+
}
|
|
17886
|
+
function createTuningJobConfigToMldev(fromObject, parentObject, _rootObject) {
|
|
17887
|
+
const toObject = {};
|
|
17888
|
+
if (getValueByPath(fromObject, ['validationDataset']) !== undefined) {
|
|
17889
|
+
throw new Error('validationDataset parameter is not supported in Gemini API.');
|
|
17890
|
+
}
|
|
17891
|
+
const fromTunedModelDisplayName = getValueByPath(fromObject, [
|
|
17892
|
+
'tunedModelDisplayName',
|
|
17893
|
+
]);
|
|
17894
|
+
if (parentObject !== undefined && fromTunedModelDisplayName != null) {
|
|
17895
|
+
setValueByPath(parentObject, ['displayName'], fromTunedModelDisplayName);
|
|
17896
|
+
}
|
|
17897
|
+
if (getValueByPath(fromObject, ['description']) !== undefined) {
|
|
17898
|
+
throw new Error('description parameter is not supported in Gemini API.');
|
|
17899
|
+
}
|
|
17900
|
+
const fromEpochCount = getValueByPath(fromObject, ['epochCount']);
|
|
17901
|
+
if (parentObject !== undefined && fromEpochCount != null) {
|
|
17902
|
+
setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'epochCount'], fromEpochCount);
|
|
17903
|
+
}
|
|
17904
|
+
const fromLearningRateMultiplier = getValueByPath(fromObject, [
|
|
17905
|
+
'learningRateMultiplier',
|
|
17906
|
+
]);
|
|
17907
|
+
if (fromLearningRateMultiplier != null) {
|
|
17908
|
+
setValueByPath(toObject, ['tuningTask', 'hyperparameters', 'learningRateMultiplier'], fromLearningRateMultiplier);
|
|
17909
|
+
}
|
|
17910
|
+
if (getValueByPath(fromObject, ['exportLastCheckpointOnly']) !==
|
|
17911
|
+
undefined) {
|
|
17912
|
+
throw new Error('exportLastCheckpointOnly parameter is not supported in Gemini API.');
|
|
17913
|
+
}
|
|
17914
|
+
if (getValueByPath(fromObject, ['preTunedModelCheckpointId']) !==
|
|
17915
|
+
undefined) {
|
|
17916
|
+
throw new Error('preTunedModelCheckpointId parameter is not supported in Gemini API.');
|
|
17917
|
+
}
|
|
17918
|
+
if (getValueByPath(fromObject, ['adapterSize']) !== undefined) {
|
|
17919
|
+
throw new Error('adapterSize parameter is not supported in Gemini API.');
|
|
17920
|
+
}
|
|
17921
|
+
const fromBatchSize = getValueByPath(fromObject, ['batchSize']);
|
|
17922
|
+
if (parentObject !== undefined && fromBatchSize != null) {
|
|
17923
|
+
setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'batchSize'], fromBatchSize);
|
|
17924
|
+
}
|
|
17925
|
+
const fromLearningRate = getValueByPath(fromObject, ['learningRate']);
|
|
17926
|
+
if (parentObject !== undefined && fromLearningRate != null) {
|
|
17927
|
+
setValueByPath(parentObject, ['tuningTask', 'hyperparameters', 'learningRate'], fromLearningRate);
|
|
17928
|
+
}
|
|
17929
|
+
if (getValueByPath(fromObject, ['labels']) !== undefined) {
|
|
17930
|
+
throw new Error('labels parameter is not supported in Gemini API.');
|
|
17931
|
+
}
|
|
17932
|
+
if (getValueByPath(fromObject, ['beta']) !== undefined) {
|
|
17933
|
+
throw new Error('beta parameter is not supported in Gemini API.');
|
|
17934
|
+
}
|
|
17935
|
+
return toObject;
|
|
17936
|
+
}
|
|
17937
|
+
function createTuningJobConfigToVertex(fromObject, parentObject, rootObject) {
|
|
17938
|
+
const toObject = {};
|
|
17939
|
+
let discriminatorValidationDataset = getValueByPath(rootObject, [
|
|
17940
|
+
'config',
|
|
17941
|
+
'method',
|
|
17942
|
+
]);
|
|
17943
|
+
if (discriminatorValidationDataset === undefined) {
|
|
17944
|
+
discriminatorValidationDataset = 'SUPERVISED_FINE_TUNING';
|
|
17945
|
+
}
|
|
17946
|
+
if (discriminatorValidationDataset === 'SUPERVISED_FINE_TUNING') {
|
|
15886
17947
|
const fromValidationDataset = getValueByPath(fromObject, [
|
|
15887
17948
|
'validationDataset',
|
|
15888
17949
|
]);
|
|
@@ -17074,6 +19135,28 @@ const LANGUAGE_LABEL_PREFIX = 'gl-node/';
|
|
|
17074
19135
|
*
|
|
17075
19136
|
*/
|
|
17076
19137
|
class GoogleGenAI {
|
|
19138
|
+
get interactions() {
|
|
19139
|
+
if (this._interactions !== undefined) {
|
|
19140
|
+
return this._interactions;
|
|
19141
|
+
}
|
|
19142
|
+
console.warn('GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions.');
|
|
19143
|
+
if (this.vertexai) {
|
|
19144
|
+
throw new Error('This version of the GenAI SDK does not support Vertex AI API for interactions.');
|
|
19145
|
+
}
|
|
19146
|
+
const httpOpts = this.httpOptions;
|
|
19147
|
+
// Unsupported Options Warnings
|
|
19148
|
+
if (httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.extraBody) {
|
|
19149
|
+
console.warn('GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.');
|
|
19150
|
+
}
|
|
19151
|
+
const nextGenClient = new GeminiNextGenAPIClient({
|
|
19152
|
+
baseURL: this.apiClient.getBaseUrl(),
|
|
19153
|
+
apiKey: this.apiKey,
|
|
19154
|
+
defaultHeaders: this.apiClient.getDefaultHeaders(),
|
|
19155
|
+
timeout: httpOpts === null || httpOpts === void 0 ? void 0 : httpOpts.timeout,
|
|
19156
|
+
});
|
|
19157
|
+
this._interactions = nextGenClient.interactions;
|
|
19158
|
+
return this._interactions;
|
|
19159
|
+
}
|
|
17077
19160
|
constructor(options) {
|
|
17078
19161
|
var _a;
|
|
17079
19162
|
if (options.apiKey == null) {
|
|
@@ -17122,5 +19205,5 @@ class GoogleGenAI {
|
|
|
17122
19205
|
}
|
|
17123
19206
|
}
|
|
17124
19207
|
|
|
17125
|
-
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 };
|
|
19208
|
+
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 };
|
|
17126
19209
|
//# sourceMappingURL=index.mjs.map
|