-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
103 lines (90 loc) · 2.67 KB
/
script.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
console.log("Helper Ai");
// helper function to debounce function calls
function debounce(func, delay) {
let inDebounce;
return function () {
let context = this;
let args = arguments;
clearTimeout(inDebounce);
inDebounce = setTimeout(() => func.apply(context, args), delay);
};
}
// regex to check the text is in the form "help: command;"
let getTextParsed = (text) => {
let parsed = /help:(.*?)\;/gi.exec(text);
return parsed ? parsed[1] : "";
};
// helper function to get the nodes, extract their text
let getTextContentFromDOMElements = (nodes, textarea = false) => {
if (!nodes || nodes.length === 0) {
return null;
}
for (let node of nodes) {
let value = textarea ? node.value : node.textContent;
if (node && value) {
let text = getTextParsed(value);
if (text) return [node, text];
else return null;
}
}
};
// function to find the text on active tab
let scrapText = () => {
let ele = document.querySelectorAll('[contenteditable="true"]');
let parsedValue = getTextContentFromDOMElements(ele);
if (parsedValue) {
let [node, text] = parsedValue;
makeChatGPTCall(text, node);
}
};
// debounced function call
let debouncedScrapText = debounce(scrapText, 1000);
// observe what the user is typing
window.addEventListener("keypress", debouncedScrapText);
// function to make the GPT call
let makeChatGPTCall = async (text, node) => {
try {
let myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Authorization", "Bearer Your Key");
// set request payload
let raw = JSON.stringify({
model: "text-davinci-003",
prompt: text,
max_tokens: 2048,
temperature: 0,
top_p: 1,
n: 1,
stream: false,
logprobs: null,
});
// set request options
let requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
// make the api call
let response = await fetch(
"https://api.openai.com/v1/completions",
requestOptions
);
response = await response.json();
let { choices } = response;
// remove the spaces from the reponse text
let responseText = choices[0].text.replace(/^\s+|\s+$/g, "");
if (responseText) {
// format the response for better readability
responseText = responseText
.replace(/([.?!])\s*(?=[A-Z])/g, "$1|")
.split("|")
.join(".\n\n");
responseText = responseText.replace(/\n([^\n])/g, "\n $1");
// populate the node with the response
node.textContent = responseText;
}
} catch (e) {
console.error("Error while calling openai api", e);
}
};