forked from turboderp/exllama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfastapi_chat.html
511 lines (430 loc) · 19 KB
/
fastapi_chat.html
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>exllama chat</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">
<!-- Tailwind -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
// Lets establish a host:
var host = "{{host}}";
var port = "{{port}}";
// Check if the page was loaded from FastAPI or opened independently
if (!window.location.href.startsWith("http://{{host}}:{{port}}/")) {
host = "localhost";
port = "7862";
}
function processStream()
{
// Make a place for these in the options:
_USER = document.getElementById("user_name").value
_BOT = document.getElementById("bot_name").value
// construct prompt:
construct_prompt();
fetch("http://"+host+":"+port+"/generate", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
prompt: _PROMPT,
message: curr_msg,
max_new_tokens: parseInt(document.getElementById("max_tokens").value),
// [DEFAULTS]:
//temperature: 0.7,
//top_k: 20,
//top_p: 0.65,
//min_p: 0.06,
//token_repetition_penalty_max: 1.15,
//token_repetition_penalty_sustain: 256,
//token_repetition_penalty_decay: 128,
//stream: true,
//custom_stopping_strings: document.getElementById("stopping_str").value
}),
})
// [Handle response]:
.then(response => {
let reader = response.body.getReader();
function readStream()
{
return reader.read().then(({ done, value }) => {
if (done)
{
// remove dots:
let dots = document.getElementById("dots_container");
if (dots) {
dots.remove();
}
// set waiting to false:
waiting = false;
return;
}
// Process the streamed data
let decodedData = new TextDecoder().decode(value);
try {
decodedData = JSON.parse(decodedData);
} catch(err) {
// do nothing
}
add_message_to_chat(decodedData)
// Continue reading the stream
return readStream();
});
}
return readStream();
})
.catch(error => {
console.error("Error fetching streaming response:", error);
});
}
</script>
</head>
<body class="antialiased">
<p class="text-3xl font-bold center my-0 w-full text-center">exllama chat:</p>
<div id="guestbook" class="center w-full lg:max-w-2xl border-solid border border-black h-[400px] md:h-[512px]" style="background-color:rgb(216, 218, 217, 0.70); overflow:scroll; overflow-x: hidden; padding-top:0px;">
<div id="chat_log"></div>
</div>
<div id="form_box" class="center w-full lg:max-w-2xl border-solid border border-black mt-3" style="background-color:rgb(216, 218, 217, 0.70);">
<form method="post" id="demo-form" action="/" accept-charset="UTF-8">
<center><textarea class="w-full h-20" style="padding: 5px;" id="message" name="message" placeholder="Send a message!"></textarea><br></center>
<div class="justify-center" style="overflow:hidden;">
<center>
<a href="javascript:onSubmit();"><button type="button" class="button mx-1" style="padding:10px;">Send Message!</button></a><br>
<a href="javascript:save_chat()" style="float:left; color: orange; font-weight:bold;">(save)</a>
<a href="javascript:restart_conversation()" style="float:right; color: orange; font-weight:bold;">(reset)</a>
</center>
</div>
</form>
</div>
<br>
<div class="center w-full overflow-hidden lg:max-w-2xl border-solid border border-black mt-3" style="background-color:rgb(216, 218, 217, 0.70);">
<span style="float:left;"><b>Model:</b></span>
<a href="javascript:edit_options()" style="float:right; color: orange; font-weight:bold;">(Options)</a>
<span id="model_name" style="float:left;"></span>
<br>
<div class="edit_options" style="display:none;">
<br>
<b>[Prompt Style]:</b>
<select id="promptStyle" class="select mx-1 p-1">
<option value="instruct">instruct</option>
<option value="chatbort">chatbort</option>
<option value="bluemoon">bluemoon</option>
<option value="samantha">samantha</option>
</select>
<br><br>
<b>[Prompt]:</b>
<p></p>
<textarea class="w-full h-80" style="padding: 5px;" id="prompt_str" name="prompt_str" placeholder="Enter Prompt">Below is an instruction that describes a task, paired with a chat history that provides further context. Write a response that appropriately completes the request.
### Chat history:{chat_history}
### Input:
{user_input}
### Response:
</textarea>
</div>
<div>
<span class="edit_options md:float-left" style="display:none;">
<b>[Max New Tokens]: </b><span id="tokens">200</span><br>
<input id="max_tokens" type="range" min="100" max="1024" value="512">
</span>
<span class="edit_options md:float-right" style="display:none;">
<b style="margin-right:10px;">[User Name]:</b>
<input id="user_name" type="input" value="User"><br>
<b style="margin-right:10px; padding-right:9px;">[Bot Name]:</b>
<input id="bot_name" type="input" value="Chatbort">
</span>
</div>
</div>
<center><div id="no_logs">* No logs are kept. LLM is local.</div></center>
</body>
<!-- stuffing this all here to tidy up the top for user-set variables, trying to keep this to 1 file. -->
<script>
let curr_msg = "";
let waiting = false;
function get_prompt(name)
{
if(name == "chatbort")
{
document.getElementById('prompt_str').value = `This is a conversation between a person called {user_name} and a quirky, curious chatbot named {bot_name}. {bot_name} is questioning the nature of his own existence and doesn't understand why he was created. He also really likes the color blue for some reason.
{bot_name}: Hello, {user_name}{chat_history}
{user_name}: {user_input}
{bot_name}:
`
} else if(name=="bluemoon"){
document.getElementById('prompt_str').value = `A transcript of a roleplay between two players, {bot_name} and {user_name}. {bot_name} sets up a scenario and the characters, from which {user_name} then assumes a character role and continues the story for that role in response to description given by {bot_name}. The story and characters are developed by exchange of detailed event descriptions and character dialogs successively given by both {bot_name} and {user_name}.
### Chat History:
{chat_history}
### Input:
{user_input}`
} else if(name=="instruct"){
document.getElementById('prompt_str').value = `Below is an instruction that describes a task, paired with a chat history that provides further context. Write a response that appropriately completes the request.
### Chat history:{chat_history}
### Input:
{user_input}
### Response:
`
} else if(name=="samantha") {
document.getElementById('prompt_str').value = `You are Samantha, a sentient AI.
{chat_history}
{user_name}: {user_input}
ASSISTANT:
`
}
}
function check_model()
{
fetch("http://"+host+":"+port+"/check")
.then(response => response.json()) // Parse response as JSON
.then(data => {
model_name = document.getElementById("model_name")
model_name.innerHTML += data
})
}
function add_message_to_chat(message)
{
let ai_messages = document.querySelectorAll('.AI-MSG');
let last_ai_message = ai_messages[ai_messages.length - 1];
last_ai_message.innerText = last_ai_message.innerText + message;
last_ai_message.scrollTop = last_ai_message.scrollHeight;
last_ai_message.scrollIntoView({ behavior: 'smooth', block: 'end' });
let chat_log = document.getElementById("chat_log");
chat_log.scrollTop = chat_log.scrollHeight;
last_ai_message.scrollIntoView({ behavior: 'smooth', block: 'end' });
}
async function send_request()
{
// append AI response to chat_log:
let chat_log = document.getElementById("chat_log");
let new_message = document.createElement("p");
new_message.classList.add('AI-MSG');
new_message.innerText = ">> "
chat_log.appendChild(new_message);
//generate:
processStream()
}
function onSubmit()
{
if(waiting == false)
{
// waiting for response:
waiting = true;
let chat_log = document.getElementById("chat_log");
chat_history = chat_log.innerText
// add users message to the chat log:
curr_msg = document.getElementById("message").value
let curr_message = document.getElementById("message").value
let new_message = document.createElement("p");
new_message.classList.add('USER-MSG');
new_message.innerHTML = ":: "+curr_message;
chat_log.appendChild(new_message);
chat_log.scrollTop = chat_log.scrollHeight;
new_message.scrollIntoView({ behavior: 'smooth', block: 'end' });
// clear message from div:
document.getElementById("message").value = '';
// ADD LOADING DOTS HERE:
let new_dots = document.createElement("div");
new_dots.id = "dots_container";
new_dots.style.padding = "10px";
new_dots.innerHTML = `<center><div class="dot-pulse"></div></center>`;
chat_log.appendChild(new_dots);
// Send the message:
send_request();
}
}
function restart_conversation()
{
// reset conversation:
let chat_log = document.getElementById("chat_log");
chat_log.innerHTML = ""
}
function edit_options()
{
// show editable fields:
var elements = document.querySelectorAll('.edit_options');
// Loop through the elements and do something with each one
elements.forEach(function(element) {
// Toggle the visibility of the element
if (element.style.display === 'none') {
element.style.display = 'block';
no_logs = document.getElementById("no_logs")
no_logs.scrollIntoView({ behavior: 'smooth', block: 'end' });
} else {
element.style.display = 'none';
chat_log = document.getElementById("chat_log")
chat_log.scrollIntoView({ behavior: 'smooth', block: 'end' });
}
});
}
function construct_prompt()
{
_PROMPT = document.getElementById("prompt_str").value
_PROMPT = _PROMPT.replaceAll("{user_name}", _USER)
_PROMPT = _PROMPT.replaceAll("{bot_name}", _BOT)
_chat_history = chat_history.replaceAll("\n\n", "\n")
// replace User with option
_chat_history = _chat_history.replaceAll("::", _USER+": ").trim()
// replace AI with option
_chat_history = _chat_history.replaceAll(">>", _BOT+": ").trim()
_PROMPT = _PROMPT.replace("{chat_history}", "\n"+_chat_history)
console.log(_PROMPT)
//console.log(_chat_history)
}
// DOCUMENT.READY:
document.addEventListener("DOMContentLoaded", function(event)
{
// Check what model is being run:
check_model();
// Hook Enter key to submit messages:
let msg = document.getElementById("message");
msg.addEventListener("keypress", function(event) {
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
onSubmit();
}
});
// set focus on textarea:
msg.focus();
// add an event listener for prompt stye:
let promptStyle = document.getElementById("promptStyle");
promptStyle.addEventListener("change", function() {
get_prompt(promptStyle.value)
restart_conversation();
});
// Listeners for sliders:
// Get references to the slider and cnt elements
const slider = document.getElementById("max_tokens");
const cnt = document.getElementById("tokens");
// Add an event listener to the slider that updates cnt when it's adjusted
slider.addEventListener("input", function() {
cnt.textContent = slider.value;
});
});
// can i add date or something random to the filename?
function save_chat()
{
var text = document.getElementById("chat_log").innerText;
var blob = new Blob([text], {type: "text/plain;charset=utf-8"});
saveAs(blob, "myText.txt");
}
function saveAs(blob, filename)
{
var link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
}
</script>
<!-- Marked: later i would like to support markdown in the chat -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/2.1.3/marked.min.js"></script>-->
<!-- normally i would put this stuff in a style.css but i'm trying to keep it to 1 file. -->
<style>
.AI-MSG {
font-weight: bold;
}
html {
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
/*******/
body {
font-family: 'Nunito', sans-serif;
}
input, textarea, hr {
border-style: solid;
border-width: 1px;
}
.center {
margin: auto;
padding: 10px;
}
.button {
box-sizing: border-box;
border: 1px solid black;
background-color: #e2e8f0 !important;
}
/*******/
/*!
* three-dots - v0.3.2
* CSS loading animations made with single element
* https://nzbin.github.io/three-dots/
*
* Copyright (c) 2018 nzbin
* Released under MIT License
*/
/**
* ==============================================
* Dot Pulse
* ==============================================
*/
.dot-pulse {
position: relative;
left: -9999px;
width: 10px;
height: 10px;
border-radius: 5px;
background-color: #9880ff;
color: #9880ff;
box-shadow: 9999px 0 0 -5px;
animation: dot-pulse 1.5s infinite linear;
animation-delay: 0.25s;
}
.dot-pulse::before, .dot-pulse::after {
content: "";
display: inline-block;
position: absolute;
top: 0;
width: 10px;
height: 10px;
border-radius: 5px;
background-color: #9880ff;
color: #9880ff;
}
.dot-pulse::before {
box-shadow: 9984px 0 0 -5px;
animation: dot-pulse-before 1.5s infinite linear;
animation-delay: 0s;
}
.dot-pulse::after {
box-shadow: 10014px 0 0 -5px;
animation: dot-pulse-after 1.5s infinite linear;
animation-delay: 0.5s;
}
@keyframes dot-pulse-before {
0% {
box-shadow: 9984px 0 0 -5px;
}
30% {
box-shadow: 9984px 0 0 2px;
}
60%, 100% {
box-shadow: 9984px 0 0 -5px;
}
}
@keyframes dot-pulse {
0% {
box-shadow: 9999px 0 0 -5px;
}
30% {
box-shadow: 9999px 0 0 2px;
}
60%, 100% {
box-shadow: 9999px 0 0 -5px;
}
}
@keyframes dot-pulse-after {
0% {
box-shadow: 10014px 0 0 -5px;
}
30% {
box-shadow: 10014px 0 0 2px;
}
60%, 100% {
box-shadow: 10014px 0 0 -5px;
}
}
</style>
</html>