Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
100 lines (86 loc) · 2.12 KB
/
Copy pathindex.js
File metadata and controls
100 lines (86 loc) · 2.12 KB
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
import { GoogleGenerativeAI } from '@google/generative-ai';
import fs from 'fs';
let genAI;
const DEFAULT_MODEL_TYPE = 'gemini-1.5-flash';
//
// HELPER FUNCTIONS
//
/**
* Set the GEMINI API key.
*/
export function setGeminiApiKey(apiKey) {
if (!apiKey) {
throw new Error('API key is required');
}
genAI = new GoogleGenerativeAI(apiKey);
}
/**
* Load GEMINI API key from environment variables.
*/
export function setGeminiApiKeyFromEnv() {
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
throw new Error('GEMINI_API_KEY environment variable is not set');
}
setGeminiApiKey(apiKey);
}
/**
* Set Gemini Model type.
*/
export function setGeminiModel(modelStringParam){
DEFAULT_MODEL_TYPE = modelStringParam;
}
/**
* Convert file to generative part.
*/
function fileToGenerativePart(path, mimeType) {
const data = fs.readFileSync(path).toString('base64');
return {
inlineData: {
data,
mimeType,
},
};
}
//
// MAIN FUNCTIONS
//
/**
* Ask GEMINI API with a prompt and optional images.
*/
export async function askGemini(prompt, images = []) {
if (!genAI) {
throw new Error('API key is not set. Use setGeminiApiKey() to set it.');
}
const model = genAI.getGenerativeModel({ model: DEFAULT_MODEL_TYPE });
let input = [prompt];
if (images.length) {
input = input.concat(images.map(image => fileToGenerativePart(image.path, image.type)));
}
try {
const result = await model.generateContent(input);
return result.response.text();
} catch (error) {
console.error('Error generating content:', error);
throw error;
}
}
/**
* Ask GEMINI API with a prompt and history.
*/
export async function askGeminiWithHistory(prompt, history = []) {
if (!genAI) {
throw new Error('API key is not set. Use setGeminiApiKey() to set it.');
}
const model = genAI.getGenerativeModel({ model: DEFAULT_MODEL_TYPE });
try {
const chat = model.startChat({
history
});
const result = await chat.sendMessage(prompt);
return result.response.text();
} catch (error) {
console.error('Error in chat with history:', error);
throw error;
}
}