-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
264 lines (229 loc) · 8.75 KB
/
script.js
File metadata and controls
264 lines (229 loc) · 8.75 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
// Selectors for UI elements
const chatBody = document.querySelector(".chat-body");
const messageInput = document.querySelector(".message-input");
const sendMessageButton = document.querySelector("#send-message");
const fileInput = document.querySelector("#file-input");
const chatbotToggler = document.querySelector("#chatbot-toggler");
const closeChatbot = document.querySelector("#close-chatbot");
// API setup
const API_KEY = "AIzaSyCMt8TKggH_yqgs2lT8iYRo1BGWK22MTYI"; // Replace with your actual API key
const API_URL = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${API_KEY}`;
const userData = {
message: null,
file: {
data: null,
mime_type: null,
},
};
const chatHistory = [];
const initialInputHeight = messageInput.scrollHeight;
// Load data from data.txt
let companyData = "";
const loadCompanyData = async () => {
try {
const response = await fetch('data.txt');
companyData = await response.text();
} catch (error) {
console.error("Error loading company data:", error);
}
};
loadCompanyData();
// Create message element with dynamic classes and return it
const createMessageElement = (content, ...classes) => {
const div = document.createElement("div");
div.classList.add("message", ...classes);
div.innerHTML = content;
return div;
};
// Generate bot response using API
const generateBotResponse = async (incomingMessageDiv) => {
const messageElement = incomingMessageDiv.querySelector(".message-text");
// Add user message to chat history
chatHistory.push({
role: "user",
parts: [
{ text: userData.message },
...(userData.file.data ? [{ inline_data: { mime_type: userData.file.mime_type, data: userData.file.data } }] : []),
],
});
// Combine company data with user's question
const prompt = `
This is the company data file, and you are the SBI Life Insurance Assistant.
Your primary role is to sell insurance to customers, help them with their queries,
and provide accurate answers based on the following company data:
${companyData}
User: ${userData.message}
`;
// API request options
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contents: [
{
role: "user",
parts: [{ text: prompt }],
},
...chatHistory,
],
}),
};
try {
// Fetch bot response from API
const response = await fetch(API_URL, requestOptions);
const data = await response.json();
if (!response.ok) throw new Error(data.error.message);
// Extract and display the bot response
const apiResponseText = data.candidates[0].content.parts[0].text
.replace(/\*\*(.*?)\*\*/g, "$1")
.trim();
messageElement.innerText = apiResponseText;
// Add bot response to chat history
chatHistory.push({
role: "model",
parts: [{ text: apiResponseText }],
});
} catch (error) {
console.log(error);
messageElement.innerText = error.message;
messageElement.style.color = "#ff0000";
} finally {
incomingMessageDiv.classList.remove("thinking");
chatBody.scrollTo({ top: chatBody.scrollHeight, behavior: "smooth" });
}
};
// Handle outgoing user messages
const handleOutgoingMessage = (e) => {
e.preventDefault();
userData.message = messageInput.value.trim();
messageInput.value = "";
messageInput.dispatchEvent(new Event("input"));
// Create and display user message
const messageContent = `<div class="message-text"></div>
${
userData.file.data
? `<div class="file-attachment">
<span class="file-name">${userData.file.name}</span>
<span class="file-size">${(userData.file.data.length / 1024).toFixed(2)} KB</span>
</div>`
: ""
}`;
const outgoingMessageDiv = createMessageElement(
messageContent,
"user-message"
);
outgoingMessageDiv.querySelector(".message-text").textContent =
userData.message;
chatBody.appendChild(outgoingMessageDiv);
chatBody.scrollTo({ top: chatBody.scrollHeight, behavior: "smooth" });
// Simulate bot response with thinking indicator after a delay
setTimeout(() => {
const messageContent = `<svg
class="bot-avatar"
xmlns="http://www.w3.org/2000/svg"
width="50"
height="50"
viewBox="0 0 1024 1024"
>
<path
d="M738.3 287.6H285.7c-59 0-106.8 47.8-106.8 106.8v303.1c0 59 47.8 106.8 106.8 106.8h81.5v111.1c0 .7.8 1.1 1.4.7l166.9-110.6 41.8-.8h117.4l43.6-.4c59 0 106.8-47.8 106.8-106.8V394.5c0-59-47.8-106.9-106.8-106.9zM351.7 448.2c0-29.5 23.9-53.5 53.5-53.5s53.5 23.9 53.5 53.5-23.9 53.5-53.5 53.5-53.5-23.9-53.5-53.5zm157.9 267.1c-67.8 0-123.8-47.5-132.3-109h264.6c-8.6 61.5-64.5 109-132.3 109zm110-213.7c-29.5 0-53.5-23.9-53.5-53.5s23.9-53.5 53.5-53.5 53.5 23.9 53.5 53.5-23.9 53.5-53.5 53.5zM867.2 644.5V453.1h26.5c19.4 0 35.1 15.7 35.1 35.1v121.1c0 19.4-15.7 35.1-35.1 35.1h-26.5zM95.2 609.4V488.2c0-19.4 15.7-35.1 35.1-35.1h26.5v191.3h-26.5c-19.4 0-35.1-15.7-35.1-35.1zM561.5 149.6c0 23.4-15.6 43.3-36.9 49.7v44.9h-30v-44.9c-21.4-6.5-36.9-26.3-36.9-49.7 0-28.6 23.3-51.9 51.9-51.9s51.9 23.3 51.9 51.9z"
></path>
</svg>
<div class="message-text">
<div class="thinking-indicator">
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
</div>`;
const incomingMessageDiv = createMessageElement(
messageContent,
"bot-message",
"thinking"
);
chatBody.appendChild(incomingMessageDiv);
chatBody.scrollTo({ top: chatBody.scrollHeight, behavior: "smooth" });
// Generate bot response
generateBotResponse(incomingMessageDiv);
}, 600);
};
// Handle file input change
fileInput.addEventListener("change", () => {
const file = fileInput.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
const base64String = e.target.result.split(",")[1];
// Store file data in userData
userData.file = {
data: base64String,
mime_type: file.type,
name: file.name,
};
// Display file attachment in the chat
const fileAttachment = document.createElement("div");
fileAttachment.classList.add("file-attachment");
fileAttachment.innerHTML = `
<span class="file-name">${file.name}</span>
<span class="file-size">${(file.size / 1024).toFixed(2)} KB</span>
`;
chatBody.appendChild(fileAttachment);
chatBody.scrollTo({ top: chatBody.scrollHeight, behavior: "smooth" });
};
reader.readAsDataURL(file);
});
// Handle Enter key press for sending messages
messageInput.addEventListener("keydown", (e) => {
const userMessage = e.target.value.trim();
if (e.key === "Enter" && userMessage && !e.shiftKey && window.innerWidth > 768) {
handleOutgoingMessage(e);
}
});
// Auto resize message input
messageInput.addEventListener("input", (e) => {
messageInput.style.height = `${initialInputHeight}px`;
messageInput.style.height = `${messageInput.scrollHeight}px`;
document.querySelector(".chat-form").style.borderRadius =
messageInput.scrollHeight > initialInputHeight ? "15px" : "32px";
});
// Emoji picker setup (optional)
const picker = new EmojiMart.Picker({
theme: "light",
skinTonePosition: "none",
preview: "none",
onEmojiSelect: (emoji) => {
const { selectionStart: start, selectionEnd: end } = messageInput;
messageInput.setRangeText(emoji.native, start, end, "end");
messageInput.focus();
},
onClickOutside: (e) => {
if (e.target.id === "emoji-picker") {
document.body.classList.toggle("show-emoji-picker");
} else {
document.body.classList.remove("show-emoji-picker");
}
},
});
document.querySelector(".chat-form").appendChild(picker);
sendMessageButton.addEventListener("click", (e) => handleOutgoingMessage(e));
document
.querySelector("#file-upload")
.addEventListener("click", () => fileInput.click());
chatbotToggler.addEventListener("click", () => {
document.body.classList.toggle("show-chatbot");
});
closeChatbot.addEventListener("click", () => {
document.body.classList.remove("show-chatbot");
});
const signUpButton=document.getElementById('signUpButton');
const signInButton=document.getElementById('signInButton');
const signInForm=document.getElementById('signIn');
const signUpForm=document.getElementById('signup');
signUpButton.addEventListener('click',function(){
signInForm.style.display="none";
signUpForm.style.display="block";
})
signInButton.addEventListener('click', function(){
signInForm.style.display="block";
signUpForm.style.display="none";
})