-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.js
68 lines (61 loc) · 2.01 KB
/
api.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
const chat = document.getElementById("chat");
const userInput = document.getElementById("user-input");
const sendButton = document.getElementById("send-button");
const loadingIcon = document.getElementById("loading-icon");
const apiUrl = "https://dls-ai.dlsdemo.com/";
// Function to add a user message to the chat
function addUserMessage(message) {
const userMessage = document.createElement("div");
userMessage.textContent = message;
userMessage.classList.add("message", "user");
chat.appendChild(userMessage);
}
// Function to add a bot message to the chat
function addBotMessage(message) {
const botMessage = document.createElement("div");
const md = window.markdownit(); // Create a new instance of markdown-it
botMessage.innerHTML = md.render(message);
botMessage.classList.add("message", "bot");
chat.appendChild(botMessage);
}
// Function to send a query to the API and display the response
async function sendQuery() {
const userQuery = userInput.value;
// Check if userQuery exceeds 500 characters
if (userQuery.length > 500) {
alert(
"Query is too long. Please limit your query to 500 characters or less."
);
return;
}
if (userQuery.trim() === "") return;
addUserMessage(userQuery);
userInput.value = "";
loadingIcon.style.display = "inline-block";
try {
console.log("UserQuery:", userQuery);
const response = await fetch(
`${apiUrl}?query=${encodeURIComponent(userQuery)}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
},
}
);
const data = await response.json();
const Response = data.response; // Assuming the API response has a "response" field
addBotMessage(Response);
} catch (error) {
console.error("Error:", error);
addBotMessage("Oops! Something went wrong.");
} finally {
loadingIcon.style.display = "none";
}
}
sendButton.addEventListener("click", sendQuery);
userInput.addEventListener("keypress", (event) => {
if (event.key === "Enter") {
sendQuery();
}
});