-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
84 lines (78 loc) · 2.84 KB
/
background.js
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
const url = 'https://api.openai.com/v1/engines/text-davinci-003/completions';
let port = null;
chrome.storage.local.set({
apiKey: 'sk-gptopenapikey',
});
console.log('check');
// Listen for messages from the content script
chrome.runtime.onConnect.addListener(function(listenerPort) {
if (listenerPort.name === 'waitGPT') {
port = listenerPort;
port.onMessage.addListener(function(message) {
chrome.storage.local.get('apiKey', (result) => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError);
} else {
getCompletion(message.prompt, message.tone, result.apiKey, url).then(response => {
if (response) {
const result = response.choices[0];
const text = result.text;
const finishReason = result.finish_reason;
const index = result.index;
console.log(message.tone);
console.log('Sending response:', { editedPrompt: text });
port.postMessage({ editedPrompt: text });
console.log('Response sent');
}
}).catch(error => {
console.error(error);
});
}
});
});
port.onDisconnect.addListener(function() {
port = null;
});
}
});
function getApiKey() {
return new Promise((resolve, reject) => {
chrome.storage.local.get('apiKey', (result) => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else {
resolve(result.apiKey);
}
});
});
}
function usePreferredTone(promptText, promptTone) {
return promptText + '\\n\\n Rewrite this prompt so it has a formal and' + promptTone + 'sound, keep the bullets (if exists) in tact, also keep the same structure. Use the same language that is used in a prompt.';
}
function getCompletion(promptText, promptTone, apiKey, url) {
const requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
body: JSON.stringify({
prompt: usePreferredTone(promptText, promptTone),
temperature: 1,
max_tokens: 100,
top_p: 1,
frequency_penalty: 1,
presence_penalty: 1,
}),
};
return fetch(url, requestOptions)
.then(response => response.json())
.then(data => {
console.log(data);
return data;
})
.catch(error => {
console.error(error);
throw error;
});
}