@junando/worker 0.13.0 → 0.15.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.
@@ -1,1463 +0,0 @@
1
- const require_rolldown_runtime = require('./rolldown-runtime-BDXX5GFZ.cjs');
2
-
3
- //#region ../../node_modules/.pnpm/@google+generative-ai@0.24.1/node_modules/@google/generative-ai/dist/index.mjs
4
- /**
5
- * Contains the list of OpenAPI data types
6
- * as defined by https://swagger.io/docs/specification/data-models/data-types/
7
- * @public
8
- */
9
- var SchemaType;
10
- (function(SchemaType) {
11
- /** String type. */
12
- SchemaType["STRING"] = "string";
13
- /** Number type. */
14
- SchemaType["NUMBER"] = "number";
15
- /** Integer type. */
16
- SchemaType["INTEGER"] = "integer";
17
- /** Boolean type. */
18
- SchemaType["BOOLEAN"] = "boolean";
19
- /** Array type. */
20
- SchemaType["ARRAY"] = "array";
21
- /** Object type. */
22
- SchemaType["OBJECT"] = "object";
23
- })(SchemaType || (SchemaType = {}));
24
- /**
25
- * @license
26
- * Copyright 2024 Google LLC
27
- *
28
- * Licensed under the Apache License, Version 2.0 (the "License");
29
- * you may not use this file except in compliance with the License.
30
- * You may obtain a copy of the License at
31
- *
32
- * http://www.apache.org/licenses/LICENSE-2.0
33
- *
34
- * Unless required by applicable law or agreed to in writing, software
35
- * distributed under the License is distributed on an "AS IS" BASIS,
36
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
37
- * See the License for the specific language governing permissions and
38
- * limitations under the License.
39
- */
40
- /**
41
- * @public
42
- */
43
- var ExecutableCodeLanguage;
44
- (function(ExecutableCodeLanguage) {
45
- ExecutableCodeLanguage["LANGUAGE_UNSPECIFIED"] = "language_unspecified";
46
- ExecutableCodeLanguage["PYTHON"] = "python";
47
- })(ExecutableCodeLanguage || (ExecutableCodeLanguage = {}));
48
- /**
49
- * Possible outcomes of code execution.
50
- * @public
51
- */
52
- var Outcome;
53
- (function(Outcome) {
54
- /**
55
- * Unspecified status. This value should not be used.
56
- */
57
- Outcome["OUTCOME_UNSPECIFIED"] = "outcome_unspecified";
58
- /**
59
- * Code execution completed successfully.
60
- */
61
- Outcome["OUTCOME_OK"] = "outcome_ok";
62
- /**
63
- * Code execution finished but with a failure. `stderr` should contain the
64
- * reason.
65
- */
66
- Outcome["OUTCOME_FAILED"] = "outcome_failed";
67
- /**
68
- * Code execution ran for too long, and was cancelled. There may or may not
69
- * be a partial output present.
70
- */
71
- Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "outcome_deadline_exceeded";
72
- })(Outcome || (Outcome = {}));
73
- /**
74
- * @license
75
- * Copyright 2024 Google LLC
76
- *
77
- * Licensed under the Apache License, Version 2.0 (the "License");
78
- * you may not use this file except in compliance with the License.
79
- * You may obtain a copy of the License at
80
- *
81
- * http://www.apache.org/licenses/LICENSE-2.0
82
- *
83
- * Unless required by applicable law or agreed to in writing, software
84
- * distributed under the License is distributed on an "AS IS" BASIS,
85
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
86
- * See the License for the specific language governing permissions and
87
- * limitations under the License.
88
- */
89
- /**
90
- * Possible roles.
91
- * @public
92
- */
93
- const POSSIBLE_ROLES = [
94
- "user",
95
- "model",
96
- "function",
97
- "system"
98
- ];
99
- /**
100
- * Harm categories that would cause prompts or candidates to be blocked.
101
- * @public
102
- */
103
- var HarmCategory;
104
- (function(HarmCategory) {
105
- HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED";
106
- HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH";
107
- HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT";
108
- HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT";
109
- HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT";
110
- HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY";
111
- })(HarmCategory || (HarmCategory = {}));
112
- /**
113
- * Threshold above which a prompt or candidate will be blocked.
114
- * @public
115
- */
116
- var HarmBlockThreshold;
117
- (function(HarmBlockThreshold) {
118
- /** Threshold is unspecified. */
119
- HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED";
120
- /** Content with NEGLIGIBLE will be allowed. */
121
- HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE";
122
- /** Content with NEGLIGIBLE and LOW will be allowed. */
123
- HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE";
124
- /** Content with NEGLIGIBLE, LOW, and MEDIUM will be allowed. */
125
- HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH";
126
- /** All content will be allowed. */
127
- HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE";
128
- })(HarmBlockThreshold || (HarmBlockThreshold = {}));
129
- /**
130
- * Probability that a prompt or candidate matches a harm category.
131
- * @public
132
- */
133
- var HarmProbability;
134
- (function(HarmProbability) {
135
- /** Probability is unspecified. */
136
- HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED";
137
- /** Content has a negligible chance of being unsafe. */
138
- HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE";
139
- /** Content has a low chance of being unsafe. */
140
- HarmProbability["LOW"] = "LOW";
141
- /** Content has a medium chance of being unsafe. */
142
- HarmProbability["MEDIUM"] = "MEDIUM";
143
- /** Content has a high chance of being unsafe. */
144
- HarmProbability["HIGH"] = "HIGH";
145
- })(HarmProbability || (HarmProbability = {}));
146
- /**
147
- * Reason that a prompt was blocked.
148
- * @public
149
- */
150
- var BlockReason;
151
- (function(BlockReason) {
152
- BlockReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED";
153
- BlockReason["SAFETY"] = "SAFETY";
154
- BlockReason["OTHER"] = "OTHER";
155
- })(BlockReason || (BlockReason = {}));
156
- /**
157
- * Reason that a candidate finished.
158
- * @public
159
- */
160
- var FinishReason;
161
- (function(FinishReason) {
162
- FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED";
163
- FinishReason["STOP"] = "STOP";
164
- FinishReason["MAX_TOKENS"] = "MAX_TOKENS";
165
- FinishReason["SAFETY"] = "SAFETY";
166
- FinishReason["RECITATION"] = "RECITATION";
167
- FinishReason["LANGUAGE"] = "LANGUAGE";
168
- FinishReason["BLOCKLIST"] = "BLOCKLIST";
169
- FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT";
170
- FinishReason["SPII"] = "SPII";
171
- FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL";
172
- FinishReason["OTHER"] = "OTHER";
173
- })(FinishReason || (FinishReason = {}));
174
- /**
175
- * Task type for embedding content.
176
- * @public
177
- */
178
- var TaskType;
179
- (function(TaskType) {
180
- TaskType["TASK_TYPE_UNSPECIFIED"] = "TASK_TYPE_UNSPECIFIED";
181
- TaskType["RETRIEVAL_QUERY"] = "RETRIEVAL_QUERY";
182
- TaskType["RETRIEVAL_DOCUMENT"] = "RETRIEVAL_DOCUMENT";
183
- TaskType["SEMANTIC_SIMILARITY"] = "SEMANTIC_SIMILARITY";
184
- TaskType["CLASSIFICATION"] = "CLASSIFICATION";
185
- TaskType["CLUSTERING"] = "CLUSTERING";
186
- })(TaskType || (TaskType = {}));
187
- /**
188
- * @public
189
- */
190
- var FunctionCallingMode;
191
- (function(FunctionCallingMode) {
192
- FunctionCallingMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
193
- FunctionCallingMode["AUTO"] = "AUTO";
194
- FunctionCallingMode["ANY"] = "ANY";
195
- FunctionCallingMode["NONE"] = "NONE";
196
- })(FunctionCallingMode || (FunctionCallingMode = {}));
197
- /**
198
- * The mode of the predictor to be used in dynamic retrieval.
199
- * @public
200
- */
201
- var DynamicRetrievalMode;
202
- (function(DynamicRetrievalMode) {
203
- DynamicRetrievalMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED";
204
- DynamicRetrievalMode["MODE_DYNAMIC"] = "MODE_DYNAMIC";
205
- })(DynamicRetrievalMode || (DynamicRetrievalMode = {}));
206
- /**
207
- * @license
208
- * Copyright 2024 Google LLC
209
- *
210
- * Licensed under the Apache License, Version 2.0 (the "License");
211
- * you may not use this file except in compliance with the License.
212
- * You may obtain a copy of the License at
213
- *
214
- * http://www.apache.org/licenses/LICENSE-2.0
215
- *
216
- * Unless required by applicable law or agreed to in writing, software
217
- * distributed under the License is distributed on an "AS IS" BASIS,
218
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
219
- * See the License for the specific language governing permissions and
220
- * limitations under the License.
221
- */
222
- /**
223
- * Basic error type for this SDK.
224
- * @public
225
- */
226
- var GoogleGenerativeAIError = class extends Error {
227
- constructor(message) {
228
- super(`[GoogleGenerativeAI Error]: ${message}`);
229
- }
230
- };
231
- /**
232
- * Errors in the contents of a response from the model. This includes parsing
233
- * errors, or responses including a safety block reason.
234
- * @public
235
- */
236
- var GoogleGenerativeAIResponseError = class extends GoogleGenerativeAIError {
237
- constructor(message, response) {
238
- super(message);
239
- this.response = response;
240
- }
241
- };
242
- /**
243
- * Error class covering HTTP errors when calling the server. Includes HTTP
244
- * status, statusText, and optional details, if provided in the server response.
245
- * @public
246
- */
247
- var GoogleGenerativeAIFetchError = class extends GoogleGenerativeAIError {
248
- constructor(message, status, statusText, errorDetails) {
249
- super(message);
250
- this.status = status;
251
- this.statusText = statusText;
252
- this.errorDetails = errorDetails;
253
- }
254
- };
255
- /**
256
- * Errors in the contents of a request originating from user input.
257
- * @public
258
- */
259
- var GoogleGenerativeAIRequestInputError = class extends GoogleGenerativeAIError {};
260
- /**
261
- * Error thrown when a request is aborted, either due to a timeout or
262
- * intentional cancellation by the user.
263
- * @public
264
- */
265
- var GoogleGenerativeAIAbortError = class extends GoogleGenerativeAIError {};
266
- /**
267
- * @license
268
- * Copyright 2024 Google LLC
269
- *
270
- * Licensed under the Apache License, Version 2.0 (the "License");
271
- * you may not use this file except in compliance with the License.
272
- * You may obtain a copy of the License at
273
- *
274
- * http://www.apache.org/licenses/LICENSE-2.0
275
- *
276
- * Unless required by applicable law or agreed to in writing, software
277
- * distributed under the License is distributed on an "AS IS" BASIS,
278
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
279
- * See the License for the specific language governing permissions and
280
- * limitations under the License.
281
- */
282
- const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com";
283
- const DEFAULT_API_VERSION = "v1beta";
284
- /**
285
- * We can't `require` package.json if this runs on web. We will use rollup to
286
- * swap in the version number here at build time.
287
- */
288
- const PACKAGE_VERSION = "0.24.1";
289
- const PACKAGE_LOG_HEADER = "genai-js";
290
- var Task;
291
- (function(Task) {
292
- Task["GENERATE_CONTENT"] = "generateContent";
293
- Task["STREAM_GENERATE_CONTENT"] = "streamGenerateContent";
294
- Task["COUNT_TOKENS"] = "countTokens";
295
- Task["EMBED_CONTENT"] = "embedContent";
296
- Task["BATCH_EMBED_CONTENTS"] = "batchEmbedContents";
297
- })(Task || (Task = {}));
298
- var RequestUrl = class {
299
- constructor(model, task, apiKey, stream, requestOptions) {
300
- this.model = model;
301
- this.task = task;
302
- this.apiKey = apiKey;
303
- this.stream = stream;
304
- this.requestOptions = requestOptions;
305
- }
306
- toString() {
307
- var _a, _b;
308
- const apiVersion = ((_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.apiVersion) || DEFAULT_API_VERSION;
309
- const baseUrl = ((_b = this.requestOptions) === null || _b === void 0 ? void 0 : _b.baseUrl) || DEFAULT_BASE_URL;
310
- let url = `${baseUrl}/${apiVersion}/${this.model}:${this.task}`;
311
- if (this.stream) {
312
- url += "?alt=sse";
313
- }
314
- return url;
315
- }
316
- };
317
- /**
318
- * Simple, but may become more complex if we add more versions to log.
319
- */
320
- function getClientHeaders(requestOptions) {
321
- const clientHeaders = [];
322
- if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.apiClient) {
323
- clientHeaders.push(requestOptions.apiClient);
324
- }
325
- clientHeaders.push(`${PACKAGE_LOG_HEADER}/${PACKAGE_VERSION}`);
326
- return clientHeaders.join(" ");
327
- }
328
- async function getHeaders(url) {
329
- var _a;
330
- const headers = new Headers();
331
- headers.append("Content-Type", "application/json");
332
- headers.append("x-goog-api-client", getClientHeaders(url.requestOptions));
333
- headers.append("x-goog-api-key", url.apiKey);
334
- let customHeaders = (_a = url.requestOptions) === null || _a === void 0 ? void 0 : _a.customHeaders;
335
- if (customHeaders) {
336
- if (!(customHeaders instanceof Headers)) {
337
- try {
338
- customHeaders = new Headers(customHeaders);
339
- } catch (e) {
340
- throw new GoogleGenerativeAIRequestInputError(`unable to convert customHeaders value ${JSON.stringify(customHeaders)} to Headers: ${e.message}`);
341
- }
342
- }
343
- for (const [headerName, headerValue] of customHeaders.entries()) {
344
- if (headerName === "x-goog-api-key") {
345
- throw new GoogleGenerativeAIRequestInputError(`Cannot set reserved header name ${headerName}`);
346
- } else if (headerName === "x-goog-api-client") {
347
- throw new GoogleGenerativeAIRequestInputError(`Header name ${headerName} can only be set using the apiClient field`);
348
- }
349
- headers.append(headerName, headerValue);
350
- }
351
- }
352
- return headers;
353
- }
354
- async function constructModelRequest(model, task, apiKey, stream, body, requestOptions) {
355
- const url = new RequestUrl(model, task, apiKey, stream, requestOptions);
356
- return {
357
- url: url.toString(),
358
- fetchOptions: Object.assign(Object.assign({}, buildFetchOptions(requestOptions)), {
359
- method: "POST",
360
- headers: await getHeaders(url),
361
- body
362
- })
363
- };
364
- }
365
- async function makeModelRequest(model, task, apiKey, stream, body, requestOptions = {}, fetchFn = fetch) {
366
- const { url, fetchOptions } = await constructModelRequest(model, task, apiKey, stream, body, requestOptions);
367
- return makeRequest(url, fetchOptions, fetchFn);
368
- }
369
- async function makeRequest(url, fetchOptions, fetchFn = fetch) {
370
- let response;
371
- try {
372
- response = await fetchFn(url, fetchOptions);
373
- } catch (e) {
374
- handleResponseError(e, url);
375
- }
376
- if (!response.ok) {
377
- await handleResponseNotOk(response, url);
378
- }
379
- return response;
380
- }
381
- function handleResponseError(e, url) {
382
- let err = e;
383
- if (err.name === "AbortError") {
384
- err = new GoogleGenerativeAIAbortError(`Request aborted when fetching ${url.toString()}: ${e.message}`);
385
- err.stack = e.stack;
386
- } else if (!(e instanceof GoogleGenerativeAIFetchError || e instanceof GoogleGenerativeAIRequestInputError)) {
387
- err = new GoogleGenerativeAIError(`Error fetching from ${url.toString()}: ${e.message}`);
388
- err.stack = e.stack;
389
- }
390
- throw err;
391
- }
392
- async function handleResponseNotOk(response, url) {
393
- let message = "";
394
- let errorDetails;
395
- try {
396
- const json = await response.json();
397
- message = json.error.message;
398
- if (json.error.details) {
399
- message += ` ${JSON.stringify(json.error.details)}`;
400
- errorDetails = json.error.details;
401
- }
402
- } catch (e) {}
403
- throw new GoogleGenerativeAIFetchError(`Error fetching from ${url.toString()}: [${response.status} ${response.statusText}] ${message}`, response.status, response.statusText, errorDetails);
404
- }
405
- /**
406
- * Generates the request options to be passed to the fetch API.
407
- * @param requestOptions - The user-defined request options.
408
- * @returns The generated request options.
409
- */
410
- function buildFetchOptions(requestOptions) {
411
- const fetchOptions = {};
412
- if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) !== undefined || (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {
413
- const controller = new AbortController();
414
- if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) {
415
- setTimeout(() => controller.abort(), requestOptions.timeout);
416
- }
417
- if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) {
418
- requestOptions.signal.addEventListener("abort", () => {
419
- controller.abort();
420
- });
421
- }
422
- fetchOptions.signal = controller.signal;
423
- }
424
- return fetchOptions;
425
- }
426
- /**
427
- * @license
428
- * Copyright 2024 Google LLC
429
- *
430
- * Licensed under the Apache License, Version 2.0 (the "License");
431
- * you may not use this file except in compliance with the License.
432
- * You may obtain a copy of the License at
433
- *
434
- * http://www.apache.org/licenses/LICENSE-2.0
435
- *
436
- * Unless required by applicable law or agreed to in writing, software
437
- * distributed under the License is distributed on an "AS IS" BASIS,
438
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
439
- * See the License for the specific language governing permissions and
440
- * limitations under the License.
441
- */
442
- /**
443
- * Adds convenience helper methods to a response object, including stream
444
- * chunks (as long as each chunk is a complete GenerateContentResponse JSON).
445
- */
446
- function addHelpers(response) {
447
- response.text = () => {
448
- if (response.candidates && response.candidates.length > 0) {
449
- if (response.candidates.length > 1) {
450
- 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.`);
451
- }
452
- if (hadBadFinishReason(response.candidates[0])) {
453
- throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);
454
- }
455
- return getText(response);
456
- } else if (response.promptFeedback) {
457
- throw new GoogleGenerativeAIResponseError(`Text not available. ${formatBlockErrorMessage(response)}`, response);
458
- }
459
- return "";
460
- };
461
- /**
462
- * TODO: remove at next major version
463
- */
464
- response.functionCall = () => {
465
- if (response.candidates && response.candidates.length > 0) {
466
- if (response.candidates.length > 1) {
467
- 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.`);
468
- }
469
- if (hadBadFinishReason(response.candidates[0])) {
470
- throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);
471
- }
472
- console.warn(`response.functionCall() is deprecated. ` + `Use response.functionCalls() instead.`);
473
- return getFunctionCalls(response)[0];
474
- } else if (response.promptFeedback) {
475
- throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response);
476
- }
477
- return undefined;
478
- };
479
- response.functionCalls = () => {
480
- if (response.candidates && response.candidates.length > 0) {
481
- if (response.candidates.length > 1) {
482
- 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.`);
483
- }
484
- if (hadBadFinishReason(response.candidates[0])) {
485
- throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);
486
- }
487
- return getFunctionCalls(response);
488
- } else if (response.promptFeedback) {
489
- throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response);
490
- }
491
- return undefined;
492
- };
493
- return response;
494
- }
495
- /**
496
- * Returns all text found in all parts of first candidate.
497
- */
498
- function getText(response) {
499
- var _a, _b, _c, _d;
500
- const textStrings = [];
501
- if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) {
502
- 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) {
503
- if (part.text) {
504
- textStrings.push(part.text);
505
- }
506
- if (part.executableCode) {
507
- textStrings.push("\n```" + part.executableCode.language + "\n" + part.executableCode.code + "\n```\n");
508
- }
509
- if (part.codeExecutionResult) {
510
- textStrings.push("\n```\n" + part.codeExecutionResult.output + "\n```\n");
511
- }
512
- }
513
- }
514
- if (textStrings.length > 0) {
515
- return textStrings.join("");
516
- } else {
517
- return "";
518
- }
519
- }
520
- /**
521
- * Returns functionCall of first candidate.
522
- */
523
- function getFunctionCalls(response) {
524
- var _a, _b, _c, _d;
525
- const functionCalls = [];
526
- if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) {
527
- 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) {
528
- if (part.functionCall) {
529
- functionCalls.push(part.functionCall);
530
- }
531
- }
532
- }
533
- if (functionCalls.length > 0) {
534
- return functionCalls;
535
- } else {
536
- return undefined;
537
- }
538
- }
539
- const badFinishReasons = [
540
- FinishReason.RECITATION,
541
- FinishReason.SAFETY,
542
- FinishReason.LANGUAGE
543
- ];
544
- function hadBadFinishReason(candidate) {
545
- return !!candidate.finishReason && badFinishReasons.includes(candidate.finishReason);
546
- }
547
- function formatBlockErrorMessage(response) {
548
- var _a, _b, _c;
549
- let message = "";
550
- if ((!response.candidates || response.candidates.length === 0) && response.promptFeedback) {
551
- message += "Response was blocked";
552
- if ((_a = response.promptFeedback) === null || _a === void 0 ? void 0 : _a.blockReason) {
553
- message += ` due to ${response.promptFeedback.blockReason}`;
554
- }
555
- if ((_b = response.promptFeedback) === null || _b === void 0 ? void 0 : _b.blockReasonMessage) {
556
- message += `: ${response.promptFeedback.blockReasonMessage}`;
557
- }
558
- } else if ((_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0]) {
559
- const firstCandidate = response.candidates[0];
560
- if (hadBadFinishReason(firstCandidate)) {
561
- message += `Candidate was blocked due to ${firstCandidate.finishReason}`;
562
- if (firstCandidate.finishMessage) {
563
- message += `: ${firstCandidate.finishMessage}`;
564
- }
565
- }
566
- }
567
- return message;
568
- }
569
- /******************************************************************************
570
- Copyright (c) Microsoft Corporation.
571
-
572
- Permission to use, copy, modify, and/or distribute this software for any
573
- purpose with or without fee is hereby granted.
574
-
575
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
576
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
577
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
578
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
579
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
580
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
581
- PERFORMANCE OF THIS SOFTWARE.
582
- ***************************************************************************** */
583
- function __await(v) {
584
- return this instanceof __await ? (this.v = v, this) : new __await(v);
585
- }
586
- function __asyncGenerator(thisArg, _arguments, generator) {
587
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
588
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
589
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
590
- return this;
591
- }, i;
592
- function verb(n) {
593
- if (g[n]) i[n] = function(v) {
594
- return new Promise(function(a, b) {
595
- q.push([
596
- n,
597
- v,
598
- a,
599
- b
600
- ]) > 1 || resume(n, v);
601
- });
602
- };
603
- }
604
- function resume(n, v) {
605
- try {
606
- step(g[n](v));
607
- } catch (e) {
608
- settle(q[0][3], e);
609
- }
610
- }
611
- function step(r) {
612
- r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
613
- }
614
- function fulfill(value) {
615
- resume("next", value);
616
- }
617
- function reject(value) {
618
- resume("throw", value);
619
- }
620
- function settle(f, v) {
621
- if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
622
- }
623
- }
624
- typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
625
- var e = new Error(message);
626
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
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
- const responseLineRE = /^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;
645
- /**
646
- * Process a response.body stream from the backend and return an
647
- * iterator that provides one complete GenerateContentResponse at a time
648
- * and a promise that resolves with a single aggregated
649
- * GenerateContentResponse.
650
- *
651
- * @param response - Response from a fetch call
652
- */
653
- function processStream(response) {
654
- const inputStream = response.body.pipeThrough(new TextDecoderStream("utf8", { fatal: true }));
655
- const responseStream = getResponseStream(inputStream);
656
- const [stream1, stream2] = responseStream.tee();
657
- return {
658
- stream: generateResponseSequence(stream1),
659
- response: getResponsePromise(stream2)
660
- };
661
- }
662
- async function getResponsePromise(stream) {
663
- const allResponses = [];
664
- const reader = stream.getReader();
665
- while (true) {
666
- const { done, value } = await reader.read();
667
- if (done) {
668
- return addHelpers(aggregateResponses(allResponses));
669
- }
670
- allResponses.push(value);
671
- }
672
- }
673
- function generateResponseSequence(stream) {
674
- return __asyncGenerator(this, arguments, function* generateResponseSequence_1() {
675
- const reader = stream.getReader();
676
- while (true) {
677
- const { value, done } = yield __await(reader.read());
678
- if (done) {
679
- break;
680
- }
681
- yield yield __await(addHelpers(value));
682
- }
683
- });
684
- }
685
- /**
686
- * Reads a raw stream from the fetch response and join incomplete
687
- * chunks, returning a new stream that provides a single complete
688
- * GenerateContentResponse in each iteration.
689
- */
690
- function getResponseStream(inputStream) {
691
- const reader = inputStream.getReader();
692
- const stream = new ReadableStream({ start(controller) {
693
- let currentText = "";
694
- return pump();
695
- function pump() {
696
- return reader.read().then(({ value, done }) => {
697
- if (done) {
698
- if (currentText.trim()) {
699
- controller.error(new GoogleGenerativeAIError("Failed to parse stream"));
700
- return;
701
- }
702
- controller.close();
703
- return;
704
- }
705
- currentText += value;
706
- let match = currentText.match(responseLineRE);
707
- let parsedResponse;
708
- while (match) {
709
- try {
710
- parsedResponse = JSON.parse(match[1]);
711
- } catch (e) {
712
- controller.error(new GoogleGenerativeAIError(`Error parsing JSON response: "${match[1]}"`));
713
- return;
714
- }
715
- controller.enqueue(parsedResponse);
716
- currentText = currentText.substring(match[0].length);
717
- match = currentText.match(responseLineRE);
718
- }
719
- return pump();
720
- }).catch((e) => {
721
- let err = e;
722
- err.stack = e.stack;
723
- if (err.name === "AbortError") {
724
- err = new GoogleGenerativeAIAbortError("Request aborted when reading from the stream");
725
- } else {
726
- err = new GoogleGenerativeAIError("Error reading from the stream");
727
- }
728
- throw err;
729
- });
730
- }
731
- } });
732
- return stream;
733
- }
734
- /**
735
- * Aggregates an array of `GenerateContentResponse`s into a single
736
- * GenerateContentResponse.
737
- */
738
- function aggregateResponses(responses) {
739
- const lastResponse = responses[responses.length - 1];
740
- const aggregatedResponse = { promptFeedback: lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.promptFeedback };
741
- for (const response of responses) {
742
- if (response.candidates) {
743
- let candidateIndex = 0;
744
- for (const candidate of response.candidates) {
745
- if (!aggregatedResponse.candidates) {
746
- aggregatedResponse.candidates = [];
747
- }
748
- if (!aggregatedResponse.candidates[candidateIndex]) {
749
- aggregatedResponse.candidates[candidateIndex] = { index: candidateIndex };
750
- }
751
- aggregatedResponse.candidates[candidateIndex].citationMetadata = candidate.citationMetadata;
752
- aggregatedResponse.candidates[candidateIndex].groundingMetadata = candidate.groundingMetadata;
753
- aggregatedResponse.candidates[candidateIndex].finishReason = candidate.finishReason;
754
- aggregatedResponse.candidates[candidateIndex].finishMessage = candidate.finishMessage;
755
- aggregatedResponse.candidates[candidateIndex].safetyRatings = candidate.safetyRatings;
756
- /**
757
- * Candidates should always have content and parts, but this handles
758
- * possible malformed responses.
759
- */
760
- if (candidate.content && candidate.content.parts) {
761
- if (!aggregatedResponse.candidates[candidateIndex].content) {
762
- aggregatedResponse.candidates[candidateIndex].content = {
763
- role: candidate.content.role || "user",
764
- parts: []
765
- };
766
- }
767
- const newPart = {};
768
- for (const part of candidate.content.parts) {
769
- if (part.text) {
770
- newPart.text = part.text;
771
- }
772
- if (part.functionCall) {
773
- newPart.functionCall = part.functionCall;
774
- }
775
- if (part.executableCode) {
776
- newPart.executableCode = part.executableCode;
777
- }
778
- if (part.codeExecutionResult) {
779
- newPart.codeExecutionResult = part.codeExecutionResult;
780
- }
781
- if (Object.keys(newPart).length === 0) {
782
- newPart.text = "";
783
- }
784
- aggregatedResponse.candidates[candidateIndex].content.parts.push(newPart);
785
- }
786
- }
787
- }
788
- candidateIndex++;
789
- }
790
- if (response.usageMetadata) {
791
- aggregatedResponse.usageMetadata = response.usageMetadata;
792
- }
793
- }
794
- return aggregatedResponse;
795
- }
796
- /**
797
- * @license
798
- * Copyright 2024 Google LLC
799
- *
800
- * Licensed under the Apache License, Version 2.0 (the "License");
801
- * you may not use this file except in compliance with the License.
802
- * You may obtain a copy of the License at
803
- *
804
- * http://www.apache.org/licenses/LICENSE-2.0
805
- *
806
- * Unless required by applicable law or agreed to in writing, software
807
- * distributed under the License is distributed on an "AS IS" BASIS,
808
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
809
- * See the License for the specific language governing permissions and
810
- * limitations under the License.
811
- */
812
- async function generateContentStream(apiKey, model, params, requestOptions) {
813
- const response = await makeModelRequest(model, Task.STREAM_GENERATE_CONTENT, apiKey, true, JSON.stringify(params), requestOptions);
814
- return processStream(response);
815
- }
816
- async function generateContent(apiKey, model, params, requestOptions) {
817
- const response = await makeModelRequest(model, Task.GENERATE_CONTENT, apiKey, false, JSON.stringify(params), requestOptions);
818
- const responseJson = await response.json();
819
- const enhancedResponse = addHelpers(responseJson);
820
- return { response: enhancedResponse };
821
- }
822
- /**
823
- * @license
824
- * Copyright 2024 Google LLC
825
- *
826
- * Licensed under the Apache License, Version 2.0 (the "License");
827
- * you may not use this file except in compliance with the License.
828
- * You may obtain a copy of the License at
829
- *
830
- * http://www.apache.org/licenses/LICENSE-2.0
831
- *
832
- * Unless required by applicable law or agreed to in writing, software
833
- * distributed under the License is distributed on an "AS IS" BASIS,
834
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
835
- * See the License for the specific language governing permissions and
836
- * limitations under the License.
837
- */
838
- function formatSystemInstruction(input) {
839
- if (input == null) {
840
- return undefined;
841
- } else if (typeof input === "string") {
842
- return {
843
- role: "system",
844
- parts: [{ text: input }]
845
- };
846
- } else if (input.text) {
847
- return {
848
- role: "system",
849
- parts: [input]
850
- };
851
- } else if (input.parts) {
852
- if (!input.role) {
853
- return {
854
- role: "system",
855
- parts: input.parts
856
- };
857
- } else {
858
- return input;
859
- }
860
- }
861
- }
862
- function formatNewContent(request) {
863
- let newParts = [];
864
- if (typeof request === "string") {
865
- newParts = [{ text: request }];
866
- } else {
867
- for (const partOrString of request) {
868
- if (typeof partOrString === "string") {
869
- newParts.push({ text: partOrString });
870
- } else {
871
- newParts.push(partOrString);
872
- }
873
- }
874
- }
875
- return assignRoleToPartsAndValidateSendMessageRequest(newParts);
876
- }
877
- /**
878
- * When multiple Part types (i.e. FunctionResponsePart and TextPart) are
879
- * passed in a single Part array, we may need to assign different roles to each
880
- * part. Currently only FunctionResponsePart requires a role other than 'user'.
881
- * @private
882
- * @param parts Array of parts to pass to the model
883
- * @returns Array of content items
884
- */
885
- function assignRoleToPartsAndValidateSendMessageRequest(parts) {
886
- const userContent = {
887
- role: "user",
888
- parts: []
889
- };
890
- const functionContent = {
891
- role: "function",
892
- parts: []
893
- };
894
- let hasUserContent = false;
895
- let hasFunctionContent = false;
896
- for (const part of parts) {
897
- if ("functionResponse" in part) {
898
- functionContent.parts.push(part);
899
- hasFunctionContent = true;
900
- } else {
901
- userContent.parts.push(part);
902
- hasUserContent = true;
903
- }
904
- }
905
- if (hasUserContent && hasFunctionContent) {
906
- throw new GoogleGenerativeAIError("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");
907
- }
908
- if (!hasUserContent && !hasFunctionContent) {
909
- throw new GoogleGenerativeAIError("No content is provided for sending chat message.");
910
- }
911
- if (hasUserContent) {
912
- return userContent;
913
- }
914
- return functionContent;
915
- }
916
- function formatCountTokensInput(params, modelParams) {
917
- var _a;
918
- let formattedGenerateContentRequest = {
919
- model: modelParams === null || modelParams === void 0 ? void 0 : modelParams.model,
920
- generationConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.generationConfig,
921
- safetySettings: modelParams === null || modelParams === void 0 ? void 0 : modelParams.safetySettings,
922
- tools: modelParams === null || modelParams === void 0 ? void 0 : modelParams.tools,
923
- toolConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.toolConfig,
924
- systemInstruction: modelParams === null || modelParams === void 0 ? void 0 : modelParams.systemInstruction,
925
- cachedContent: (_a = modelParams === null || modelParams === void 0 ? void 0 : modelParams.cachedContent) === null || _a === void 0 ? void 0 : _a.name,
926
- contents: []
927
- };
928
- const containsGenerateContentRequest = params.generateContentRequest != null;
929
- if (params.contents) {
930
- if (containsGenerateContentRequest) {
931
- throw new GoogleGenerativeAIRequestInputError("CountTokensRequest must have one of contents or generateContentRequest, not both.");
932
- }
933
- formattedGenerateContentRequest.contents = params.contents;
934
- } else if (containsGenerateContentRequest) {
935
- formattedGenerateContentRequest = Object.assign(Object.assign({}, formattedGenerateContentRequest), params.generateContentRequest);
936
- } else {
937
- const content = formatNewContent(params);
938
- formattedGenerateContentRequest.contents = [content];
939
- }
940
- return { generateContentRequest: formattedGenerateContentRequest };
941
- }
942
- function formatGenerateContentInput(params) {
943
- let formattedRequest;
944
- if (params.contents) {
945
- formattedRequest = params;
946
- } else {
947
- const content = formatNewContent(params);
948
- formattedRequest = { contents: [content] };
949
- }
950
- if (params.systemInstruction) {
951
- formattedRequest.systemInstruction = formatSystemInstruction(params.systemInstruction);
952
- }
953
- return formattedRequest;
954
- }
955
- function formatEmbedContentInput(params) {
956
- if (typeof params === "string" || Array.isArray(params)) {
957
- const content = formatNewContent(params);
958
- return { content };
959
- }
960
- return params;
961
- }
962
- /**
963
- * @license
964
- * Copyright 2024 Google LLC
965
- *
966
- * Licensed under the Apache License, Version 2.0 (the "License");
967
- * you may not use this file except in compliance with the License.
968
- * You may obtain a copy of the License at
969
- *
970
- * http://www.apache.org/licenses/LICENSE-2.0
971
- *
972
- * Unless required by applicable law or agreed to in writing, software
973
- * distributed under the License is distributed on an "AS IS" BASIS,
974
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
975
- * See the License for the specific language governing permissions and
976
- * limitations under the License.
977
- */
978
- const VALID_PART_FIELDS = [
979
- "text",
980
- "inlineData",
981
- "functionCall",
982
- "functionResponse",
983
- "executableCode",
984
- "codeExecutionResult"
985
- ];
986
- const VALID_PARTS_PER_ROLE = {
987
- user: ["text", "inlineData"],
988
- function: ["functionResponse"],
989
- model: [
990
- "text",
991
- "functionCall",
992
- "executableCode",
993
- "codeExecutionResult"
994
- ],
995
- system: ["text"]
996
- };
997
- function validateChatHistory(history) {
998
- let prevContent = false;
999
- for (const currContent of history) {
1000
- const { role, parts } = currContent;
1001
- if (!prevContent && role !== "user") {
1002
- throw new GoogleGenerativeAIError(`First content should be with role 'user', got ${role}`);
1003
- }
1004
- if (!POSSIBLE_ROLES.includes(role)) {
1005
- throw new GoogleGenerativeAIError(`Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(POSSIBLE_ROLES)}`);
1006
- }
1007
- if (!Array.isArray(parts)) {
1008
- throw new GoogleGenerativeAIError("Content should have 'parts' property with an array of Parts");
1009
- }
1010
- if (parts.length === 0) {
1011
- throw new GoogleGenerativeAIError("Each Content should have at least one part");
1012
- }
1013
- const countFields = {
1014
- text: 0,
1015
- inlineData: 0,
1016
- functionCall: 0,
1017
- functionResponse: 0,
1018
- fileData: 0,
1019
- executableCode: 0,
1020
- codeExecutionResult: 0
1021
- };
1022
- for (const part of parts) {
1023
- for (const key of VALID_PART_FIELDS) {
1024
- if (key in part) {
1025
- countFields[key] += 1;
1026
- }
1027
- }
1028
- }
1029
- const validParts = VALID_PARTS_PER_ROLE[role];
1030
- for (const key of VALID_PART_FIELDS) {
1031
- if (!validParts.includes(key) && countFields[key] > 0) {
1032
- throw new GoogleGenerativeAIError(`Content with role '${role}' can't contain '${key}' part`);
1033
- }
1034
- }
1035
- prevContent = true;
1036
- }
1037
- }
1038
- /**
1039
- * Returns true if the response is valid (could be appended to the history), flase otherwise.
1040
- */
1041
- function isValidResponse(response) {
1042
- var _a;
1043
- if (response.candidates === undefined || response.candidates.length === 0) {
1044
- return false;
1045
- }
1046
- const content = (_a = response.candidates[0]) === null || _a === void 0 ? void 0 : _a.content;
1047
- if (content === undefined) {
1048
- return false;
1049
- }
1050
- if (content.parts === undefined || content.parts.length === 0) {
1051
- return false;
1052
- }
1053
- for (const part of content.parts) {
1054
- if (part === undefined || Object.keys(part).length === 0) {
1055
- return false;
1056
- }
1057
- if (part.text !== undefined && part.text === "") {
1058
- return false;
1059
- }
1060
- }
1061
- return true;
1062
- }
1063
- /**
1064
- * @license
1065
- * Copyright 2024 Google LLC
1066
- *
1067
- * Licensed under the Apache License, Version 2.0 (the "License");
1068
- * you may not use this file except in compliance with the License.
1069
- * You may obtain a copy of the License at
1070
- *
1071
- * http://www.apache.org/licenses/LICENSE-2.0
1072
- *
1073
- * Unless required by applicable law or agreed to in writing, software
1074
- * distributed under the License is distributed on an "AS IS" BASIS,
1075
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1076
- * See the License for the specific language governing permissions and
1077
- * limitations under the License.
1078
- */
1079
- /**
1080
- * Do not log a message for this error.
1081
- */
1082
- const SILENT_ERROR = "SILENT_ERROR";
1083
- /**
1084
- * ChatSession class that enables sending chat messages and stores
1085
- * history of sent and received messages so far.
1086
- *
1087
- * @public
1088
- */
1089
- var ChatSession = class {
1090
- constructor(apiKey, model, params, _requestOptions = {}) {
1091
- this.model = model;
1092
- this.params = params;
1093
- this._requestOptions = _requestOptions;
1094
- this._history = [];
1095
- this._sendPromise = Promise.resolve();
1096
- this._apiKey = apiKey;
1097
- if (params === null || params === void 0 ? void 0 : params.history) {
1098
- validateChatHistory(params.history);
1099
- this._history = params.history;
1100
- }
1101
- }
1102
- /**
1103
- * Gets the chat history so far. Blocked prompts are not added to history.
1104
- * Blocked candidates are not added to history, nor are the prompts that
1105
- * generated them.
1106
- */
1107
- async getHistory() {
1108
- await this._sendPromise;
1109
- return this._history;
1110
- }
1111
- /**
1112
- * Sends a chat message and receives a non-streaming
1113
- * {@link GenerateContentResult}.
1114
- *
1115
- * Fields set in the optional {@link SingleRequestOptions} parameter will
1116
- * take precedence over the {@link RequestOptions} values provided to
1117
- * {@link GoogleGenerativeAI.getGenerativeModel }.
1118
- */
1119
- async sendMessage(request, requestOptions = {}) {
1120
- var _a, _b, _c, _d, _e, _f;
1121
- await this._sendPromise;
1122
- const newContent = formatNewContent(request);
1123
- const generateContentRequest = {
1124
- safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings,
1125
- generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig,
1126
- tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools,
1127
- toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig,
1128
- systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction,
1129
- cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent,
1130
- contents: [...this._history, newContent]
1131
- };
1132
- const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1133
- let finalResult;
1134
- this._sendPromise = this._sendPromise.then(() => generateContent(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions)).then((result) => {
1135
- var _a;
1136
- if (isValidResponse(result.response)) {
1137
- this._history.push(newContent);
1138
- const responseContent = Object.assign({
1139
- parts: [],
1140
- role: "model"
1141
- }, (_a = result.response.candidates) === null || _a === void 0 ? void 0 : _a[0].content);
1142
- this._history.push(responseContent);
1143
- } else {
1144
- const blockErrorMessage = formatBlockErrorMessage(result.response);
1145
- if (blockErrorMessage) {
1146
- console.warn(`sendMessage() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);
1147
- }
1148
- }
1149
- finalResult = result;
1150
- }).catch((e) => {
1151
- this._sendPromise = Promise.resolve();
1152
- throw e;
1153
- });
1154
- await this._sendPromise;
1155
- return finalResult;
1156
- }
1157
- /**
1158
- * Sends a chat message and receives the response as a
1159
- * {@link GenerateContentStreamResult} containing an iterable stream
1160
- * and a response promise.
1161
- *
1162
- * Fields set in the optional {@link SingleRequestOptions} parameter will
1163
- * take precedence over the {@link RequestOptions} values provided to
1164
- * {@link GoogleGenerativeAI.getGenerativeModel }.
1165
- */
1166
- async sendMessageStream(request, requestOptions = {}) {
1167
- var _a, _b, _c, _d, _e, _f;
1168
- await this._sendPromise;
1169
- const newContent = formatNewContent(request);
1170
- const generateContentRequest = {
1171
- safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings,
1172
- generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig,
1173
- tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools,
1174
- toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig,
1175
- systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction,
1176
- cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent,
1177
- contents: [...this._history, newContent]
1178
- };
1179
- const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1180
- const streamPromise = generateContentStream(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions);
1181
- this._sendPromise = this._sendPromise.then(() => streamPromise).catch((_ignored) => {
1182
- throw new Error(SILENT_ERROR);
1183
- }).then((streamResult) => streamResult.response).then((response) => {
1184
- if (isValidResponse(response)) {
1185
- this._history.push(newContent);
1186
- const responseContent = Object.assign({}, response.candidates[0].content);
1187
- if (!responseContent.role) {
1188
- responseContent.role = "model";
1189
- }
1190
- this._history.push(responseContent);
1191
- } else {
1192
- const blockErrorMessage = formatBlockErrorMessage(response);
1193
- if (blockErrorMessage) {
1194
- console.warn(`sendMessageStream() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`);
1195
- }
1196
- }
1197
- }).catch((e) => {
1198
- if (e.message !== SILENT_ERROR) {
1199
- console.error(e);
1200
- }
1201
- });
1202
- return streamPromise;
1203
- }
1204
- };
1205
- /**
1206
- * @license
1207
- * Copyright 2024 Google LLC
1208
- *
1209
- * Licensed under the Apache License, Version 2.0 (the "License");
1210
- * you may not use this file except in compliance with the License.
1211
- * You may obtain a copy of the License at
1212
- *
1213
- * http://www.apache.org/licenses/LICENSE-2.0
1214
- *
1215
- * Unless required by applicable law or agreed to in writing, software
1216
- * distributed under the License is distributed on an "AS IS" BASIS,
1217
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1218
- * See the License for the specific language governing permissions and
1219
- * limitations under the License.
1220
- */
1221
- async function countTokens(apiKey, model, params, singleRequestOptions) {
1222
- const response = await makeModelRequest(model, Task.COUNT_TOKENS, apiKey, false, JSON.stringify(params), singleRequestOptions);
1223
- return response.json();
1224
- }
1225
- /**
1226
- * @license
1227
- * Copyright 2024 Google LLC
1228
- *
1229
- * Licensed under the Apache License, Version 2.0 (the "License");
1230
- * you may not use this file except in compliance with the License.
1231
- * You may obtain a copy of the License at
1232
- *
1233
- * http://www.apache.org/licenses/LICENSE-2.0
1234
- *
1235
- * Unless required by applicable law or agreed to in writing, software
1236
- * distributed under the License is distributed on an "AS IS" BASIS,
1237
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1238
- * See the License for the specific language governing permissions and
1239
- * limitations under the License.
1240
- */
1241
- async function embedContent(apiKey, model, params, requestOptions) {
1242
- const response = await makeModelRequest(model, Task.EMBED_CONTENT, apiKey, false, JSON.stringify(params), requestOptions);
1243
- return response.json();
1244
- }
1245
- async function batchEmbedContents(apiKey, model, params, requestOptions) {
1246
- const requestsWithModel = params.requests.map((request) => {
1247
- return Object.assign(Object.assign({}, request), { model });
1248
- });
1249
- const response = await makeModelRequest(model, Task.BATCH_EMBED_CONTENTS, apiKey, false, JSON.stringify({ requests: requestsWithModel }), requestOptions);
1250
- return response.json();
1251
- }
1252
- /**
1253
- * @license
1254
- * Copyright 2024 Google LLC
1255
- *
1256
- * Licensed under the Apache License, Version 2.0 (the "License");
1257
- * you may not use this file except in compliance with the License.
1258
- * You may obtain a copy of the License at
1259
- *
1260
- * http://www.apache.org/licenses/LICENSE-2.0
1261
- *
1262
- * Unless required by applicable law or agreed to in writing, software
1263
- * distributed under the License is distributed on an "AS IS" BASIS,
1264
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1265
- * See the License for the specific language governing permissions and
1266
- * limitations under the License.
1267
- */
1268
- /**
1269
- * Class for generative model APIs.
1270
- * @public
1271
- */
1272
- var GenerativeModel = class {
1273
- constructor(apiKey, modelParams, _requestOptions = {}) {
1274
- this.apiKey = apiKey;
1275
- this._requestOptions = _requestOptions;
1276
- if (modelParams.model.includes("/")) {
1277
- this.model = modelParams.model;
1278
- } else {
1279
- this.model = `models/${modelParams.model}`;
1280
- }
1281
- this.generationConfig = modelParams.generationConfig || {};
1282
- this.safetySettings = modelParams.safetySettings || [];
1283
- this.tools = modelParams.tools;
1284
- this.toolConfig = modelParams.toolConfig;
1285
- this.systemInstruction = formatSystemInstruction(modelParams.systemInstruction);
1286
- this.cachedContent = modelParams.cachedContent;
1287
- }
1288
- /**
1289
- * Makes a single non-streaming call to the model
1290
- * and returns an object containing a single {@link GenerateContentResponse}.
1291
- *
1292
- * Fields set in the optional {@link SingleRequestOptions} parameter will
1293
- * take precedence over the {@link RequestOptions} values provided to
1294
- * {@link GoogleGenerativeAI.getGenerativeModel }.
1295
- */
1296
- async generateContent(request, requestOptions = {}) {
1297
- var _a;
1298
- const formattedParams = formatGenerateContentInput(request);
1299
- const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1300
- return generateContent(this.apiKey, this.model, Object.assign({
1301
- generationConfig: this.generationConfig,
1302
- safetySettings: this.safetySettings,
1303
- tools: this.tools,
1304
- toolConfig: this.toolConfig,
1305
- systemInstruction: this.systemInstruction,
1306
- cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name
1307
- }, formattedParams), generativeModelRequestOptions);
1308
- }
1309
- /**
1310
- * Makes a single streaming call to the model and returns an object
1311
- * containing an iterable stream that iterates over all chunks in the
1312
- * streaming response as well as a promise that returns the final
1313
- * aggregated response.
1314
- *
1315
- * Fields set in the optional {@link SingleRequestOptions} parameter will
1316
- * take precedence over the {@link RequestOptions} values provided to
1317
- * {@link GoogleGenerativeAI.getGenerativeModel }.
1318
- */
1319
- async generateContentStream(request, requestOptions = {}) {
1320
- var _a;
1321
- const formattedParams = formatGenerateContentInput(request);
1322
- const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1323
- return generateContentStream(this.apiKey, this.model, Object.assign({
1324
- generationConfig: this.generationConfig,
1325
- safetySettings: this.safetySettings,
1326
- tools: this.tools,
1327
- toolConfig: this.toolConfig,
1328
- systemInstruction: this.systemInstruction,
1329
- cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name
1330
- }, formattedParams), generativeModelRequestOptions);
1331
- }
1332
- /**
1333
- * Gets a new {@link ChatSession} instance which can be used for
1334
- * multi-turn chats.
1335
- */
1336
- startChat(startChatParams) {
1337
- var _a;
1338
- return new ChatSession(this.apiKey, this.model, Object.assign({
1339
- generationConfig: this.generationConfig,
1340
- safetySettings: this.safetySettings,
1341
- tools: this.tools,
1342
- toolConfig: this.toolConfig,
1343
- systemInstruction: this.systemInstruction,
1344
- cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name
1345
- }, startChatParams), this._requestOptions);
1346
- }
1347
- /**
1348
- * Counts the tokens in the provided request.
1349
- *
1350
- * Fields set in the optional {@link SingleRequestOptions} parameter will
1351
- * take precedence over the {@link RequestOptions} values provided to
1352
- * {@link GoogleGenerativeAI.getGenerativeModel }.
1353
- */
1354
- async countTokens(request, requestOptions = {}) {
1355
- const formattedParams = formatCountTokensInput(request, {
1356
- model: this.model,
1357
- generationConfig: this.generationConfig,
1358
- safetySettings: this.safetySettings,
1359
- tools: this.tools,
1360
- toolConfig: this.toolConfig,
1361
- systemInstruction: this.systemInstruction,
1362
- cachedContent: this.cachedContent
1363
- });
1364
- const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1365
- return countTokens(this.apiKey, this.model, formattedParams, generativeModelRequestOptions);
1366
- }
1367
- /**
1368
- * Embeds the provided content.
1369
- *
1370
- * Fields set in the optional {@link SingleRequestOptions} parameter will
1371
- * take precedence over the {@link RequestOptions} values provided to
1372
- * {@link GoogleGenerativeAI.getGenerativeModel }.
1373
- */
1374
- async embedContent(request, requestOptions = {}) {
1375
- const formattedParams = formatEmbedContentInput(request);
1376
- const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1377
- return embedContent(this.apiKey, this.model, formattedParams, generativeModelRequestOptions);
1378
- }
1379
- /**
1380
- * Embeds an array of {@link EmbedContentRequest}s.
1381
- *
1382
- * Fields set in the optional {@link SingleRequestOptions} parameter will
1383
- * take precedence over the {@link RequestOptions} values provided to
1384
- * {@link GoogleGenerativeAI.getGenerativeModel }.
1385
- */
1386
- async batchEmbedContents(batchEmbedContentRequest, requestOptions = {}) {
1387
- const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions);
1388
- return batchEmbedContents(this.apiKey, this.model, batchEmbedContentRequest, generativeModelRequestOptions);
1389
- }
1390
- };
1391
- /**
1392
- * @license
1393
- * Copyright 2024 Google LLC
1394
- *
1395
- * Licensed under the Apache License, Version 2.0 (the "License");
1396
- * you may not use this file except in compliance with the License.
1397
- * You may obtain a copy of the License at
1398
- *
1399
- * http://www.apache.org/licenses/LICENSE-2.0
1400
- *
1401
- * Unless required by applicable law or agreed to in writing, software
1402
- * distributed under the License is distributed on an "AS IS" BASIS,
1403
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1404
- * See the License for the specific language governing permissions and
1405
- * limitations under the License.
1406
- */
1407
- /**
1408
- * Top-level class for this SDK
1409
- * @public
1410
- */
1411
- var GoogleGenerativeAI = class {
1412
- constructor(apiKey) {
1413
- this.apiKey = apiKey;
1414
- }
1415
- /**
1416
- * Gets a {@link GenerativeModel} instance for the provided model name.
1417
- */
1418
- getGenerativeModel(modelParams, requestOptions) {
1419
- if (!modelParams.model) {
1420
- throw new GoogleGenerativeAIError(`Must provide a model name. ` + `Example: genai.getGenerativeModel({ model: 'my-model-name' })`);
1421
- }
1422
- return new GenerativeModel(this.apiKey, modelParams, requestOptions);
1423
- }
1424
- /**
1425
- * Creates a {@link GenerativeModel} instance from provided content cache.
1426
- */
1427
- getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions) {
1428
- if (!cachedContent.name) {
1429
- throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `name` field.");
1430
- }
1431
- if (!cachedContent.model) {
1432
- throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `model` field.");
1433
- }
1434
- /**
1435
- * Not checking tools and toolConfig for now as it would require a deep
1436
- * equality comparison and isn't likely to be a common case.
1437
- */
1438
- const disallowedDuplicates = ["model", "systemInstruction"];
1439
- for (const key of disallowedDuplicates) {
1440
- if ((modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) && cachedContent[key] && (modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) !== cachedContent[key]) {
1441
- if (key === "model") {
1442
- const modelParamsComp = modelParams.model.startsWith("models/") ? modelParams.model.replace("models/", "") : modelParams.model;
1443
- const cachedContentComp = cachedContent.model.startsWith("models/") ? cachedContent.model.replace("models/", "") : cachedContent.model;
1444
- if (modelParamsComp === cachedContentComp) {
1445
- continue;
1446
- }
1447
- }
1448
- throw new GoogleGenerativeAIRequestInputError(`Different value for "${key}" specified in modelParams` + ` (${modelParams[key]}) and cachedContent (${cachedContent[key]})`);
1449
- }
1450
- }
1451
- const modelParamsFromCache = Object.assign(Object.assign({}, modelParams), {
1452
- model: cachedContent.model,
1453
- tools: cachedContent.tools,
1454
- toolConfig: cachedContent.toolConfig,
1455
- systemInstruction: cachedContent.systemInstruction,
1456
- cachedContent
1457
- });
1458
- return new GenerativeModel(this.apiKey, modelParamsFromCache, requestOptions);
1459
- }
1460
- };
1461
-
1462
- //#endregion
1463
- exports.GoogleGenerativeAI = GoogleGenerativeAI;