-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
62 lines (51 loc) · 1.72 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
const question = document.getElementById("question");
const responseIA = document.getElementById("response-IA");
question.addEventListener("keypress", (e) => {
if (question.value && e.key === "Enter") {
sendQuestion();
}
});
const OPENAI_API_KEY = ""; // Your API key
function sendQuestion() {
let sendQ = question.value;
fetch("https://api.openai.com/v1/completions", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer " + OPENAI_API_KEY,
},
body: JSON.stringify({
model: "text-davinci-003",
prompt: sendQ,
max_tokens: 2048,
temperature: 0.5,
}),
})
.then((response) => response.json())
.then((json) => {
if (responseIA.value) {
responseIA.value += "\n";
}
if (json.error?.message) {
responseIA.value += `Error: ${json.error.message}`;
} else if (json.choices?.[0].text) {
let text = json.choices[0].text || "No reply";
responseIA.value += "ChatGPT: " + text;
}
responseIA, scrollTop = responseIA.scrollHeight;
})
.catch((error) => console.error("Error:", error))
.finally(() => {
question.value = "";
question.disabled = false;
question.focus();
});
if (responseIA.value) {
responseIA.value += "\n\n\n";
responseIA.value += `I: ${sendQ}\n`;
question.value = "Waiting your answer...";
question.disabled = true;
responseIA.scrollTop = responseIA.scrollHeight;
}
}