-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
76 lines (69 loc) · 2.04 KB
/
script.js
File metadata and controls
76 lines (69 loc) · 2.04 KB
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
let prompt=document.querySelector(".prompt")
let container=document.querySelector(".container")
let chatContainer=document.querySelector(".chat-container")
let btn=document.querySelector(".btn")
let userMessage=null
const Api_url="https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-latest:generateContent?key=AIzaSyAguQE5lEfkaMY7Weo3E2rKAtOB9f8sY30"
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 109 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"
}
}
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)
chatContainer.scrollTop = chatContainer.scrollHeight;
}
btn.addEventListener("click",()=>{
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)
})