@weavelogic/knowledge-graph-agent 0.10.4 → 0.10.5

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.
@@ -0,0 +1,1256 @@
1
+ var SchemaType;
2
+ (function(SchemaType2) {
3
+ SchemaType2["STRING"] = "string";
4
+ SchemaType2["NUMBER"] = "number";
5
+ SchemaType2["INTEGER"] = "integer";
6
+ SchemaType2["BOOLEAN"] = "boolean";
7
+ SchemaType2["ARRAY"] = "array";
8
+ SchemaType2["OBJECT"] = "object";
9
+ })(SchemaType || (SchemaType = {}));
10
+ /**
11
+ * @license
12
+ * Copyright 2024 Google LLC
13
+ *
14
+ * Licensed under the Apache License, Version 2.0 (the "License");
15
+ * you may not use this file except in compliance with the License.
16
+ * You may obtain a copy of the License at
17
+ *
18
+ * http://www.apache.org/licenses/LICENSE-2.0
19
+ *
20
+ * Unless required by applicable law or agreed to in writing, software
21
+ * distributed under the License is distributed on an "AS IS" BASIS,
22
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23
+ * See the License for the specific language governing permissions and
24
+ * limitations under the License.
25
+ */
26
+ var ExecutableCodeLanguage;
27
+ (function(ExecutableCodeLanguage2) {
28
+ ExecutableCodeLanguage2["LANGUAGE_UNSPECIFIED"] = "language_unspecified";
29
+ ExecutableCodeLanguage2["PYTHON"] = "python";
30
+ })(ExecutableCodeLanguage || (ExecutableCodeLanguage = {}));
31
+ var Outcome;
32
+ (function(Outcome2) {
33
+ Outcome2["OUTCOME_UNSPECIFIED"] = "outcome_unspecified";
34
+ Outcome2["OUTCOME_OK"] = "outcome_ok";
35
+ Outcome2["OUTCOME_FAILED"] = "outcome_failed";
36
+ Outcome2["OUTCOME_DEADLINE_EXCEEDED"] = "outcome_deadline_exceeded";
37
+ })(Outcome || (Outcome = {}));
38
+ /**
39
+ * @license
40
+ * Copyright 2024 Google LLC
41
+ *
42
+ * Licensed under the Apache License, Version 2.0 (the "License");
43
+ * you may not use this file except in compliance with the License.
44
+ * You may obtain a copy of the License at
45
+ *
46
+ * http://www.apache.org/licenses/LICENSE-2.0
47
+ *
48
+ * Unless required by applicable law or agreed to in writing, software
49
+ * distributed under the License is distributed on an "AS IS" BASIS,
50
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
51
+ * See the License for the specific language governing permissions and
52
+ * limitations under the License.
53
+ */
54
+ const POSSIBLE_ROLES = ["user", "model", "function", "system"];
55
+ var HarmCategory;
56
+ (function(HarmCategory2) {
57
+ HarmCategory2["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED";
58
+ HarmCategory2["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH";
59
+ HarmCategory2["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT";
60
+ HarmCategory2["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT";
61
+ HarmCategory2["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT";
62
+ HarmCategory2["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY";
63
+ })(HarmCategory || (HarmCategory = {}));
64
+ var HarmBlockThreshold;
65
+ (function(HarmBlockThreshold2) {
66
+ HarmBlockThreshold2["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED";
67
+ HarmBlockThreshold2["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
68
+ HarmBlockThreshold2["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
69
+ HarmBlockThreshold2["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
70
+ HarmBlockThreshold2["BLOCK_NONE"] = "BLOCK_NONE";
71
+ })(HarmBlockThreshold || (HarmBlockThreshold = {}));
72
+ var HarmProbability;
73
+ (function(HarmProbability2) {
74
+ HarmProbability2["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED";
75
+ HarmProbability2["NEGLIGIBLE"] = "NEGLIGIBLE";
76
+ HarmProbability2["LOW"] = "LOW";
77
+ HarmProbability2["MEDIUM"] = "MEDIUM";
78
+ HarmProbability2["HIGH"] = "HIGH";
79
+ })(HarmProbability || (HarmProbability = {}));
80
+ var BlockReason;
81
+ (function(BlockReason2) {
82
+ BlockReason2["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED";
83
+ BlockReason2["SAFETY"] = "SAFETY";
84
+ BlockReason2["OTHER"] = "OTHER";
85
+ })(BlockReason || (BlockReason = {}));
86
+ var FinishReason;
87
+ (function(FinishReason2) {
88
+ FinishReason2["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED";
89
+ FinishReason2["STOP"] = "STOP";
90
+ FinishReason2["MAX_TOKENS"] = "MAX_TOKENS";
91
+ FinishReason2["SAFETY"] = "SAFETY";
92
+ FinishReason2["RECITATION"] = "RECITATION";
93
+ FinishReason2["LANGUAGE"] = "LANGUAGE";
94
+ FinishReason2["BLOCKLIST"] = "BLOCKLIST";
95
+ FinishReason2["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
96
+ FinishReason2["SPII"] = "SPII";
97
+ FinishReason2["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL";
98
+ FinishReason2["OTHER"] = "OTHER";
99
+ })(FinishReason || (FinishReason = {}));
100
+ var TaskType;
101
+ (function(TaskType2) {
102
+ TaskType2["TASK_TYPE_UNSPECIFIED"] = "TASK_TYPE_UNSPECIFIED";
103
+ TaskType2["RETRIEVAL_QUERY"] = "RETRIEVAL_QUERY";
104
+ TaskType2["RETRIEVAL_DOCUMENT"] = "RETRIEVAL_DOCUMENT";
105
+ TaskType2["SEMANTIC_SIMILARITY"] = "SEMANTIC_SIMILARITY";
106
+ TaskType2["CLASSIFICATION"] = "CLASSIFICATION";
107
+ TaskType2["CLUSTERING"] = "CLUSTERING";
108
+ })(TaskType || (TaskType = {}));
109
+ var FunctionCallingMode;
110
+ (function(FunctionCallingMode2) {
111
+ FunctionCallingMode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
112
+ FunctionCallingMode2["AUTO"] = "AUTO";
113
+ FunctionCallingMode2["ANY"] = "ANY";
114
+ FunctionCallingMode2["NONE"] = "NONE";
115
+ })(FunctionCallingMode || (FunctionCallingMode = {}));
116
+ var DynamicRetrievalMode;
117
+ (function(DynamicRetrievalMode2) {
118
+ DynamicRetrievalMode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
119
+ DynamicRetrievalMode2["MODE_DYNAMIC"] = "MODE_DYNAMIC";
120
+ })(DynamicRetrievalMode || (DynamicRetrievalMode = {}));
121
+ /**
122
+ * @license
123
+ * Copyright 2024 Google LLC
124
+ *
125
+ * Licensed under the Apache License, Version 2.0 (the "License");
126
+ * you may not use this file except in compliance with the License.
127
+ * You may obtain a copy of the License at
128
+ *
129
+ * http://www.apache.org/licenses/LICENSE-2.0
130
+ *
131
+ * Unless required by applicable law or agreed to in writing, software
132
+ * distributed under the License is distributed on an "AS IS" BASIS,
133
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
134
+ * See the License for the specific language governing permissions and
135
+ * limitations under the License.
136
+ */
137
+ class GoogleGenerativeAIError extends Error {
138
+ constructor(message) {
139
+ super(`[GoogleGenerativeAI Error]: ${message}`);
140
+ }
141
+ }
142
+ class GoogleGenerativeAIResponseError extends GoogleGenerativeAIError {
143
+ constructor(message, response) {
144
+ super(message);
145
+ this.response = response;
146
+ }
147
+ }
148
+ class GoogleGenerativeAIFetchError extends GoogleGenerativeAIError {
149
+ constructor(message, status, statusText, errorDetails) {
150
+ super(message);
151
+ this.status = status;
152
+ this.statusText = statusText;
153
+ this.errorDetails = errorDetails;
154
+ }
155
+ }
156
+ class GoogleGenerativeAIRequestInputError extends GoogleGenerativeAIError {
157
+ }
158
+ class GoogleGenerativeAIAbortError extends GoogleGenerativeAIError {
159
+ }
160
+ /**
161
+ * @license
162
+ * Copyright 2024 Google LLC
163
+ *
164
+ * Licensed under the Apache License, Version 2.0 (the "License");
165
+ * you may not use this file except in compliance with the License.
166
+ * You may obtain a copy of the License at
167
+ *
168
+ * http://www.apache.org/licenses/LICENSE-2.0
169
+ *
170
+ * Unless required by applicable law or agreed to in writing, software
171
+ * distributed under the License is distributed on an "AS IS" BASIS,
172
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
173
+ * See the License for the specific language governing permissions and
174
+ * limitations under the License.
175
+ */
176
+ const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com";
177
+ const DEFAULT_API_VERSION = "v1beta";
178
+ const PACKAGE_VERSION = "0.24.1";
179
+ const PACKAGE_LOG_HEADER = "genai-js";
180
+ var Task;
181
+ (function(Task2) {
182
+ Task2["GENERATE_CONTENT"] = "generateContent";
183
+ Task2["STREAM_GENERATE_CONTENT"] = "streamGenerateContent";
184
+ Task2["COUNT_TOKENS"] = "countTokens";
185
+ Task2["EMBED_CONTENT"] = "embedContent";
186
+ Task2["BATCH_EMBED_CONTENTS"] = "batchEmbedContents";
187
+ })(Task || (Task = {}));
188
+ class RequestUrl {
189
+ constructor(model, task, apiKey, stream, requestOptions) {
190
+ this.model = model;
191
+ this.task = task;
192
+ this.apiKey = apiKey;
193
+ this.stream = stream;
194
+ this.requestOptions = requestOptions;
195
+ }
196
+ toString() {
197
+ var _a, _b;
198
+ const apiVersion = ((_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.apiVersion) || DEFAULT_API_VERSION;
199
+ const baseUrl = ((_b = this.requestOptions) === null || _b === void 0 ? void 0 : _b.baseUrl) || DEFAULT_BASE_URL;
200
+ let url = `${baseUrl}/${apiVersion}/${this.model}:${this.task}`;
201
+ if (this.stream) {
202
+ url += "?alt=sse";
203
+ }
204
+ return url;
205
+ }
206
+ }
207
+ function getClientHeaders(requestOptions) {
208
+ const clientHeaders = [];
209
+ if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.apiClient) {
210
+ clientHeaders.push(requestOptions.apiClient);
211
+ }
212
+ clientHeaders.push(`${PACKAGE_LOG_HEADER}/${PACKAGE_VERSION}`);
213
+ return clientHeaders.join(" ");
214
+ }
215
+ async function getHeaders(url) {
216
+ var _a;
217
+ const headers = new Headers();
218
+ headers.append("Content-Type", "application/json");
219
+ headers.append("x-goog-api-client", getClientHeaders(url.requestOptions));
220
+ headers.append("x-goog-api-key", url.apiKey);
221
+ let customHeaders = (_a = url.requestOptions) === null || _a === void 0 ? void 0 : _a.customHeaders;
222
+ if (customHeaders) {
223
+ if (!(customHeaders instanceof Headers)) {
224
+ try {
225
+ customHeaders = new Headers(customHeaders);
226
+ } catch (e) {
227
+ throw new GoogleGenerativeAIRequestInputError(`unable to convert customHeaders value ${JSON.stringify(customHeaders)} to Headers: ${e.message}`);
228
+ }
229
+ }
230
+ for (const [headerName, headerValue] of customHeaders.entries()) {
231
+ if (headerName === "x-goog-api-key") {
232
+ throw new GoogleGenerativeAIRequestInputError(`Cannot set reserved header name ${headerName}`);
233
+ } else if (headerName === "x-goog-api-client") {
234
+ throw new GoogleGenerativeAIRequestInputError(`Header name ${headerName} can only be set using the apiClient field`);
235
+ }
236
+ headers.append(headerName, headerValue);
237
+ }
238
+ }
239
+ return headers;
240
+ }
241
+ async function constructModelRequest(model, task, apiKey, stream, body, requestOptions) {
242
+ const url = new RequestUrl(model, task, apiKey, stream, requestOptions);
243
+ return {
244
+ url: url.toString(),
245
+ fetchOptions: Object.assign(Object.assign({}, buildFetchOptions(requestOptions)), { method: "POST", headers: await getHeaders(url), body })
246
+ };
247
+ }
248
+ async function makeModelRequest(model, task, apiKey, stream, body, requestOptions = {}, fetchFn = fetch) {
249
+ const { url, fetchOptions } = await constructModelRequest(model, task, apiKey, stream, body, requestOptions);
250
+ return makeRequest(url, fetchOptions, fetchFn);
251
+ }
252
+ async function makeRequest(url, fetchOptions, fetchFn = fetch) {
253
+ let response;
254
+ try {
255
+ response = await fetchFn(url, fetchOptions);
256
+ } catch (e) {
257
+ handleResponseError(e, url);
258
+ }
259
+ if (!response.ok) {
260
+ await handleResponseNotOk(response, url);
261
+ }
262
+ return response;
263
+ }
264
+ function handleResponseError(e, url) {
265
+ let err = e;
266
+ if (err.name === "AbortError") {
267
+ err = new GoogleGenerativeAIAbortError(`Request aborted when fetching ${url.toString()}: ${e.message}`);
268
+ err.stack = e.stack;
269
+ } else if (!(e instanceof GoogleGenerativeAIFetchError || e instanceof GoogleGenerativeAIRequestInputError)) {
270
+ err = new GoogleGenerativeAIError(`Error fetching from ${url.toString()}: ${e.message}`);
271
+ err.stack = e.stack;
272
+ }
273
+ throw err;
274
+ }
275
+ async function handleResponseNotOk(response, url) {
276
+ let message = "";
277
+ let errorDetails;
278
+ try {
279
+ const json = await response.json();
280
+ message = json.error.message;
281
+ if (json.error.details) {
282
+ message += ` ${JSON.stringify(json.error.details)}`;
283
+ errorDetails = json.error.details;
284
+ }
285
+ } catch (e) {
286
+ }
287
+ throw new GoogleGenerativeAIFetchError(`Error fetching from ${url.toString()}: [${response.status} ${response.statusText}] ${message}`, response.status, response.statusText, errorDetails);
288
+ }
289
+ function buildFetchOptions(requestOptions) {
290
+ const fetchOptions = {};
291
+ if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) !== void 0 || (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {
292
+ const controller = new AbortController();
293
+ if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {
294
+ setTimeout(() => controller.abort(), requestOptions.timeout);
295
+ }
296
+ if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) {
297
+ requestOptions.signal.addEventListener("abort", () => {
298
+ controller.abort();
299
+ });
300
+ }
301
+ fetchOptions.signal = controller.signal;
302
+ }
303
+ return fetchOptions;
304
+ }
305
+ /**
306
+ * @license
307
+ * Copyright 2024 Google LLC
308
+ *
309
+ * Licensed under the Apache License, Version 2.0 (the "License");
310
+ * you may not use this file except in compliance with the License.
311
+ * You may obtain a copy of the License at
312
+ *
313
+ * http://www.apache.org/licenses/LICENSE-2.0
314
+ *
315
+ * Unless required by applicable law or agreed to in writing, software
316
+ * distributed under the License is distributed on an "AS IS" BASIS,
317
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
318
+ * See the License for the specific language governing permissions and
319
+ * limitations under the License.
320
+ */
321
+ function addHelpers(response) {
322
+ response.text = () => {
323
+ if (response.candidates && response.candidates.length > 0) {
324
+ if (response.candidates.length > 1) {
325
+ console.warn(`This response had ${response.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`);
326
+ }
327
+ if (hadBadFinishReason(response.candidates[0])) {
328
+ throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);
329
+ }
330
+ return getText(response);
331
+ } else if (response.promptFeedback) {
332
+ throw new GoogleGenerativeAIResponseError(`Text not available. ${formatBlockErrorMessage(response)}`, response);
333
+ }
334
+ return "";
335
+ };
336
+ response.functionCall = () => {
337
+ if (response.candidates && response.candidates.length > 0) {
338
+ if (response.candidates.length > 1) {
339
+ console.warn(`This response had ${response.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`);
340
+ }
341
+ if (hadBadFinishReason(response.candidates[0])) {
342
+ throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);
343
+ }
344
+ console.warn(`response.functionCall() is deprecated. Use response.functionCalls() instead.`);
345
+ return getFunctionCalls(response)[0];
346
+ } else if (response.promptFeedback) {
347
+ throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response);
348
+ }
349
+ return void 0;
350
+ };
351
+ response.functionCalls = () => {
352
+ if (response.candidates && response.candidates.length > 0) {
353
+ if (response.candidates.length > 1) {
354
+ console.warn(`This response had ${response.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`);
355
+ }
356
+ if (hadBadFinishReason(response.candidates[0])) {
357
+ throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);
358
+ }
359
+ return getFunctionCalls(response);
360
+ } else if (response.promptFeedback) {
361
+ throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response);
362
+ }
363
+ return void 0;
364
+ };
365
+ return response;
366
+ }
367
+ function getText(response) {
368
+ var _a, _b, _c, _d;
369
+ const textStrings = [];
370
+ if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) {
371
+ for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) {
372
+ if (part.text) {
373
+ textStrings.push(part.text);
374
+ }
375
+ if (part.executableCode) {
376
+ textStrings.push("\n```" + part.executableCode.language + "\n" + part.executableCode.code + "\n```\n");
377
+ }
378
+ if (part.codeExecutionResult) {
379
+ textStrings.push("\n```\n" + part.codeExecutionResult.output + "\n```\n");
380
+ }
381
+ }
382
+ }
383
+ if (textStrings.length > 0) {
384
+ return textStrings.join("");
385
+ } else {
386
+ return "";
387
+ }
388
+ }
389
+ function getFunctionCalls(response) {
390
+ var _a, _b, _c, _d;
391
+ const functionCalls = [];
392
+ if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) {
393
+ for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) {
394
+ if (part.functionCall) {
395
+ functionCalls.push(part.functionCall);
396
+ }
397
+ }
398
+ }
399
+ if (functionCalls.length > 0) {
400
+ return functionCalls;
401
+ } else {
402
+ return void 0;
403
+ }
404
+ }
405
+ const badFinishReasons = [
406
+ FinishReason.RECITATION,
407
+ FinishReason.SAFETY,
408
+ FinishReason.LANGUAGE
409
+ ];
410
+ function hadBadFinishReason(candidate) {
411
+ return !!candidate.finishReason && badFinishReasons.includes(candidate.finishReason);
412
+ }
413
+ function formatBlockErrorMessage(response) {
414
+ var _a, _b, _c;
415
+ let message = "";
416
+ if ((!response.candidates || response.candidates.length === 0) && response.promptFeedback) {
417
+ message += "Response was blocked";
418
+ if ((_a = response.promptFeedback) === null || _a === void 0 ? void 0 : _a.blockReason) {
419
+ message += ` due to ${response.promptFeedback.blockReason}`;
420
+ }
421
+ if ((_b = response.promptFeedback) === null || _b === void 0 ? void 0 : _b.blockReasonMessage) {
422
+ message += `: ${response.promptFeedback.blockReasonMessage}`;
423
+ }
424
+ } else if ((_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0]) {
425
+ const firstCandidate = response.candidates[0];
426
+ if (hadBadFinishReason(firstCandidate)) {
427
+ message += `Candidate was blocked due to ${firstCandidate.finishReason}`;
428
+ if (firstCandidate.finishMessage) {
429
+ message += `: ${firstCandidate.finishMessage}`;
430
+ }
431
+ }
432
+ }
433
+ return message;
434
+ }
435
+ function __await(v) {
436
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
437
+ }
438
+ function __asyncGenerator(thisArg, _arguments, generator) {
439
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
440
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
441
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
442
+ return this;
443
+ }, i;
444
+ function verb(n) {
445
+ if (g[n]) i[n] = function(v) {
446
+ return new Promise(function(a, b) {
447
+ q.push([n, v, a, b]) > 1 || resume(n, v);
448
+ });
449
+ };
450
+ }
451
+ function resume(n, v) {
452
+ try {
453
+ step(g[n](v));
454
+ } catch (e) {
455
+ settle(q[0][3], e);
456
+ }
457
+ }
458
+ function step(r) {
459
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
460
+ }
461
+ function fulfill(value) {
462
+ resume("next", value);
463
+ }
464
+ function reject(value) {
465
+ resume("throw", value);
466
+ }
467
+ function settle(f, v) {
468
+ if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
469
+ }
470
+ }
471
+ typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
472
+ var e = new Error(message);
473
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
474
+ };
475
+ /**
476
+ * @license
477
+ * Copyright 2024 Google LLC
478
+ *
479
+ * Licensed under the Apache License, Version 2.0 (the "License");
480
+ * you may not use this file except in compliance with the License.
481
+ * You may obtain a copy of the License at
482
+ *
483
+ * http://www.apache.org/licenses/LICENSE-2.0
484
+ *
485
+ * Unless required by applicable law or agreed to in writing, software
486
+ * distributed under the License is distributed on an "AS IS" BASIS,
487
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
488
+ * See the License for the specific language governing permissions and
489
+ * limitations under the License.
490
+ */
491
+ const responseLineRE = /^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;
492
+ function processStream(response) {
493
+ const inputStream = response.body.pipeThrough(new TextDecoderStream("utf8", { fatal: true }));
494
+ const responseStream = getResponseStream(inputStream);
495
+ const [stream1, stream2] = responseStream.tee();
496
+ return {
497
+ stream: generateResponseSequence(stream1),
498
+ response: getResponsePromise(stream2)
499
+ };
500
+ }
501
+ async function getResponsePromise(stream) {
502
+ const allResponses = [];
503
+ const reader = stream.getReader();
504
+ while (true) {
505
+ const { done, value } = await reader.read();
506
+ if (done) {
507
+ return addHelpers(aggregateResponses(allResponses));
508
+ }
509
+ allResponses.push(value);
510
+ }
511
+ }
512
+ function generateResponseSequence(stream) {
513
+ return __asyncGenerator(this, arguments, function* generateResponseSequence_1() {
514
+ const reader = stream.getReader();
515
+ while (true) {
516
+ const { value, done } = yield __await(reader.read());
517
+ if (done) {
518
+ break;
519
+ }
520
+ yield yield __await(addHelpers(value));
521
+ }
522
+ });
523
+ }
524
+ function getResponseStream(inputStream) {
525
+ const reader = inputStream.getReader();
526
+ const stream = new ReadableStream({
527
+ start(controller) {
528
+ let currentText = "";
529
+ return pump();
530
+ function pump() {
531
+ return reader.read().then(({ value, done }) => {
532
+ if (done) {
533
+ if (currentText.trim()) {
534
+ controller.error(new GoogleGenerativeAIError("Failed to parse stream"));
535
+ return;
536
+ }
537
+ controller.close();
538
+ return;
539
+ }
540
+ currentText += value;
541
+ let match = currentText.match(responseLineRE);
542
+ let parsedResponse;
543
+ while (match) {
544
+ try {
545
+ parsedResponse = JSON.parse(match[1]);
546
+ } catch (e) {
547
+ controller.error(new GoogleGenerativeAIError(`Error parsing JSON response: "${match[1]}"`));
548
+ return;
549
+ }
550
+ controller.enqueue(parsedResponse);
551
+ currentText = currentText.substring(match[0].length);
552
+ match = currentText.match(responseLineRE);
553
+ }
554
+ return pump();
555
+ }).catch((e) => {
556
+ let err = e;
557
+ err.stack = e.stack;
558
+ if (err.name === "AbortError") {
559
+ err = new GoogleGenerativeAIAbortError("Request aborted when reading from the stream");
560
+ } else {
561
+ err = new GoogleGenerativeAIError("Error reading from the stream");
562
+ }
563
+ throw err;
564
+ });
565
+ }
566
+ }
567
+ });
568
+ return stream;
569
+ }
570
+ function aggregateResponses(responses) {
571
+ const lastResponse = responses[responses.length - 1];
572
+ const aggregatedResponse = {
573
+ promptFeedback: lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.promptFeedback
574
+ };
575
+ for (const response of responses) {
576
+ if (response.candidates) {
577
+ let candidateIndex = 0;
578
+ for (const candidate of response.candidates) {
579
+ if (!aggregatedResponse.candidates) {
580
+ aggregatedResponse.candidates = [];
581
+ }
582
+ if (!aggregatedResponse.candidates[candidateIndex]) {
583
+ aggregatedResponse.candidates[candidateIndex] = {
584
+ index: candidateIndex
585
+ };
586
+ }
587
+ aggregatedResponse.candidates[candidateIndex].citationMetadata = candidate.citationMetadata;
588
+ aggregatedResponse.candidates[candidateIndex].groundingMetadata = candidate.groundingMetadata;
589
+ aggregatedResponse.candidates[candidateIndex].finishReason = candidate.finishReason;
590
+ aggregatedResponse.candidates[candidateIndex].finishMessage = candidate.finishMessage;
591
+ aggregatedResponse.candidates[candidateIndex].safetyRatings = candidate.safetyRatings;
592
+ if (candidate.content && candidate.content.parts) {
593
+ if (!aggregatedResponse.candidates[candidateIndex].content) {
594
+ aggregatedResponse.candidates[candidateIndex].content = {
595
+ role: candidate.content.role || "user",
596
+ parts: []
597
+ };
598
+ }
599
+ const newPart = {};
600
+ for (const part of candidate.content.parts) {
601
+ if (part.text) {
602
+ newPart.text = part.text;
603
+ }
604
+ if (part.functionCall) {
605
+ newPart.functionCall = part.functionCall;
606
+ }
607
+ if (part.executableCode) {
608
+ newPart.executableCode = part.executableCode;
609
+ }
610
+ if (part.codeExecutionResult) {
611
+ newPart.codeExecutionResult = part.codeExecutionResult;
612
+ }
613
+ if (Object.keys(newPart).length === 0) {
614
+ newPart.text = "";
615
+ }
616
+ aggregatedResponse.candidates[candidateIndex].content.parts.push(newPart);
617
+ }
618
+ }
619
+ }
620
+ candidateIndex++;
621
+ }
622
+ if (response.usageMetadata) {
623
+ aggregatedResponse.usageMetadata = response.usageMetadata;
624
+ }
625
+ }
626
+ return aggregatedResponse;
627
+ }
628
+ /**
629
+ * @license
630
+ * Copyright 2024 Google LLC
631
+ *
632
+ * Licensed under the Apache License, Version 2.0 (the "License");
633
+ * you may not use this file except in compliance with the License.
634
+ * You may obtain a copy of the License at
635
+ *
636
+ * http://www.apache.org/licenses/LICENSE-2.0
637
+ *
638
+ * Unless required by applicable law or agreed to in writing, software
639
+ * distributed under the License is distributed on an "AS IS" BASIS,
640
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
641
+ * See the License for the specific language governing permissions and
642
+ * limitations under the License.
643
+ */
644
+ async function generateContentStream(apiKey, model, params, requestOptions) {
645
+ const response = await makeModelRequest(
646
+ model,
647
+ Task.STREAM_GENERATE_CONTENT,
648
+ apiKey,
649
+ /* stream */
650
+ true,
651
+ JSON.stringify(params),
652
+ requestOptions
653
+ );
654
+ return processStream(response);
655
+ }
656
+ async function generateContent(apiKey, model, params, requestOptions) {
657
+ const response = await makeModelRequest(
658
+ model,
659
+ Task.GENERATE_CONTENT,
660
+ apiKey,
661
+ /* stream */
662
+ false,
663
+ JSON.stringify(params),
664
+ requestOptions
665
+ );
666
+ const responseJson = await response.json();
667
+ const enhancedResponse = addHelpers(responseJson);
668
+ return {
669
+ response: enhancedResponse
670
+ };
671
+ }
672
+ /**
673
+ * @license
674
+ * Copyright 2024 Google LLC
675
+ *
676
+ * Licensed under the Apache License, Version 2.0 (the "License");
677
+ * you may not use this file except in compliance with the License.
678
+ * You may obtain a copy of the License at
679
+ *
680
+ * http://www.apache.org/licenses/LICENSE-2.0
681
+ *
682
+ * Unless required by applicable law or agreed to in writing, software
683
+ * distributed under the License is distributed on an "AS IS" BASIS,
684
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
685
+ * See the License for the specific language governing permissions and
686
+ * limitations under the License.
687
+ */
688
+ function formatSystemInstruction(input) {
689
+ if (input == null) {
690
+ return void 0;
691
+ } else if (typeof input === "string") {
692
+ return { role: "system", parts: [{ text: input }] };
693
+ } else if (input.text) {
694
+ return { role: "system", parts: [input] };
695
+ } else if (input.parts) {
696
+ if (!input.role) {
697
+ return { role: "system", parts: input.parts };
698
+ } else {
699
+ return input;
700
+ }
701
+ }
702
+ }
703
+ function formatNewContent(request) {
704
+ let newParts = [];
705
+ if (typeof request === "string") {
706
+ newParts = [{ text: request }];
707
+ } else {
708
+ for (const partOrString of request) {
709
+ if (typeof partOrString === "string") {
710
+ newParts.push({ text: partOrString });
711
+ } else {
712
+ newParts.push(partOrString);
713
+ }
714
+ }
715
+ }
716
+ return assignRoleToPartsAndValidateSendMessageRequest(newParts);
717
+ }
718
+ function assignRoleToPartsAndValidateSendMessageRequest(parts) {
719
+ const userContent = { role: "user", parts: [] };
720
+ const functionContent = { role: "function", parts: [] };
721
+ let hasUserContent = false;
722
+ let hasFunctionContent = false;
723
+ for (const part of parts) {
724
+ if ("functionResponse" in part) {
725
+ functionContent.parts.push(part);
726
+ hasFunctionContent = true;
727
+ } else {
728
+ userContent.parts.push(part);
729
+ hasUserContent = true;
730
+ }
731
+ }
732
+ if (hasUserContent && hasFunctionContent) {
733
+ throw new GoogleGenerativeAIError("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");
734
+ }
735
+ if (!hasUserContent && !hasFunctionContent) {
736
+ throw new GoogleGenerativeAIError("No content is provided for sending chat message.");
737
+ }
738
+ if (hasUserContent) {
739
+ return userContent;
740
+ }
741
+ return functionContent;
742
+ }
743
+ function formatCountTokensInput(params, modelParams) {
744
+ var _a;
745
+ let formattedGenerateContentRequest = {
746
+ model: modelParams === null || modelParams === void 0 ? void 0 : modelParams.model,
747
+ generationConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.generationConfig,
748
+ safetySettings: modelParams === null || modelParams === void 0 ? void 0 : modelParams.safetySettings,
749
+ tools: modelParams === null || modelParams === void 0 ? void 0 : modelParams.tools,
750
+ toolConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.toolConfig,
751
+ systemInstruction: modelParams === null || modelParams === void 0 ? void 0 : modelParams.systemInstruction,
752
+ cachedContent: (_a = modelParams === null || modelParams === void 0 ? void 0 : modelParams.cachedContent) === null || _a === void 0 ? void 0 : _a.name,
753
+ contents: []
754
+ };
755
+ const containsGenerateContentRequest = params.generateContentRequest != null;
756
+ if (params.contents) {
757
+ if (containsGenerateContentRequest) {
758
+ throw new GoogleGenerativeAIRequestInputError("CountTokensRequest must have one of contents or generateContentRequest, not both.");
759
+ }
760
+ formattedGenerateContentRequest.contents = params.contents;
761
+ } else if (containsGenerateContentRequest) {
762
+ formattedGenerateContentRequest = Object.assign(Object.assign({}, formattedGenerateContentRequest), params.generateContentRequest);
763
+ } else {
764
+ const content = formatNewContent(params);
765
+ formattedGenerateContentRequest.contents = [content];
766
+ }
767
+ return { generateContentRequest: formattedGenerateContentRequest };
768
+ }
769
+ function formatGenerateContentInput(params) {
770
+ let formattedRequest;
771
+ if (params.contents) {
772
+ formattedRequest = params;
773
+ } else {
774
+ const content = formatNewContent(params);
775
+ formattedRequest = { contents: [content] };
776
+ }
777
+ if (params.systemInstruction) {
778
+ formattedRequest.systemInstruction = formatSystemInstruction(params.systemInstruction);
779
+ }
780
+ return formattedRequest;
781
+ }
782
+ function formatEmbedContentInput(params) {
783
+ if (typeof params === "string" || Array.isArray(params)) {
784
+ const content = formatNewContent(params);
785
+ return { content };
786
+ }
787
+ return params;
788
+ }
789
+ /**
790
+ * @license
791
+ * Copyright 2024 Google LLC
792
+ *
793
+ * Licensed under the Apache License, Version 2.0 (the "License");
794
+ * you may not use this file except in compliance with the License.
795
+ * You may obtain a copy of the License at
796
+ *
797
+ * http://www.apache.org/licenses/LICENSE-2.0
798
+ *
799
+ * Unless required by applicable law or agreed to in writing, software
800
+ * distributed under the License is distributed on an "AS IS" BASIS,
801
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
802
+ * See the License for the specific language governing permissions and
803
+ * limitations under the License.
804
+ */
805
+ const VALID_PART_FIELDS = [
806
+ "text",
807
+ "inlineData",
808
+ "functionCall",
809
+ "functionResponse",
810
+ "executableCode",
811
+ "codeExecutionResult"
812
+ ];
813
+ const VALID_PARTS_PER_ROLE = {
814
+ user: ["text", "inlineData"],
815
+ function: ["functionResponse"],
816
+ model: ["text", "functionCall", "executableCode", "codeExecutionResult"],
817
+ // System instructions shouldn't be in history anyway.
818
+ system: ["text"]
819
+ };
820
+ function validateChatHistory(history) {
821
+ let prevContent = false;
822
+ for (const currContent of history) {
823
+ const { role, parts } = currContent;
824
+ if (!prevContent && role !== "user") {
825
+ throw new GoogleGenerativeAIError(`First content should be with role 'user', got ${role}`);
826
+ }
827
+ if (!POSSIBLE_ROLES.includes(role)) {
828
+ throw new GoogleGenerativeAIError(`Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(POSSIBLE_ROLES)}`);
829
+ }
830
+ if (!Array.isArray(parts)) {
831
+ throw new GoogleGenerativeAIError("Content should have 'parts' property with an array of Parts");
832
+ }
833
+ if (parts.length === 0) {
834
+ throw new GoogleGenerativeAIError("Each Content should have at least one part");
835
+ }
836
+ const countFields = {
837
+ text: 0,
838
+ inlineData: 0,
839
+ functionCall: 0,
840
+ functionResponse: 0,
841
+ fileData: 0,
842
+ executableCode: 0,
843
+ codeExecutionResult: 0
844
+ };
845
+ for (const part of parts) {
846
+ for (const key of VALID_PART_FIELDS) {
847
+ if (key in part) {
848
+ countFields[key] += 1;
849
+ }
850
+ }
851
+ }
852
+ const validParts = VALID_PARTS_PER_ROLE[role];
853
+ for (const key of VALID_PART_FIELDS) {
854
+ if (!validParts.includes(key) && countFields[key] > 0) {
855
+ throw new GoogleGenerativeAIError(`Content with role '${role}' can't contain '${key}' part`);
856
+ }
857
+ }
858
+ prevContent = true;
859
+ }
860
+ }
861
+ function isValidResponse(response) {
862
+ var _a;
863
+ if (response.candidates === void 0 || response.candidates.length === 0) {
864
+ return false;
865
+ }
866
+ const content = (_a = response.candidates[0]) === null || _a === void 0 ? void 0 : _a.content;
867
+ if (content === void 0) {
868
+ return false;
869
+ }
870
+ if (content.parts === void 0 || content.parts.length === 0) {
871
+ return false;
872
+ }
873
+ for (const part of content.parts) {
874
+ if (part === void 0 || Object.keys(part).length === 0) {
875
+ return false;
876
+ }
877
+ if (part.text !== void 0 && part.text === "") {
878
+ return false;
879
+ }
880
+ }
881
+ return true;
882
+ }
883
+ /**
884
+ * @license
885
+ * Copyright 2024 Google LLC
886
+ *
887
+ * Licensed under the Apache License, Version 2.0 (the "License");
888
+ * you may not use this file except in compliance with the License.
889
+ * You may obtain a copy of the License at
890
+ *
891
+ * http://www.apache.org/licenses/LICENSE-2.0
892
+ *
893
+ * Unless required by applicable law or agreed to in writing, software
894
+ * distributed under the License is distributed on an "AS IS" BASIS,
895
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
896
+ * See the License for the specific language governing permissions and
897
+ * limitations under the License.
898
+ */
899
+ const SILENT_ERROR = "SILENT_ERROR";
900
+ class ChatSession {
901
+ constructor(apiKey, model, params, _requestOptions = {}) {
902
+ this.model = model;
903
+ this.params = params;
904
+ this._requestOptions = _requestOptions;
905
+ this._history = [];
906
+ this._sendPromise = Promise.resolve();
907
+ this._apiKey = apiKey;
908
+ if (params === null || params === void 0 ? void 0 : params.history) {
909
+ validateChatHistory(params.history);
910
+ this._history = params.history;
911
+ }
912
+ }
913
+ /**
914
+ * Gets the chat history so far. Blocked prompts are not added to history.
915
+ * Blocked candidates are not added to history, nor are the prompts that
916
+ * generated them.
917
+ */
918
+ async getHistory() {
919
+ await this._sendPromise;
920
+ return this._history;
921
+ }
922
+ /**
923
+ * Sends a chat message and receives a non-streaming
924
+ * {@link GenerateContentResult}.
925
+ *
926
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
927
+ * take precedence over the {@link RequestOptions} values provided to
928
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
929
+ */
930
+ async sendMessage(request, requestOptions = {}) {
931
+ var _a, _b, _c, _d, _e, _f;
932
+ await this._sendPromise;
933
+ const newContent = formatNewContent(request);
934
+ const generateContentRequest = {
935
+ safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings,
936
+ generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig,
937
+ tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools,
938
+ toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig,
939
+ systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction,
940
+ cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent,
941
+ contents: [...this._history, newContent]
942
+ };
943
+ const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
944
+ let finalResult;
945
+ this._sendPromise = this._sendPromise.then(() => generateContent(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions)).then((result) => {
946
+ var _a2;
947
+ if (isValidResponse(result.response)) {
948
+ this._history.push(newContent);
949
+ const responseContent = Object.assign({
950
+ parts: [],
951
+ // Response seems to come back without a role set.
952
+ role: "model"
953
+ }, (_a2 = result.response.candidates) === null || _a2 === void 0 ? void 0 : _a2[0].content);
954
+ this._history.push(responseContent);
955
+ } else {
956
+ const blockErrorMessage = formatBlockErrorMessage(result.response);
957
+ if (blockErrorMessage) {
958
+ console.warn(`sendMessage() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);
959
+ }
960
+ }
961
+ finalResult = result;
962
+ }).catch((e) => {
963
+ this._sendPromise = Promise.resolve();
964
+ throw e;
965
+ });
966
+ await this._sendPromise;
967
+ return finalResult;
968
+ }
969
+ /**
970
+ * Sends a chat message and receives the response as a
971
+ * {@link GenerateContentStreamResult} containing an iterable stream
972
+ * and a response promise.
973
+ *
974
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
975
+ * take precedence over the {@link RequestOptions} values provided to
976
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
977
+ */
978
+ async sendMessageStream(request, requestOptions = {}) {
979
+ var _a, _b, _c, _d, _e, _f;
980
+ await this._sendPromise;
981
+ const newContent = formatNewContent(request);
982
+ const generateContentRequest = {
983
+ safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings,
984
+ generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig,
985
+ tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools,
986
+ toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig,
987
+ systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction,
988
+ cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent,
989
+ contents: [...this._history, newContent]
990
+ };
991
+ const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
992
+ const streamPromise = generateContentStream(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions);
993
+ this._sendPromise = this._sendPromise.then(() => streamPromise).catch((_ignored) => {
994
+ throw new Error(SILENT_ERROR);
995
+ }).then((streamResult) => streamResult.response).then((response) => {
996
+ if (isValidResponse(response)) {
997
+ this._history.push(newContent);
998
+ const responseContent = Object.assign({}, response.candidates[0].content);
999
+ if (!responseContent.role) {
1000
+ responseContent.role = "model";
1001
+ }
1002
+ this._history.push(responseContent);
1003
+ } else {
1004
+ const blockErrorMessage = formatBlockErrorMessage(response);
1005
+ if (blockErrorMessage) {
1006
+ console.warn(`sendMessageStream() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);
1007
+ }
1008
+ }
1009
+ }).catch((e) => {
1010
+ if (e.message !== SILENT_ERROR) {
1011
+ console.error(e);
1012
+ }
1013
+ });
1014
+ return streamPromise;
1015
+ }
1016
+ }
1017
+ /**
1018
+ * @license
1019
+ * Copyright 2024 Google LLC
1020
+ *
1021
+ * Licensed under the Apache License, Version 2.0 (the "License");
1022
+ * you may not use this file except in compliance with the License.
1023
+ * You may obtain a copy of the License at
1024
+ *
1025
+ * http://www.apache.org/licenses/LICENSE-2.0
1026
+ *
1027
+ * Unless required by applicable law or agreed to in writing, software
1028
+ * distributed under the License is distributed on an "AS IS" BASIS,
1029
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1030
+ * See the License for the specific language governing permissions and
1031
+ * limitations under the License.
1032
+ */
1033
+ async function countTokens(apiKey, model, params, singleRequestOptions) {
1034
+ const response = await makeModelRequest(model, Task.COUNT_TOKENS, apiKey, false, JSON.stringify(params), singleRequestOptions);
1035
+ return response.json();
1036
+ }
1037
+ /**
1038
+ * @license
1039
+ * Copyright 2024 Google LLC
1040
+ *
1041
+ * Licensed under the Apache License, Version 2.0 (the "License");
1042
+ * you may not use this file except in compliance with the License.
1043
+ * You may obtain a copy of the License at
1044
+ *
1045
+ * http://www.apache.org/licenses/LICENSE-2.0
1046
+ *
1047
+ * Unless required by applicable law or agreed to in writing, software
1048
+ * distributed under the License is distributed on an "AS IS" BASIS,
1049
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1050
+ * See the License for the specific language governing permissions and
1051
+ * limitations under the License.
1052
+ */
1053
+ async function embedContent(apiKey, model, params, requestOptions) {
1054
+ const response = await makeModelRequest(model, Task.EMBED_CONTENT, apiKey, false, JSON.stringify(params), requestOptions);
1055
+ return response.json();
1056
+ }
1057
+ async function batchEmbedContents(apiKey, model, params, requestOptions) {
1058
+ const requestsWithModel = params.requests.map((request) => {
1059
+ return Object.assign(Object.assign({}, request), { model });
1060
+ });
1061
+ const response = await makeModelRequest(model, Task.BATCH_EMBED_CONTENTS, apiKey, false, JSON.stringify({ requests: requestsWithModel }), requestOptions);
1062
+ return response.json();
1063
+ }
1064
+ /**
1065
+ * @license
1066
+ * Copyright 2024 Google LLC
1067
+ *
1068
+ * Licensed under the Apache License, Version 2.0 (the "License");
1069
+ * you may not use this file except in compliance with the License.
1070
+ * You may obtain a copy of the License at
1071
+ *
1072
+ * http://www.apache.org/licenses/LICENSE-2.0
1073
+ *
1074
+ * Unless required by applicable law or agreed to in writing, software
1075
+ * distributed under the License is distributed on an "AS IS" BASIS,
1076
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1077
+ * See the License for the specific language governing permissions and
1078
+ * limitations under the License.
1079
+ */
1080
+ class GenerativeModel {
1081
+ constructor(apiKey, modelParams, _requestOptions = {}) {
1082
+ this.apiKey = apiKey;
1083
+ this._requestOptions = _requestOptions;
1084
+ if (modelParams.model.includes("/")) {
1085
+ this.model = modelParams.model;
1086
+ } else {
1087
+ this.model = `models/${modelParams.model}`;
1088
+ }
1089
+ this.generationConfig = modelParams.generationConfig || {};
1090
+ this.safetySettings = modelParams.safetySettings || [];
1091
+ this.tools = modelParams.tools;
1092
+ this.toolConfig = modelParams.toolConfig;
1093
+ this.systemInstruction = formatSystemInstruction(modelParams.systemInstruction);
1094
+ this.cachedContent = modelParams.cachedContent;
1095
+ }
1096
+ /**
1097
+ * Makes a single non-streaming call to the model
1098
+ * and returns an object containing a single {@link GenerateContentResponse}.
1099
+ *
1100
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1101
+ * take precedence over the {@link RequestOptions} values provided to
1102
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1103
+ */
1104
+ async generateContent(request, requestOptions = {}) {
1105
+ var _a;
1106
+ const formattedParams = formatGenerateContentInput(request);
1107
+ const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1108
+ return generateContent(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, formattedParams), generativeModelRequestOptions);
1109
+ }
1110
+ /**
1111
+ * Makes a single streaming call to the model and returns an object
1112
+ * containing an iterable stream that iterates over all chunks in the
1113
+ * streaming response as well as a promise that returns the final
1114
+ * aggregated response.
1115
+ *
1116
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1117
+ * take precedence over the {@link RequestOptions} values provided to
1118
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1119
+ */
1120
+ async generateContentStream(request, requestOptions = {}) {
1121
+ var _a;
1122
+ const formattedParams = formatGenerateContentInput(request);
1123
+ const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1124
+ return generateContentStream(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, formattedParams), generativeModelRequestOptions);
1125
+ }
1126
+ /**
1127
+ * Gets a new {@link ChatSession} instance which can be used for
1128
+ * multi-turn chats.
1129
+ */
1130
+ startChat(startChatParams) {
1131
+ var _a;
1132
+ return new ChatSession(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, startChatParams), this._requestOptions);
1133
+ }
1134
+ /**
1135
+ * Counts the tokens in the provided request.
1136
+ *
1137
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1138
+ * take precedence over the {@link RequestOptions} values provided to
1139
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1140
+ */
1141
+ async countTokens(request, requestOptions = {}) {
1142
+ const formattedParams = formatCountTokensInput(request, {
1143
+ model: this.model,
1144
+ generationConfig: this.generationConfig,
1145
+ safetySettings: this.safetySettings,
1146
+ tools: this.tools,
1147
+ toolConfig: this.toolConfig,
1148
+ systemInstruction: this.systemInstruction,
1149
+ cachedContent: this.cachedContent
1150
+ });
1151
+ const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1152
+ return countTokens(this.apiKey, this.model, formattedParams, generativeModelRequestOptions);
1153
+ }
1154
+ /**
1155
+ * Embeds the provided content.
1156
+ *
1157
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1158
+ * take precedence over the {@link RequestOptions} values provided to
1159
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1160
+ */
1161
+ async embedContent(request, requestOptions = {}) {
1162
+ const formattedParams = formatEmbedContentInput(request);
1163
+ const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1164
+ return embedContent(this.apiKey, this.model, formattedParams, generativeModelRequestOptions);
1165
+ }
1166
+ /**
1167
+ * Embeds an array of {@link EmbedContentRequest}s.
1168
+ *
1169
+ * Fields set in the optional {@link SingleRequestOptions} parameter will
1170
+ * take precedence over the {@link RequestOptions} values provided to
1171
+ * {@link GoogleGenerativeAI.getGenerativeModel }.
1172
+ */
1173
+ async batchEmbedContents(batchEmbedContentRequest, requestOptions = {}) {
1174
+ const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1175
+ return batchEmbedContents(this.apiKey, this.model, batchEmbedContentRequest, generativeModelRequestOptions);
1176
+ }
1177
+ }
1178
+ /**
1179
+ * @license
1180
+ * Copyright 2024 Google LLC
1181
+ *
1182
+ * Licensed under the Apache License, Version 2.0 (the "License");
1183
+ * you may not use this file except in compliance with the License.
1184
+ * You may obtain a copy of the License at
1185
+ *
1186
+ * http://www.apache.org/licenses/LICENSE-2.0
1187
+ *
1188
+ * Unless required by applicable law or agreed to in writing, software
1189
+ * distributed under the License is distributed on an "AS IS" BASIS,
1190
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1191
+ * See the License for the specific language governing permissions and
1192
+ * limitations under the License.
1193
+ */
1194
+ class GoogleGenerativeAI {
1195
+ constructor(apiKey) {
1196
+ this.apiKey = apiKey;
1197
+ }
1198
+ /**
1199
+ * Gets a {@link GenerativeModel} instance for the provided model name.
1200
+ */
1201
+ getGenerativeModel(modelParams, requestOptions) {
1202
+ if (!modelParams.model) {
1203
+ throw new GoogleGenerativeAIError(`Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })`);
1204
+ }
1205
+ return new GenerativeModel(this.apiKey, modelParams, requestOptions);
1206
+ }
1207
+ /**
1208
+ * Creates a {@link GenerativeModel} instance from provided content cache.
1209
+ */
1210
+ getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions) {
1211
+ if (!cachedContent.name) {
1212
+ throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `name` field.");
1213
+ }
1214
+ if (!cachedContent.model) {
1215
+ throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `model` field.");
1216
+ }
1217
+ const disallowedDuplicates = ["model", "systemInstruction"];
1218
+ for (const key of disallowedDuplicates) {
1219
+ if ((modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) && cachedContent[key] && (modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) !== cachedContent[key]) {
1220
+ if (key === "model") {
1221
+ const modelParamsComp = modelParams.model.startsWith("models/") ? modelParams.model.replace("models/", "") : modelParams.model;
1222
+ const cachedContentComp = cachedContent.model.startsWith("models/") ? cachedContent.model.replace("models/", "") : cachedContent.model;
1223
+ if (modelParamsComp === cachedContentComp) {
1224
+ continue;
1225
+ }
1226
+ }
1227
+ throw new GoogleGenerativeAIRequestInputError(`Different value for "${key}" specified in modelParams (${modelParams[key]}) and cachedContent (${cachedContent[key]})`);
1228
+ }
1229
+ }
1230
+ const modelParamsFromCache = Object.assign(Object.assign({}, modelParams), { model: cachedContent.model, tools: cachedContent.tools, toolConfig: cachedContent.toolConfig, systemInstruction: cachedContent.systemInstruction, cachedContent });
1231
+ return new GenerativeModel(this.apiKey, modelParamsFromCache, requestOptions);
1232
+ }
1233
+ }
1234
+ export {
1235
+ BlockReason,
1236
+ ChatSession,
1237
+ DynamicRetrievalMode,
1238
+ ExecutableCodeLanguage,
1239
+ FinishReason,
1240
+ FunctionCallingMode,
1241
+ GenerativeModel,
1242
+ GoogleGenerativeAI,
1243
+ GoogleGenerativeAIAbortError,
1244
+ GoogleGenerativeAIError,
1245
+ GoogleGenerativeAIFetchError,
1246
+ GoogleGenerativeAIRequestInputError,
1247
+ GoogleGenerativeAIResponseError,
1248
+ HarmBlockThreshold,
1249
+ HarmCategory,
1250
+ HarmProbability,
1251
+ Outcome,
1252
+ POSSIBLE_ROLES,
1253
+ SchemaType,
1254
+ TaskType
1255
+ };
1256
+ //# sourceMappingURL=index.js.map