2024-02-18 22:56:38 -06:00
|
|
|
import { GoogleGenerativeAI } from '@google/generative-ai';
|
2024-05-10 13:41:29 -05:00
|
|
|
import { toSinglePrompt } from '../utils/text.js';
|
2024-05-27 12:36:29 +01:00
|
|
|
import configJson from "../../config.json" assert { type: "json" };
|
2024-04-24 11:28:04 -07:00
|
|
|
|
2024-02-18 22:56:38 -06:00
|
|
|
export class Gemini {
|
2024-04-24 11:28:04 -07:00
|
|
|
constructor(model_name, url) {
|
|
|
|
this.model_name = model_name;
|
|
|
|
this.url = url;
|
|
|
|
|
2024-05-27 12:36:29 +01:00
|
|
|
if (!configJson.GEMINI_API_KEY) {
|
|
|
|
throw new Error('Gemini API key missing! Make sure you set your GEMINI_API_KEY in your config.json.');
|
2024-02-18 22:56:38 -06:00
|
|
|
}
|
2024-05-27 12:36:29 +01:00
|
|
|
this.genAI = new GoogleGenerativeAI(configJson.GEMINI_API_KEY);
|
2024-02-18 22:56:38 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
async sendRequest(turns, systemMessage) {
|
2024-05-07 15:08:22 -05:00
|
|
|
let model;
|
2024-04-24 11:28:04 -07:00
|
|
|
if (this.url) {
|
|
|
|
model = this.genAI.getGenerativeModel(
|
|
|
|
{model: this.model_name || "gemini-pro"},
|
|
|
|
{baseUrl: this.url}
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
model = this.genAI.getGenerativeModel(
|
|
|
|
{model: this.model_name || "gemini-pro"}
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2024-05-07 15:08:22 -05:00
|
|
|
const stop_seq = '***';
|
|
|
|
const prompt = toSinglePrompt(turns, systemMessage, stop_seq, 'model');
|
2024-04-24 11:28:04 -07:00
|
|
|
const result = await model.generateContent(prompt);
|
2024-02-18 22:56:38 -06:00
|
|
|
const response = await result.response;
|
2024-05-07 15:08:22 -05:00
|
|
|
const text = response.text();
|
|
|
|
if (!text.includes(stop_seq)) return text;
|
|
|
|
const idx = text.indexOf(stop_seq);
|
|
|
|
return text.slice(0, idx);
|
2024-02-18 22:56:38 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
async embed(text) {
|
2024-05-07 15:08:22 -05:00
|
|
|
let model;
|
2024-04-24 11:28:04 -07:00
|
|
|
if (this.url) {
|
|
|
|
model = this.genAI.getGenerativeModel(
|
|
|
|
{model: this.model_name || "embedding-001"},
|
|
|
|
{baseUrl: this.url}
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
model = this.genAI.getGenerativeModel(
|
|
|
|
{model: this.model_name || "embedding-001"}
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
const result = await model.embedContent(text);
|
2024-02-18 22:56:38 -06:00
|
|
|
return result.embedding;
|
|
|
|
}
|
|
|
|
}
|