-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatbot.js
171 lines (129 loc) · 5.27 KB
/
chatbot.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
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
chat_history = []
document.addEventListener("DOMContentLoaded", function () {
const chatBox = document.getElementById("chat-box");
const userInput = document.getElementById("user-input");
const sendBtn = document.getElementById("send-btn");
let message_count = 0
sendBtn.addEventListener("click", function () {
const question = userInput.value.trim();
if (question !== "") {
message_count += 1;
const userMessage = document.createElement("div");
userMessage.className = "message-box user";
const userContainer = document.createElement("div");
userContainer.className = "user";
const profilePic = document.createElement("div");
profilePic.className = "profile-pic";
const messageContent = document.createElement("div");
messageContent.className = "message";
messageContent.textContent = question;
userContainer.appendChild(messageContent);
userContainer.appendChild(profilePic);
userMessage.appendChild(userContainer);
const botMessage = `
<div class="message-box bot">
<div class="bot">
<div class="profile-pic"></div>
<div class="message" id="botmessage${message_count}">
<div class="loading"></div>
</div>
</div>
<div class="sources" id="botsources${message_count}"></div>
</div>
`;
chatBox.appendChild(userMessage);
chatBox.innerHTML += botMessage;
userInput.value = "";
userInput.style.height = "45px";
ask_gouvx(question, message_count);
}
});
userInput.addEventListener("keyup", function (event) {
if (event.key === "Enter") {
sendBtn.click();
}
});
});
function adjustRows(textarea) {
textarea.style.height = "45px";
textarea.style.height = (25 + textarea.scrollHeight) + "px"
}
function parse_response_metadata(metadata, message_number) {
[metada_json, other_text] = metadata.split("\n")
if (metada_json == null){
return other_text
}
const jsonData = JSON.parse(metada_json);
let lastbotsources = document.getElementById("botsources" + message_number);
const result = jsonData.map((item, index) => {
const { title, url } = item;
return `<a href="${url}" target="_blank">[${index + 1}] ${title}</a>`;
});
sources = result.join('<br>');
lastbotsources.innerHTML = sources
return other_text
}
function ask_gouvx(question, message_number) {
const url = 'https://gouvx-api-g26csh5qkq-ew.a.run.app/ask/';
const postData = new URLSearchParams({
q: question,
h: JSON.stringify(chat_history)
});
const loader = document.querySelector('.loading')
loader.classList.add('display')
fetch(url, {
method: 'POST',
body: postData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => {
const reader = response.body.getReader();
const textDecoder = new TextDecoder();
let system_reply = ""
return new ReadableStream({
async start(controller) {
const { done, value } = await reader.read();
let metadata = textDecoder.decode(value, { stream: true });
remaining_reply = parse_response_metadata(metadata, message_number)
//TODO make this a function
if (remaining_reply) {
let lastbotmessage = document.getElementById("botmessage" + message_number);
lastbotmessage.innerHTML += remaining_reply
}
while (true) {
const { done, value } = await reader.read();
if (done) {
controller.close();
break;
}
// Convert the chunk to a string and print it
let chunkText = textDecoder.decode(value, { stream: true });
system_reply += chunkText
chunkTextHTML = chunkText.replace("\n", "<br><br>")
let lastbotmessage = document.getElementById("botmessage" + message_number);
lastbotmessage.innerHTML += chunkTextHTML
controller.enqueue(value);
}
chat_history.push({
"role": "user",
"content": question
})
chat_history.push({
"role": "system",
"content": system_reply
})
}
});
})
.then(() => loader.remove())
.then(stream => new Response(stream))
.then(response => response.text())
.then(data => {
return data
})
.catch(error => {
console.error('Error:', error);
});
}