107 lines
1.9 KiB
JavaScript
107 lines
1.9 KiB
JavaScript
'use strict';
|
|
|
|
const conf = require('../conf');
|
|
const {sleep} = require('../utils');
|
|
|
|
|
|
const {
|
|
GoogleGenerativeAI,
|
|
HarmCategory,
|
|
HarmBlockThreshold,
|
|
} = require("@google/generative-ai");
|
|
|
|
|
|
|
|
class Ai{
|
|
constructor(prompt){
|
|
this.prompt = prompt;
|
|
this.start();
|
|
}
|
|
|
|
__settings(history){
|
|
return {
|
|
generationConfig: {
|
|
temperature: 1,
|
|
topP: 0.95,
|
|
topK: 64,
|
|
maxOutputTokens: 8192,
|
|
responseMimeType: "application/json",
|
|
},
|
|
safetySettings:[
|
|
// See https://ai.google.dev/gemini-api/docs/safety-settings
|
|
{
|
|
category: HarmCategory.HARM_CATEGORY_HARASSMENT,
|
|
threshold: HarmBlockThreshold.BLOCK_NONE,
|
|
},
|
|
{
|
|
category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
|
|
threshold: HarmBlockThreshold.BLOCK_NONE,
|
|
},
|
|
{
|
|
category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
|
|
threshold: HarmBlockThreshold.BLOCK_NONE,
|
|
},
|
|
{
|
|
category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
|
|
threshold: HarmBlockThreshold.BLOCK_NONE,
|
|
},
|
|
],
|
|
history: history || [
|
|
{
|
|
role: "user",
|
|
parts: [
|
|
{text: this.prompt},
|
|
],
|
|
},
|
|
{
|
|
role: "model",
|
|
parts: [
|
|
{text: "Chat stuff"},
|
|
],
|
|
}
|
|
],
|
|
}
|
|
}
|
|
|
|
start(history){
|
|
const genAI = new GoogleGenerativeAI(conf.ai.key);
|
|
|
|
const model = genAI.getGenerativeModel({
|
|
model: "gemini-1.5-flash",
|
|
});
|
|
|
|
this.session = model.startChat({
|
|
...this.__settings(history),
|
|
// systemInstruction: this.prompt,
|
|
});
|
|
}
|
|
|
|
async chat(message, retryCount=0){
|
|
console.log('chat', retryCount)
|
|
try{
|
|
let result = await this.session.sendMessage(message);
|
|
|
|
return result
|
|
}catch(error){
|
|
console.log('AI chat error', error)
|
|
|
|
if(retryCount > 3){
|
|
console.log('hit retry count');
|
|
return ;
|
|
};
|
|
await sleep(500);
|
|
this.session.params.history.pop();
|
|
console.log('current history', this.session.params.history);
|
|
this.start(this.session.params.history);
|
|
return await this.chat(message, retryCount++)
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
module.exports = {Ai};
|
|
// run();
|