-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
92 lines (82 loc) · 2.95 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
let prompt = document.querySelector(".prompt");
let container = document.querySelector(".container");
let chatContainer = document.querySelector(".chat-container");
let btn = document.querySelector(".btn");
let userMessage = null;
let Api_Url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:generateContent?key=AIzaSyCQgaRm0lDw7WaXsqycVVjvf1tkGzT_00w'; // Replace with your actual API URL
function createChatBox(html, className) {
const div = document.createElement("div");
div.classList.add(className);
div.innerHTML = html;
return div;
}
async function generateApiResponse(aiChatBox) {
const textElement = aiChatBox.querySelector(".text");
try {
const response = await fetch(Api_Url, {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({
contents: [{
"role": "user",
"parts": [{text: `${userMessage} in 10 words`}]
}]
})
});
const data = await response.json();
const apiResponse = data?.candidates[0].content.parts[0].text.trim();
textElement.innerText = apiResponse;
} catch (error) {
console.log(error);
} finally {
aiChatBox.querySelector(".loading").style.display = "none";
scrollToBottom(); // Scroll to the bottom after API response
}
}
function showLoading() {
const html = `
<div id="img">
<img src="ai.png" alt="">
</div>
<div class="text">
</div>
<img src="loading.gif" alt="" height="50" class="loading">
`;
let aiChatBox = createChatBox(html, "ai-chat-box");
chatContainer.appendChild(aiChatBox);
generateApiResponse(aiChatBox);
scrollToBottom(); // Scroll to the bottom when loading AI response
}
function scrollToBottom() {
chatContainer.scrollTop = chatContainer.scrollHeight;
}
function handleSubmit() {
userMessage = prompt.value;
if (prompt.value === "") {
container.style.display = "flex";
} else {
container.style.display = "none";
}
if (!userMessage) return;
const html = `
<div id="img">
<img src="user.png" alt="">
</div>
<div class="text">
</div>`;
let userChatBox = createChatBox(html, "user-chat-box");
userChatBox.querySelector(".text").innerText = userMessage;
chatContainer.appendChild(userChatBox);
prompt.value = "";
setTimeout(showLoading, 500);
scrollToBottom(); // Scroll to the bottom when user sends a message
}
// Event listener for the button click
btn.addEventListener("click", handleSubmit);
// Event listener for the "Enter" key press
prompt.addEventListener("keypress", function (e) {
if (e.key === "Enter") {
e.preventDefault(); // Prevent form submission if needed
handleSubmit(); // Trigger the submit logic
}
});