-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGeminiApp.js
1293 lines (1184 loc) · 38.4 KB
/
GeminiApp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* This library includes software components derived from the following projects:
* [ChatGPTApp] (https://github.com/scriptit-fr/ChatGPTApp)
* [Google AI JavaScript SDK] (https://github.com/google/generative-ai-js/)
*
* These components are licensed under the Apache License 2.0.
* A copy of the license can be found in the LICENSE file.
*/
/**
* @license
* Copyright 2025 Martin Hawksey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* CoreFunctions for GenerativeModel and Chat.
*/
class _CoreFunctions {
constructor() {
}
_countTokens(auth, model, params, singleRequestOptions) {
// modify the request if vertex ai
if (!auth.apiKey) {
params = params.generateContentRequest
}
const response = this._makeModelRequest(
model,
Task.COUNT_TOKENS,
auth,
false,
params,
singleRequestOptions
)
return response
};
_generateContent(auth, model, params, requestOptions) {
const response = this._makeModelRequest(
model,
Task.GENERATE_CONTENT,
auth,
/* stream */ false,
params,
requestOptions
)
const responseJson = response
const enhancedResponse = this._addHelpers(responseJson)
return {
response: enhancedResponse
}
};
_getHeaders(url) {
const headers = {};
if (url.apiKey) {
headers['X-Goog-Api-Key'] = url.apiKey;
} else if (url._auth?.type === 'service_account') {
const credentials = this._credentialsForVertexAI(url._auth);
headers['Authorization'] = `Bearer ${credentials.accessToken}`
} else {
headers['Authorization'] = `Bearer ${ScriptApp.getOAuthToken()}`;
}
return headers
}
_constructModelRequest(
model,
task,
auth,
stream,
body,
requestOptions
) {
const url = new RequestUrl(model, task, auth, stream, requestOptions);
return {
url: url.toString(),
fetchOptions: {
...this._buildFetchOptions(requestOptions),
'method': "POST",
'contentType': 'application/json',
'headers': this._getHeaders(url),
'payload': this._removeEmptyParams(body)
}
}
}
_makeModelRequest(
model,
task,
auth,
stream,
body,
requestOptions = {},
// Allows this to be stubbed for tests
fetchFn = UrlFetchApp.fetch
) {
const { url, fetchOptions } = this._constructModelRequest(
model,
task,
auth,
stream,
body,
requestOptions
)
return makeRequest_(url, fetchOptions, fetchFn)
}
_buildFetchOptions(requestOptions) {
return requestOptions
}
// @See https://github.com/googleworkspace/slides-advisor-add-on/blob/main/src/ai.js
_credentialsForVertexAI(auth) {
try {
const service = OAuth2.createService("Vertex")
.setTokenUrl('https://oauth2.googleapis.com/token')
.setPrivateKey(auth.private_key)
.setIssuer(auth.client_email)
.setPropertyStore(PropertiesService.getScriptProperties())
.setCache(CacheService.getScriptCache())
.setScope("https://www.googleapis.com/auth/cloud-platform");
return { accessToken: service.getAccessToken() }
} catch (e) {
console.error(e)
}
}
/**
* Import from https://github.com/google/generative-ai-js/blob/main/packages/main/src/requests/request-helpers.ts
*/
_formatGenerateContentInput(params) {
let formattedRequest
if (params.contents) {
formattedRequest = params
} else {
// Array or string
const content = this._formatNewContent(params)
formattedRequest = { contents: [content] }
}
if (params.systemInstruction) {
formattedRequest.systemInstruction = this._formatSystemInstruction(
params.systemInstruction
)
}
return formattedRequest
}
_formatCountTokensInput(params, modelParams) {
let formattedGenerateContentRequest = {
model: modelParams?.model,
generationConfig: modelParams?.generationConfig,
safetySettings: modelParams?.safetySettings,
tools: modelParams?.tools,
toolConfig: modelParams?.toolConfig,
systemInstruction: modelParams?.systemInstruction,
cachedContent: modelParams?.cachedContent?.name,
contents: []
}
const containsGenerateContentRequest = params.generateContentRequest != null
if (params.contents) {
if (containsGenerateContentRequest) {
throw new GoogleGenerativeAIRequestInputError(
"CountTokensRequest must have one of contents or generateContentRequest, not both."
)
}
formattedGenerateContentRequest.contents = params.contents
} else if (containsGenerateContentRequest) {
formattedGenerateContentRequest = {
...formattedGenerateContentRequest,
...params.generateContentRequest
}
} else {
// Array or string
const content = this._formatNewContent(params)
formattedGenerateContentRequest.contents = [content]
}
return { generateContentRequest: formattedGenerateContentRequest }
}
_removeEmptyParams(params) {
return JSON.stringify(
Object.fromEntries(
Object.entries(params).filter(([_, v]) => v != null && (!Array.isArray(v) || v.length > 0))
)
);
}
_formatNewContent(request) {
let newParts = [];
if (typeof request === "string") {
newParts = [{ text: request }]
} else {
for (const partOrString of request) {
if (typeof partOrString === "string") {
newParts.push({ text: partOrString })
} else {
newParts.push(partOrString)
}
}
}
return this._assignRoleToPartsAndValidateSendMessageRequest(newParts)
}
_formatSystemInstruction(input) {
if (input == null) {
return undefined
} else if (typeof input === "string") {
return {
role: "system",
parts: [{ text: input }]
}
} else if (input.text) {
return { role: "system", parts: [input] }
} else if (input.parts) {
if (!input.role) {
return { role: "system", parts: input.parts }
} else {
return input
}
}
}
_assignRoleToPartsAndValidateSendMessageRequest(parts) {
const userContent = { role: "user", parts: [] }
const functionContent = { role: "function", parts: [] }
let hasUserContent = false
let hasFunctionContent = false
for (const part of parts) {
if ("functionResponse" in part) {
functionContent.parts.push(part)
hasFunctionContent = true
} else {
userContent.parts.push(part)
hasUserContent = true
}
}
if (hasUserContent && hasFunctionContent) {
throw new GoogleGenerativeAIError(
"Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message."
)
}
if (!hasUserContent && !hasFunctionContent) {
throw new GoogleGenerativeAIError(
"No content is provided for sending chat message."
)
}
if (hasUserContent) {
return userContent
}
return functionContent
}
_addHelpers(response) {
response.text = () => {
if (response.candidates && response.candidates.length > 0) {
if (response.candidates.length > 1) {
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.`
)
}
if (this._hadBadFinishReason(response.candidates[0])) {
throw new GoogleGenerativeAIResponseError(
`${this._formatBlockErrorMessage(response)}`,
response
)
}
return this._getText(response)
} else if (response.promptFeedback) {
throw new GoogleGenerativeAIResponseError(
`Text not available. ${this._formatBlockErrorMessage(response)}`,
response
)
}
return ""
}
/**
* TODO: remove at next major version
*/
response.functionCall = () => {
if (response.candidates && response.candidates.length > 0) {
if (response.candidates.length > 1) {
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.`
)
}
if (this._hadBadFinishReason(response.candidates[0])) {
throw new GoogleGenerativeAIResponseError(
`${this._formatBlockErrorMessage(response)}`,
response
)
}
console.warn(
`response.functionCall() is deprecated. ` +
`Use response.functionCalls() instead.`
)
return this._getFunctionCalls(response)[0]
} else if (response.promptFeedback) {
throw new GoogleGenerativeAIResponseError(
`Function call not available. ${this._formatBlockErrorMessage(response)}`,
response
)
}
return undefined
}
response.functionCalls = () => {
if (response.candidates && response.candidates.length > 0) {
if (response.candidates.length > 1) {
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.`
)
}
if (this._hadBadFinishReason(response.candidates[0])) {
throw new GoogleGenerativeAIResponseError(
`${this._formatBlockErrorMessage(response)}`,
response
)
}
return this._getFunctionCalls(response)
} else if (response.promptFeedback) {
throw new GoogleGenerativeAIResponseError(
`Function call not available. ${this._formatBlockErrorMessage(response)}`,
response
)
}
return undefined
}
response.json = function () {
if (response.candidates?.[0].content?.parts?.[0]?.text) {
return response.candidates[0].content.parts.map(({ text }) => JSON.parse(text));
} else {
return "";
}
};
return response
}
_getText(response) {
const textStrings = []
if (response.candidates?.[0].content?.parts) {
for (const part of response.candidates?.[0].content?.parts) {
if (part.text) {
textStrings.push(part.text)
}
if (part.executableCode) {
textStrings.push(
"\n```" +
part.executableCode.language +
"\n" +
part.executableCode.code +
"\n```\n"
)
}
if (part.codeExecutionResult) {
textStrings.push(
"\n```\n" + part.codeExecutionResult.output + "\n```\n"
)
}
}
}
if (textStrings.length > 0) {
return textStrings.join("")
} else {
return ""
}
}
_getFunctionCalls(response) {
const functionCalls = []
if (response.candidates?.[0].content?.parts) {
for (const part of response.candidates?.[0].content?.parts) {
if (part.functionCall) {
functionCalls.push(part.functionCall)
}
}
}
if (functionCalls.length > 0) {
return functionCalls
} else {
return undefined
}
}
_hadBadFinishReason(candidate) {
const badFinishReasons = [
FinishReason.FINISH_REASON_UNSPECIFIED,
FinishReason.MAX_TOKENS,
FinishReason.SAFETY,
FinishReason.RECITATION,
FinishReason.LANGUAGE,
FinishReason.BLOCKLIST,
FinishReason.PROHIBITED_CONTENT,
FinishReason.SPII,
FinishReason.MALFORMED_FUNCTION_CALL,
FinishReason.OTHER
];
return (
!!candidate.finishReason &&
badFinishReasons.includes(candidate.finishReason)
)
}
_formatBlockErrorMessage(response) {
let message = ""
if (
(!response.candidates || response.candidates.length === 0) &&
response.promptFeedback
) {
message += "Response was blocked"
if (response.promptFeedback?.blockReason) {
message += ` due to ${response.promptFeedback.blockReason}`
}
if (response.promptFeedback?.blockReasonMessage) {
message += `: ${response.promptFeedback.blockReasonMessage}`
}
} else if (response.candidates?.[0]) {
const firstCandidate = response.candidates[0]
if (this._hadBadFinishReason(firstCandidate)) {
message += `Candidate was blocked due to ${firstCandidate.finishReason}`
if (firstCandidate.finishMessage) {
message += `: ${firstCandidate.finishMessage}`
}
}
}
return message
}
}
/**
* Class representing _GoogleGenerativeAI
*
* @constructor
* @param {Object|string} options - Configuration options for the class instance.
* @param {string} [options.apiKey] - API key for authentication.
* @param {string} [options.region] - Region for the Vertex AI project.
* @param {string} [options.project_id] - Project ID for the Vertex AI project
* @param {string} [options.type] - Type of authentication (e.g., 'service_account').
* @param {string} [options.private_key] - Private key for service account authentication.
* @param {string} [options.client_email] - Client email for service account authentication.
* @param {string} [options.model] - The model to use (defaults to '').
*/
class _GoogleGenerativeAI {
constructor(options) {
this._auth = {};
if (typeof options === 'string') {
this._auth.apiKey = options
} else {
if (options.region && options.project_id) {
this._auth.region = options.region;
this._auth.project_id = options.project_id;
}
if (options.type && options.type === "service_account") {
this._auth.type = options.type;
this._auth.private_key = options.private_key;
this._auth.client_email = options.client_email;
}
}
this.tools = [];
this.model = options.model || ''
}
getGenerativeModel(modelParams, requestOptions) {
if (!modelParams.model) {
throw new Error(
`Must provide a model name. ` +
`Example: genai.getGenerativeModel({ model: 'my-model-name' })`
);
}
return new GenerativeModel(this._auth, modelParams, requestOptions);
}
/**
* Creates a {@link GenerativeModel} instance from provided content cache.
*/
getGenerativeModelFromCachedContent(
cachedContent,
modelParams,
requestOptions
) {
if (!cachedContent.name) {
throw new GoogleGenerativeAIRequestInputError(
"Cached content must contain a `name` field."
)
}
if (!cachedContent.model) {
throw new GoogleGenerativeAIRequestInputError(
"Cached content must contain a `model` field."
)
}
/**
* Not checking tools and toolConfig for now as it would require a deep
* equality comparison and isn't likely to be a common case.
*/
const disallowedDuplicates = ["model", "systemInstruction"]
for (const key of disallowedDuplicates) {
if (
modelParams?.[key] &&
cachedContent[key] &&
modelParams?.[key] !== cachedContent[key]
) {
if (key === "model") {
const modelParamsComp = modelParams.model.startsWith("models/")
? modelParams.model.replace("models/", "")
: modelParams.model
const cachedContentComp = cachedContent.model.startsWith("models/")
? cachedContent.model.replace("models/", "")
: cachedContent.model
if (modelParamsComp === cachedContentComp) {
continue
}
}
throw new GoogleGenerativeAIRequestInputError(
`Different value for "${key}" specified in modelParams` +
` (${modelParams[key]}) and cachedContent (${cachedContent[key]})`
)
}
}
const modelParamsFromCache = {
...modelParams,
model: cachedContent.model,
tools: cachedContent.tools,
toolConfig: cachedContent.toolConfig,
systemInstruction: cachedContent.systemInstruction,
cachedContent
}
return new GenerativeModel(
this._auth,
modelParamsFromCache,
requestOptions
)
}
}
/* @constructor
* @param {Object|string} options - Configuration options for the class instance.
* @param {string} [options.apiKey] - API key for authentication.
* @param {string} [options.region] - Region for the Vertex AI project.
* @param {string} [options.project_id] - Project ID for the Vertex AI project
* @param {string} [options.type] - Type of authentication (e.g., 'service_account').
* @param {string} [options.private_key] - Private key for service account authentication.
* @param {string} [options.client_email] - Client email for service account authentication.
* @param {string} [options.model] - The model to use (defaults to '').
*/
var GeminiApp = _GoogleGenerativeAI;
var GoogleGenerativeAI = _GoogleGenerativeAI;
class _GenerativeModel extends _CoreFunctions {
constructor(auth, modelParams, requestOptions) {
super();
this._auth = auth;
this._requestOptions = requestOptions
if (modelParams.model.includes("/")) {
// Models may be named "models/model-name" or "tunedModels/model-name"
this.model = modelParams.model
} else {
// If path is not included, assume it's a non-tuned model.
this.model = `models/${modelParams.model}`
}
this.generationConfig = modelParams.generationConfig || {};
this.safetySettings = modelParams.safetySettings || [];
this.tools = modelParams.tools;
this.toolConfig = modelParams.toolConfig;
this.systemInstruction = this._formatSystemInstruction(
modelParams.systemInstruction
)
this.cachedContent = modelParams.cachedContent
}
generateContent(request, requestOptions = {}) {
const formattedParams = super._formatGenerateContentInput(request);
const generativeModelRequestOptions = {
...this._requestOptions,
...requestOptions
}
return super._generateContent(
this._auth,
this.model,
{
generationConfig: this.generationConfig,
safetySettings: this.safetySettings,
tools: this.tools,
toolConfig: this.toolConfig,
systemInstruction: this.systemInstruction,
cachedContent: this.cachedContent?.name,
...formattedParams
},
generativeModelRequestOptions
);
}
countTokens(request, requestOptions = {}) {
const formattedParams = super._formatCountTokensInput(request, {
model: this.model,
generationConfig: this.generationConfig,
safetySettings: this.safetySettings,
tools: this.tools,
toolConfig: this.toolConfig,
systemInstruction: this.systemInstruction,
cachedContent: this.cachedContent
})
const generativeModelRequestOptions = {
...this._requestOptions,
...requestOptions
}
return super._countTokens(
this._auth,
this.model,
formattedParams,
generativeModelRequestOptions);
}
startChat(startChatParams) {
return new ChatSession(
this._auth,
this.model,
{
generationConfig: this.generationConfig,
safetySettings: this.safetySettings,
tools: this.tools,
toolConfig: this.toolConfig,
systemInstruction: this.systemInstruction,
cachedContent: this.cachedContent?.name,
...startChatParams
},
this._requestOptions,
);
};
newFunction() {
return new FunctionObject()
}
}
var GenerativeModel = _GenerativeModel
class ChatSession extends _CoreFunctions {
constructor(auth, model, params, _requestOptions = {}) {
super();
this._auth = auth;
this._history = [];
this._functions = [];
this.model = model;
this.params = params;
this.tools = this.params?.tools || [];
this._requestOptions = _requestOptions
if (params?.history) {
this._validateChatHistory(params.history)
this._history = params.history
}
}
/**
* Gets the chat history so far. Blocked prompts are not added to history.
* Blocked candidates are not added to history, nor are the prompts that
* generated them.
*/
getHistory() {
return this._history
}
sendMessage(request, requestOptions = {}, skipFormat = false) {
const newContent = (skipFormat) ? request : super._formatNewContent(request);
const generateContentRequest = {
safetySettings: this?.safetySettings,
generationConfig: this?.generationConfig,
tools: this?.tools,
toolConfig: this?.toolConfig,
systemInstruction: this?.systemInstruction,
cachedContent: this?.cachedContent,
contents: [...this._history, newContent]
}
const chatSessionRequestOptions = {
...this._requestOptions,
...requestOptions
}
const result = super._generateContent(
this._auth,
this.model,
generateContentRequest,
this._requestOptions,
chatSessionRequestOptions
);
let functionCall = result.response.functionCalls();
if (this._functions.length >> 0 && functionCall) {
this._history.push(newContent);
// Check if Gemini wanted to call a function
let functionParts = [];
let functionName = functionCall[0].name;
let functionArgs = functionCall[0].args;
let argsOrder = [];
let endWithResult = false;
let onlyReturnArguments = false;
for (let f in this._functions) {
let currentFunction = this._functions[f].toJSON();
if (currentFunction.name == functionName) {
argsOrder = currentFunction.argumentsInRightOrder; // get the args in the right order
endWithResult = currentFunction.endingFunction;
onlyReturnArguments = currentFunction.onlyArgs;
break;
}
}
if (endWithResult) {
let functionResponse = this._callFunction(functionName, functionArgs, argsOrder);
if (typeof functionResponse === "string") {
functionResponse = { text: functionResponse };
}
return result;
} else if (onlyReturnArguments) {
return functionArgs;
} else {
let functionResponse = this._callFunction(functionName, functionArgs, argsOrder);
if (typeof functionResponse === "string") {
functionResponse = { content: functionResponse };
}
// Inform the chat that the function has been called
functionParts.push({
"role": "model",
"parts": [{
"functionCall": {
"name": functionName,
"args": functionArgs
}
}]
});
functionParts.push({
"role": "user",
"parts": [{
"functionResponse": {
"name": functionName,
"response": functionResponse
}
}]
});
}
return this.sendMessage(functionParts, requestOptions, true)
} else if (
result.response.candidates &&
result.response.candidates.length > 0 &&
result.response.candidates[0]?.content !== undefined
) {
this._history.push(newContent)
const responseContent = {
parts: [],
// Response seems to come back without a role set.
role: "model",
...result.response.candidates?.[0].content
}
this._history.push(responseContent)
} else {
const blockErrorMessage = formatBlockErrorMessage(result.response)
if (blockErrorMessage) {
console.warn(
`sendMessage() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`
)
}
}
let finalResult = result;
return finalResult;
}
addFunction(functionObject) {
this._functions.push(functionObject);
const functionDeclaration = {
name: functionObject.toJSON().name,
description: functionObject.toJSON().description,
parameters: functionObject.toJSON().parameters
};
const toolsFunctionObject = this.tools.find(tool => tool.hasOwnProperty("functionDeclarations"));
if (toolsFunctionObject) {
toolsFunctionObject.functionDeclarations.push(functionDeclaration);
} else {
this.tools.push({ functionDeclarations: [functionDeclaration] })
}
return this
}
_callFunction(functionName, jsonArgs, argsOrder) {
// Parse JSON arguments
var argsObj = jsonArgs;
let argsArray = argsOrder.map(argName => argsObj[argName]);
// Call the function dynamically
if (globalThis[functionName] instanceof Function) {
let functionResponse = globalThis[functionName].apply(null, argsArray);
if (functionResponse) {
return functionResponse;
}
else {
return "the function has been sucessfully executed but has nothing to return";
}
}
else {
throw Error("Function not found or not a function: " + functionName);
}
}
_validateChatHistory(history) {
let prevContent = false
for (const currContent of history) {
const { role, parts } = currContent
if (!prevContent && role !== "user") {
throw new GoogleGenerativeAIError(
`First content should be with role 'user', got ${role}`
)
}
if (!POSSIBLE_ROLES.includes(role)) {
throw new GoogleGenerativeAIError(
`Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(
POSSIBLE_ROLES
)}`
)
}
if (!Array.isArray(parts)) {
throw new GoogleGenerativeAIError(
"Content should have 'parts' property with an array of Parts"
)
}
if (parts.length === 0) {
throw new GoogleGenerativeAIError(
"Each Content should have at least one part"
)
}
const countFields = {
text: 0,
inlineData: 0,
functionCall: 0,
functionResponse: 0,
fileData: 0,
executableCode: 0,
codeExecutionResult: 0
}
for (const part of parts) {
for (const key of VALID_PART_FIELDS) {
if (key in part) {
countFields[key] += 1
}
}
}
const validParts = VALID_PARTS_PER_ROLE[role]
for (const key of VALID_PART_FIELDS) {
if (!validParts.includes(key) && countFields[key] > 0) {
throw new GoogleGenerativeAIError(
`Content with role '${role}' can't contain '${key}' part`
)
}
}
prevContent = true
}
}
}
/**
* import from https://github.com/google/generative-ai-js/blob/main/packages/main/src/requests/request.ts
*/
var BASE_URL_STUDIO = "https://generativelanguage.googleapis.com";
var BASE_URL_VERTEX = "https://{REGION}-aiplatform.googleapis.com/{apiVersion}/projects/{PROJECT_ID}/locations/{REGION}/publishers/google";
var DEFAULT_API_VERSION_STUDIO = "v1beta";
var DEFAULT_API_VERSION_VERTEX = "v1";
/**
* import from https://github.com/google/generative-ai-js/blob/main/packages/main/types/enums.ts
*/
const POSSIBLE_ROLES = ["user", "model", "function"];
/**
* Harm categories that would cause prompts or candidates to be blocked.
* @public
*/
const HarmCategory = Object.freeze({
HARM_CATEGORY_UNSPECIFIED: "HARM_CATEGORY_UNSPECIFIED",
HARM_CATEGORY_HATE_SPEECH: "HARM_CATEGORY_HATE_SPEECH",
HARM_CATEGORY_SEXUALLY_EXPLICIT: "HARM_CATEGORY_SEXUALLY_EXPLICIT",
HARM_CATEGORY_HARASSMENT: "HARM_CATEGORY_HARASSMENT",
HARM_CATEGORY_DANGEROUS_CONTENT: "HARM_CATEGORY_DANGEROUS_CONTENT",
});
/**
* Threshold above which a prompt or candidate will be blocked.
* @public
*/
const HarmBlockThreshold = Object.freeze({
HARM_BLOCK_THRESHOLD_UNSPECIFIED: "HARM_BLOCK_THRESHOLD_UNSPECIFIED",
BLOCK_LOW_AND_ABOVE: "BLOCK_LOW_AND_ABOVE",
BLOCK_MEDIUM_AND_ABOVE: "BLOCK_MEDIUM_AND_ABOVE",
BLOCK_ONLY_HIGH: "BLOCK_ONLY_HIGH",
BLOCK_NONE: "BLOCK_NONE",
});
/**
* Probability that a prompt or candidate matches a harm category.
* @public
*/
const HarmProbability = Object.freeze({
HARM_PROBABILITY_UNSPECIFIED: "HARM_PROBABILITY_UNSPECIFIED",
NEGLIGIBLE: "NEGLIGIBLE",
LOW: "LOW",
MEDIUM: "MEDIUM",
HIGH: "HIGH",
});
/**
* Contains the list of OpenAPI data types
* as defined by https://swagger.io/docs/specification/data-models/data-types/
* @public
*/
const SchemaType = Object.freeze({
STRING: "string",
NUMBER: "number",
INTEGER: "integer",
BOOLEAN: "boolean",
ARRAY: "array",
OBJECT: "object"
});
/**
* Reason that a prompt was blocked.
* @public
*/
const BlockReason = Object.freeze({
BLOCKED_REASON_UNSPECIFIED: "BLOCKED_REASON_UNSPECIFIED",
SAFETY: "SAFETY",
OTHER: "OTHER",
});
const Task = Object.freeze({
GENERATE_CONTENT: "generateContent",
STREAM_GENERATE_CONTENT: "streamGenerateContent",
COUNT_TOKENS: "countTokens",
EMBED_CONTENT: "embedContent",
BATCH_EMBED_CONTENTS: "batchEmbedContents"
});
const FinishReason = Object.freeze({
// Default value. This value is unused.
FINISH_REASON_UNSPECIFIED: "FINISH_REASON_UNSPECIFIED",
// Natural stop point of the model or provided stop sequence.
STOP: "STOP",
// The maximum number of tokens as specified in the request was reached.
MAX_TOKENS: "MAX_TOKENS",
// The candidate content was flagged for safety reasons.
SAFETY: "SAFETY",
// The candidate content was flagged for recitation reasons.
RECITATION: "RECITATION",
// The candidate content was flagged for using an unsupported language.
LANGUAGE: "LANGUAGE",
// Token generation stopped because the content contains forbidden terms.
BLOCKLIST: "BLOCKLIST",
// Token generation stopped for potentially containing prohibited content.