mindcraft/src/models/gemini.js

54 lines
1.7 KiB
JavaScript
Raw Normal View History

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-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-02-18 22:56:38 -06:00
if (!process.env.GEMINI_API_KEY) {
2024-03-23 11:15:53 -05:00
throw new Error('Gemini API key missing! Make sure you set your GEMINI_API_KEY environment variable.');
2024-02-18 22:56:38 -06:00
}
this.genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
}
async sendRequest(turns, systemMessage) {
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"}
);
}
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;
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) {
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;
}
}