-
Notifications
You must be signed in to change notification settings - Fork 2
/
script.js
57 lines (49 loc) · 1.75 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
const messageBar = document.querySelector(".bar-wrapper input");
const sendBtn = document.querySelector(".bar-wrapper button");
const messageBox = document.querySelector(".message-box");
let API_URL = "https://api.openai.com/v1/chat/completions";
let API_KEY =
/*Get API KEY at https://platform.openai.com/account/api-keys */
(sendBtn.onclick = function () {
if (messageBar.value.length > 0) {
const UserTypedMessage = messageBar.value;
messageBar.value = "";
let message = `<div class="chat message">
<img src="img/user.jpg">
<span>
${UserTypedMessage}
</span>
</div>`;
let response = `<div class="chat response">
<img src="img/logo.png">
<span class= "new">...
</span>
</div>`;
messageBox.insertAdjacentHTML("beforeend", message);
setTimeout(() => {
messageBox.insertAdjacentHTML("beforeend", response);
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${API_KEY}`,
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: UserTypedMessage }],
}),
};
fetch(API_URL, requestOptions)
.then((res) => res.json())
.then((data) => {
const ChatBotResponse = document.querySelector(".response .new");
ChatBotResponse.innerHTML = data.choices[0].message.content;
ChatBotResponse.classList.remove("new");
})
.catch((error) => {
ChatBotResponse.innerHTML =
"Opps! An error occured. Please try again";
});
}, 100);
}
});