-
Notifications
You must be signed in to change notification settings - Fork 3
/
nilla.html
544 lines (461 loc) · 21.1 KB
/
nilla.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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
<!DOCTYPE html>
<head>
<title>Chat</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<style>
body {
font-family: Roboto,Lato,Arial;
line-height: 1.5;
font-size: 16px;
margin: 0;
padding: 0;
overflow: hidden;
}
header {
background: linear-gradient(to bottom right, #06c, #fc0);
}
header {
color: #eee;
padding: 12px;
font-size: 20px;
height: 45px;
font-family: "Open Sans"
}
#left {
float: left;
width: calc(60vw - 30px);
height: calc(100vh - 100px);
}
#right {
float: right;
width: 40%;
height: calc(100vh - 100px);
}
#left, #prompt, #list {
border: 1px solid grey;
padding: 6px;
overflow: auto
}
#list li:hover {
background: #ddd
}
#menu button {
font-family: Lato,arial;
border-radius: 3px;
border: none;
padding: 3px 6px
}
#right textarea {
display: block;
width: 96%;
margin: 3px auto;
background: #eee
}
.prompt {
color: #322;
background: #ccc;
padding: 6px;
}
.markdown code {
background: #f0f0f0;
color: navy;
border-radius: 6px;
padding: 2px;
}
.markdown pre {
background: #f0f0f0;
margin: 16px;
border: 1px solid #ddd;
padding: 8px;
border-radius: 6px;
}
.markdown blockquote {
background: #f0f0f0;
border-left: 6px solid grey;
padding: 8px
}
.markdown table {
margin: 12px;
border-collapse: collapse;
}
.markdown th {
border: 1px solid grey;
background: lightgrey;
padding: 6px;
}
.markdown td {
border: 1px solid grey;
padding: 6px;
}
.markdown tr:nth-child(even) {
background: #f0f0f0;
}
@media print {
#menu, #right {
display: none !important
}
#left {
position: relative;
width: 100%;
left: 0px;
top: 0px;
border: none;
height: auto;
overflow: hidden
}
.prompt {
border-bottom: 1px solid grey
}
}
@media screen and (max-width: 880px) {
#list, #message {
display: none !important
}
#right {
width: 100%;
height: auto;
}
#left {
width: 97%;
height: calc(100vh - 160px);
}
}
</style>
<header>
<div id=heading style="float:left">
Vanilla ChatGPT<br>
<span id=message style="color:yellow;font-size:10px">
<a href="https://github.com/casualwriter/vanilla-chatgpt" target=_NEW>github</a> @20230329
</span>
</div>
<div id=menu style="float:right;">
<button onclick="chat.logout()" title="remove API key">Logout</button>
<button onclick="chat.export()" title="export conversation">Export</button>
<button onclick="chat.showPrompts()" title="show prompts">Prompts</button>
<button id=btnSent accesskey=s onclick="chat.submit()" title="[Alt-S] submit prompt"><b>S</b>end</button>
</div>
</header>
<div id="content" style="margin:8px;color:#112;background:bed">
<div id="right">
<textarea id=prompt rows=3 placeholder="please input prompt here.."></textarea>
<div id="list" style="height:calc(100vh - 163px)">
<b>Samples of prompt</b>
<ul>
<li>A quote of today
<li>A table for 10 famous artists include name, DOB and style
<li>Create an article outline in markdown format for "teamwork"
<li>Create a dialogue discussing "the meaning of love"
<li>Introduce "vanilla chatGPT"
<li>Write a short story about "vanilla chatGPT"
<li>Discuss about the pros and cons of "vanilla js"
<li>Summarize the following content ...
</ul>
</div>
</div>
<div id="left">
<div id="main" style="padding:12px; max-width:960px">
<h3>Welcome to vanilla-chatgpt.</h3><p>
Please submit prompt by pressing
<label><input type="radio" name="submitkey" onclick="chat.hotkey='enter'" checked>[Enter]</label>
<label><input type="radio" name="submitkey" onclick="chat.hotkey='ctrl'">[Ctrl-Enter]</label>
<p>[Ctrl-P] to print, [Export] to export conversation [Logout] to remove API key
</div>
</div>
</div>
<script>
/*****************************************************************************
* casual-markdown - a lightweight regexp-base markdown parser with TOC support
* last updated on 2023/03/27, v0.91, some refinement for chatgpt markdown
*
* Copyright (c) 2022-2023, Casualwriter (MIT Licensed)
* https://github.com/casualwriter/casual-markdown
*****************************************************************************/
// define md object, and extent function (which is a dummy function)
const md = { yaml: {}, before: function (str) { return str }, after: function (str) { return str } }
// function for REGEXP to convert html tag. ie. <TAG> => <TAG*gt;
md.formatTag = function (html) { return html.replace(/</g, '<').replace(/\>/g, '>'); }
//===== format code-block, highlight remarks/keywords for code/sql
md.formatCode = function (match, title, block) {
// convert tag <> to < > tab to 3 space, support marker using ^^^
block = block.replace(/</g, '<').replace(/\>/g, '>')
block = block.replace(/\t/g, ' ').replace(/\^\^\^(.+?)\^\^\^/g, '<mark>$1</mark>')
// highlight comment and keyword based on title := none | sql | code
if (title.toLowerCase(title) == 'sql') {
block = block.replace(/^\-\-(.*)/gm, '<rem>--$1</rem>').replace(/\s\-\-(.*)/gm, ' <rem>--$1</rem>')
block = block.replace(/(\s?)(function|procedure|return|if|then|else|end|loop|while|or|and|case|when)(\s)/gim, '$1<b>$2</b>$3')
block = block.replace(/(\s?)(select|update|delete|insert|create|from|where|group by|having|set)(\s)/gim, '$1<b>$2</b>$3')
} else if ((title || 'none') !== 'none') {
block = block.replace(/^\/\/(.*)/gm, '<rem>//$1</rem>').replace(/\s\/\/(.*)/gm, ' <rem>//$1</rem>')
block = block.replace(/(\s?)(function|procedure|return|if|then|else|end|loop|while|or|and|case|when)(\s)/gim, '$1<b>$2</b>$3')
block = block.replace(/(\s?)(var|let|const|for|next|do|while|loop|continue|break|switch|try|catch|finally)(\s)/gim, '$1<b>$2</b>$3')
}
return '<pre title="' + title + '"><code>' + block + '</code></pre>'
}
//===== parse markdown string into HTML string (exclude code-block)
md.parser = function (mdstr) {
// apply yaml variables
for (var name in this.yaml) mdstr = mdstr.replace(new RegExp('\{\{\\s*' + name + '\\s*\}\}', 'gm'), this.yaml[name])
// table syntax
mdstr = mdstr.replace(/\n(.+?)\n.*?\-\-\s?\|\s?\-\-.*?\n([\s\S]*?)\n\s*?\n/g, function (m, p1, p2) {
var thead = p1.replace(/^\|(.+)/gm, '$1').replace(/(.+)\|$/gm, '$1').replace(/\|/g, '<th>')
var tbody = p2.replace(/^\|(.+)/gm, '$1').replace(/(.+)\|$/gm, '$1')
tbody = tbody.replace(/(.+)/gm, '<tr><td>$1</td></tr>').replace(/\|/g, '<td>')
return '\n<table>\n<thead>\n<th>' + thead + '\n</thead>\n<tbody>' + tbody + '\n</tbody></table>\n\n'
})
// horizontal rule => <hr>
mdstr = mdstr.replace(/^-{3,}|^\_{3,}|^\*{3,}$/gm, '<hr>').replace(/\n\n<hr\>/g, '\n<br><hr>')
// header => <h1>..<h5>
mdstr = mdstr.replace(/^##### (.*?)\s*#*$/gm, '<h5>$1</h5>')
.replace(/^#### (.*?)\s*#*$/gm, '<h4>$1</h4>')
.replace(/^### (.*?)\s*#*$/gm, '<h3>$1</h3>')
.replace(/^## (.*?)\s*#*$/gm, '<h2>$1</h2>')
.replace(/^# (.*?)\s*#*$/gm, '<h1>$1</h1>')
.replace(/^<h(\d)\>(.*?)\s*{(.*)}\s*<\/h\d\>$/gm, '<h$1 id="$3">$2</h$1>')
// inline code-block: `code-block` => <code>code-block</code>
mdstr = mdstr.replace(/``(.*?)``/gm, function (m, p) { return '<code>' + md.formatTag(p).replace(/`/g, '`') + '</code>' })
mdstr = mdstr.replace(/`(.*?)`/gm, '<code>$1</code>')
// blockquote, max 2 levels => <blockquote>{text}</blockquote>
mdstr = mdstr.replace(/^\>\> (.*$)/gm, '<blockquote><blockquote>$1</blockquote></blockquote>')
mdstr = mdstr.replace(/^\> (.*$)/gm, '<blockquote>$1</blockquote>')
mdstr = mdstr.replace(/<\/blockquote\>\n<blockquote\>/g, '\n<br>')
mdstr = mdstr.replace(/<\/blockquote\>\n<br\><blockquote\>/g, '\n<br>')
// image syntax: ![title](url) => <img alt="title" src="url" />
mdstr = mdstr.replace(/!\[(.*?)\]\((.*?) "(.*?)"\)/gm, '<img alt="$1" src="$2" $3 />')
mdstr = mdstr.replace(/!\[(.*?)\]\((.*?)\)/gm, '<img alt="$1" src="$2" width="90%" />')
// links syntax: [title "title"](url) => <a href="url" title="title">text</a>
mdstr = mdstr.replace(/\[(.*?)\]\((.*?) "new"\)/gm, '<a href="$2" target=_new>$1</a>')
mdstr = mdstr.replace(/\[(.*?)\]\((.*?) "(.*?)"\)/gm, '<a href="$2" title="$3">$1</a>')
mdstr = mdstr.replace(/([<\s])(https?\:\/\/.*?)([\s\>])/gm, '$1<a href="$2">$2</a>$3')
mdstr = mdstr.replace(/\[(.*?)\]\(\)/gm, '<a href="$1">$1</a>')
mdstr = mdstr.replace(/\[(.*?)\]\((.*?)\)/gm, '<a href="$2">$1</a>')
// unordered/ordered list, max 2 levels => <ul><li>..</li></ul>, <ol><li>..</li></ol>
mdstr = mdstr.replace(/^[\*+-][ .](.*)/gm, '<ul><li>$1</li></ul>')
mdstr = mdstr.replace(/^\d\d?[ .](.*)/gm, '<ol><li>$1</li></ol>')
mdstr = mdstr.replace(/^\s{2,6}[\*+-][ .](.*)/gm, '<ul><ul><li>$1</li></ul></ul>')
mdstr = mdstr.replace(/^\s{2,6}\d[ .](.*)/gm, '<ul><ol><li>$1</li></ol></ul>')
mdstr = mdstr.replace(/<\/[ou]l\>\n\n?<[ou]l\>/g, '\n')
mdstr = mdstr.replace(/<\/[ou]l\>\n<[ou]l\>/g, '\n')
// text decoration: bold, italic, underline, strikethrough, highlight
mdstr = mdstr.replace(/\*\*\*(\w.*?[^\\])\*\*\*/gm, '<b><em>$1</em></b>')
mdstr = mdstr.replace(/\*\*(\w.*?[^\\])\*\*/gm, '<b>$1</b>')
mdstr = mdstr.replace(/\*(\w.*?[^\\])\*/gm, '<em>$1</em>')
mdstr = mdstr.replace(/___(\w.*?[^\\])___/gm, '<b><em>$1</em></b>')
mdstr = mdstr.replace(/__(\w.*?[^\\])__/gm, '<u>$1</u>')
// mdstr = mdstr.replace(/_(\w.*?[^\\])_/gm, '<u>$1</u>') // NOT support!!
mdstr = mdstr.replace(/\^\^\^(.+?)\^\^\^/gm, '<mark>$1</mark>')
mdstr = mdstr.replace(/\^\^(\w.*?)\^\^/gm, '<ins>$1</ins>')
mdstr = mdstr.replace(/~~(\w.*?)~~/gm, '<del>$1</del>')
// line break and paragraph => <br/> <p>
mdstr = mdstr.replace(/ \n/g, '\n<br/>').replace(/\n\s*\n/g, '\n<p>\n')
// indent as code-block
mdstr = mdstr.replace(/^ {4,10}(.*)/gm, function (m, p) { return '<pre><code>' + md.formatTag(p) + '</code></pre>' })
mdstr = mdstr.replace(/^\t(.*)/gm, function (m, p) { return '<pre><code>' + md.formatTag(p) + '</code></pre>' })
mdstr = mdstr.replace(/<\/code\><\/pre\>\n<pre\><code\>/g, '\n')
// Escaping Characters
return mdstr.replace(/\\([`_~\*\+\-\.\^\\\<\>\(\)\[\]])/gm, '$1')
}
//===== parse markdown string into HTML content (cater code-block)
md.html = function (mdText) {
// replace \r\n to \n, and handle front matter for simple YAML
mdText = mdText.replace(/\r\n/g, '\n').replace(/^---+\s*\n([\s\S]*?)\n---+\s*\n/, md.formatYAML)
// handle code-block.
mdText = mdText.replace(/\n~~~/g, '\n```').replace(/\n``` *(.*?)\n([\s\S]*?)\n``` *\n/g, md.formatCode)
// split by "<code>", skip for code-block and process normal text
var pos1 = 0, pos2 = 0, mdHTML = ''
while ((pos1 = mdText.indexOf('<code>')) >= 0) {
pos2 = mdText.indexOf('</code>', pos1)
mdHTML += md.after(md.parser(md.before(mdText.substr(0, pos1))))
mdHTML += mdText.substr(pos1, (pos2 > 0 ? pos2 - pos1 + 7 : mdtext.length))
mdText = mdText.substr(pos2 + 7)
}
return '<div class="markdown">' + mdHTML + md.after(md.parser(md.before(mdText))) + '</div>'
}
//============= end of casual-markdown-parser===================
/*****************************************************************************
* vanilla-chatgpt.js - chat library for openai-chatgpt
* last updated on 2023/03/28, v0.60, basic chat, responsive, print-friendly, export.
*
* Copyright (c) 2023, Casualwriter (MIT Licensed)
* https://github.com/casualwriter/vanilla-chatgpt
*****************************************************************************/
const chat = (id) => window.document.getElementById(id);
// Set the API endpoint URL
chat.endPoint = "https://api.openai.com/v1/chat/completions";
chat.model = "gpt-3.5-turbo"
chat.body = { model: chat.model, temperature: 0.8 }
chat.history = []
// stream result from openai
chat.stream = function (prompt) {
chat.body.stream = true
chat.body.messages = [{ role: "user", content: prompt }]
chat.headers = { "Authorization": `Bearer ${chat.apiKey}`, "Content-Type": "application/json" }
chat.result = ''
chat.controller = new AbortController();
const signal = chat.controller.signal
for (let i = chat.history.length - 1; i >= 0 && i > (chat.history.length - 3); i--) {
chat.body.messages.unshift({ role: 'assistant', content: chat.history[i].result });
chat.body.messages.unshift({ role: 'user', content: chat.history[i].prompt });
}
fetch(chat.endPoint, { method: 'POST', headers: chat.headers, body: JSON.stringify(chat.body), signal })
.then(response => {
if (!response.ok) {
if (response.status == 401) throw new Error('401 Unauthorized, invalide API Key');
throw new Error('failed to get data, error status ' + response.status)
}
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
reader.read().then(function processText({ done, value }) {
if (done) return chat.oncomplete(chat.result);
const lines = (chat.value = value).split('\n');
for (let i in lines) {
if (lines[i].length === 0) continue; // ignore empty message
if (lines[i].startsWith(':')) continue; // ignore comment message
if (lines[i] === 'data: [DONE]') return chat.oncomplete(chat.result); // end of message
chat.json = JSON.parse(lines[i].substring(6));
if (chat.json.choices) {
chat.result += (chat.json.choices[0].delta.content || '')
}
}
chat.onmessage(chat.result)
return reader.read().then(processText);
})
}).catch(error => chat.onerror(error));
}
// default error handle
chat.onerror = (error) => { alert(error); };
// clear API key when logout
chat.logout = () => {
if (confirm('Logout and clear API Key?')) localStorage.clear();
}
// export conversation
chat.export = (fname) => {
const link = document.createElement('a');
link.href = 'data:text/plain;charset=utf-8,'
chat.history.forEach((x) => {
link.href += encodeURIComponent('### ' + x.prompt + '\n\n' + x.result + '\n\n')
});
link.download = fname || ('chat-' + new Date().toISOString().substr(0, 16)) + '.md';
link.click();
}
//================= main program ===================
// display result when receiving message
chat.onmessage = function (text) {
chat("message").innerHTML = 'receiving messages..'
chat("receiving").innerHTML = md.html(text + '<br><br>');
}
// show whole conversation when message completed
chat.oncomplete = (text) => {
let html1 = '', html2 = ''
chat("message").innerHTML = `(model: ${chat.model})`
chat.history.push({ prompt: chat.prompt, result: chat.result })
for (let i = 0; i < chat.history.length; i++) {
html1 += '<h4 class=prompt id=prompt' + i + ' ondblclick="chat.clipboard(' + i + ')" title="doubleclick to copy">'
html1 += chat.history[i].prompt + '</h4>\n' + chat.history[i].result + '\n\n'
html2 += '<li onclick="location=this.title" title="#prompt' + i + '">' + chat.history[i].prompt
}
chat("main").innerHTML = md.html(html1 + '<br><br>')
chat("list").innerHTML = html2
chat("left").scrollTop = chat("left").scrollHeight;
chat('prompt').select()
chat('prompt').focus();
chat("btnSent").innerHTML = '<b>S</b>end'
}
// abort fetch request.
chat.abort = () => {
chat.controller.abort()
chat("receiving").innerHTML += '\n<font color=red>Message Aborted!</font>'
chat("receiving").id = 'abort';
};
// submit prompt
chat.submit = () => {
if (chat("btnSent").innerText === 'Stop..') {
chat.abort()
chat("btnSent").innerText = 'Send'
} else {
chat.stream(chat.prompt = chat('prompt').value)
chat("main").innerHTML += '<h4 class=prompt>' + chat.prompt + '</h4>\n<div id=receiving>Receiving....</div>'
chat("left").scrollTop = chat("left").scrollHeight;
chat("btnSent").innerText = 'Stop..'
}
}
// show default prompt list
chat.showPrompts = () => {
chat('list').innerHTML = chat.prompts
document.querySelectorAll('#list li').forEach((element) => {
element.addEventListener('click', (event) => {
chat('prompt').value = element.innerText
chat('prompt').focus();
});
})
};
chat.clipboard = (i) => {
navigator.clipboard.writeText('### ' + chat.history[i].prompt + '\n\n' + chat.history[i].result)
chat("message").innerText = 'dialogue has been copied to clipboard'
}
// prompt for API key if not found in localStorage
window.onload = () => {
chat.apiKey = localStorage.getItem('OPENAI_API_KEY');
if (!chat.apiKey || chat.apiKey.length < 10) {
chat.apiKey = prompt("Please input Secret API key (will store in local.storage)", "sk-");
localStorage.setItem('OPENAI_API_KEY', chat.apiKey)
}
chat.prompts = chat('list').innerHTML
chat.showPrompts()
chat('prompt').focus();
}
// add submit hot-key of ctrl-enter
document.addEventListener('keydown', function (event) {
if (event.key === 'Enter' && (chat.hotkey != 'ctrl' || event.ctrlKey)) {
if (chat("btnSent").innerText === 'Send') {
event.preventDefault(); chat.submit();
}
}
});
const recognition = (input, btn, lang = 'en-US') => {
var SpeechRecognition = SpeechRecognition || webkitSpeechRecognition;
let recognition = new SpeechRecognition();
recognition.lang = lang;
input.addEventListener('click', e => e.detail === 2 ? recognition.start() : '');
recognition.onresult = e => {
input.value = e.results[0][0].transcript;
if (input.value.length && btn && btn.innerText === 'Send') chat.submit();
}
recognition.onspeechend = () => recognition.stop();
}
recognition(chat('prompt'), chat("btnSent"));
const speaker = (lang = 'en-AU', rate = 1.2) => {
let ss = speechSynthesis, speaking = false;
document.body.addEventListener('click', e => {
if (e.target.tagName === "TEXTAREA") return;
if (e.detail === 2) {
var utter = new SpeechSynthesisUtterance();
ss.cancel();
const sel = window.getSelection();
let offset = sel.baseOffset || sel.anchorOffset;
let node = sel.extentNode || sel.focusNode;
let arr = [node.textContent.substr(offset)]
node = node.parentNode;
if (node.tagName === "P" || node.tagName === "LI") {
while (node = node.nextSibling) {
if (node.nodeType === 3) continue;
arr.push(node.textContent);
}
}
utter.text = arr.join('\n');
utter.lang = lang; utter.rate = rate;
ss.speak(utter);
speaking = true;
}
else if (speaking) {
ss.pause();
speaking = false;
}
else if (ss.paused) {
ss.resume();
speaking = true;
}
});
}
speaker();
</script>