-
Notifications
You must be signed in to change notification settings - Fork 854
Expand file tree
/
Copy pathgemini-api.mjs
More file actions
73 lines (63 loc) · 3.15 KB
/
gemini-api.mjs
File metadata and controls
73 lines (63 loc) · 3.15 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
import { getUserConfig } from '../../config/index.mjs';
import { pushRecord } from './shared.mjs'; // Assuming this is used for history
// import { fetchSSE } from '../../utils/fetch-sse.mjs'; // If streaming is needed
// Placeholder for the actual Gemini API endpoint
const GEMINI_API_ENDPOINT = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent';
export async function generateAnswersWithGeminiApi(port, question, session) {
const config = await getUserConfig();
const apiKey = config.geminiApiKey;
if (!apiKey) {
port.postMessage({ error: 'Gemini API key not configured.', done: true, session });
return;
}
try {
// Construct the request payload
// This is a placeholder structure and needs to be verified against Gemini API documentation
const payload = {
contents: [{
parts: [{
text: question,
}],
}],
// generationConfig: { // Optional: configure temperature, maxOutputTokens, etc.
// temperature: config.temperature,
// maxOutputTokens: config.maxResponseTokenLength,
// },
// safetySettings: [ // Optional: configure safety settings
// { category: 'HARM_CATEGORY_HARASSMENT', threshold: 'BLOCK_MEDIUM_AND_ABOVE' },
// { category: 'HARM_CATEGORY_HATE_SPEECH', threshold: 'BLOCK_MEDIUM_AND_ABOVE' },
// { category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT', threshold: 'BLOCK_MEDIUM_AND_ABOVE' },
// { category: 'HARM_CATEGORY_DANGEROUS_CONTENT', threshold: 'BLOCK_MEDIUM_AND_ABOVE' },
// ],
};
const response = await fetch(`${GEMINI_API_ENDPOINT}?key=${apiKey}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: response.statusText }));
console.error('Gemini API error:', errorData);
port.postMessage({ error: `Gemini API error: ${errorData.error?.message || errorData.message || 'Unknown error'}`, done: true, session });
return;
}
const responseData = await response.json();
// Extract the answer from the responseData
// This is a placeholder and needs to be verified against actual Gemini API response structure
// Expected structure: responseData.candidates[0].content.parts[0].text
let answer = 'No response from Gemini API.';
if (responseData.candidates && responseData.candidates[0] && responseData.candidates[0].content && responseData.candidates[0].content.parts && responseData.candidates[0].content.parts[0]) {
answer = responseData.candidates[0].content.parts[0].text;
} else {
console.error('Unexpected Gemini API response structure:', responseData);
}
pushRecord(session, question, answer);
// console.debug('Gemini conversation history', { content: session.conversationRecords });
port.postMessage({ answer: answer, done: true, session: session });
} catch (err) {
console.error('Error in generateAnswersWithGeminiApi:', err);
port.postMessage({ error: err.message || 'Failed to communicate with Gemini API.', done: true, session });
}
}