-
Notifications
You must be signed in to change notification settings - Fork 21
/
api.js
75 lines (63 loc) · 2.36 KB
/
api.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
chrome.runtime.onMessage.addListener(
(request, sender, sendResponse) => {
sendRequestToAPI(request, sender, sendResponse);
return true; // keep the message channel open to the other end until sendResponse is called
}
);
const sendRequestToAPI = async (request, _sender, sendResponse) => {
if (request.message === "submit") {
var prompt = request.text;
// set 'api_key', 'temperature', 'max_tokens' from chrome.storage.sync.get all at once
const { api_key, temperature, max_tokens } = await new Promise((resolve, reject) => {
chrome.storage.sync.get(['api_key', 'temperature', 'max_tokens'], (result) => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else {
resolve(result);
}
});
});
const url = 'https://api.openai.com/v1/completions';
const data = {
"model": "text-davinci-003",
"prompt": prompt,
"temperature": parseFloat(temperature),
"max_tokens": parseInt(max_tokens)
};
// const url = "https://api.openai.com/v1/chat/completions";
// const headers = {
// "Content-Type": "application/json",
// "Authorization": `Bearer ${api_key}`
// };
// const data = JSON.stringify({
// model: "gpt-3.5-turbo",
// messages: [
// {
// role: "user",
// content: prompt
// }
// ]
// });
try {
// const response = await fetch(url, {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// 'Authorization': `Bearer ${api_key}`
// },
// body: JSON.stringify(data)
// });
// const json = await response.json();
// sendResponse(json);
// const response = await fetch(url, {
// method: "POST",
// headers: headers,
// body: data
// });
// const json = await response.json();
// sendResponse(json);
} catch (e) {
sendResponse({ error: { message: e.message } });
}
}
}