-
Notifications
You must be signed in to change notification settings - Fork 268
/
Copy pathscript.js
63 lines (56 loc) · 1.92 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
const chatInput = document.querySelector(".chat-input textarea");
const sendChatBtn = document.querySelector(".chat-input span");
const chatbox = document.querySelector(".chatbox");
let userMessage = "";
const API_KEY="";
const createChatLi = (message, className) => {
const chatLi = document.createElement("li");
chatLi.classList.add("chat", className);
let chatContent =
className === "outgoing"
? `<p></p>`
: `<span class="material-symbols-outlined">smart_toy</span><p></p>`;
chatLi.innerHTML = chatContent;
chatLi.querySelector("p").textContent = message;
return chatLi;
};
const generateResponse = (incomingChatLi) => {
const API_URL = `https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent?key=${API_KEY}`;
const messageElement = incomingChatLi.querySelector("p");
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contents: [
{
role: "user",
parts: [{ text: userMessage }],
},
],
}),
};
fetch(API_URL, requestOptions)
.then((res) => res.json())
.then((data) => {
messageElement.textContent = data.candidates[0].content.parts[0].text;
})
.catch((error) => {
messageElement.textContent =
"Oops! Something went wrong. Please try again later.";
})
.finally(() => chatbox.scrollTo(0, chatbox.scrollHeight));
};
const handleChat = () => {
userMessage = chatInput.value.trim();
if (!userMessage) return;
chatInput.value = "";
chatbox.appendChild(createChatLi(userMessage, "outgoing"));
chatbox.scrollTo(0, chatbox.scrollHeight);
setTimeout(() => {
const incomingChatLi = createChatLi("Thinking....", "incoming");
chatbox.appendChild(incomingChatLi);
chatbox.scrollTo(0, chatbox.scrollHeight);
generateResponse(incomingChatLi);
}, 600);
};
sendChatBtn.addEventListener("click", handleChat);