-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathchat.html
More file actions
633 lines (610 loc) · 34.9 KB
/
Copy pathchat.html
File metadata and controls
633 lines (610 loc) · 34.9 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
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Ctext y='.9em' font-size='90'%3E%E2%9A%A1%3C/text%3E%3C/svg%3E" />
<title>bitgpu - 1-bit LLM chat, entirely in your browser</title>
<style>
/* ── tokens: warm stone ground, circuit-copper accent. Light is the default; dark is an
explicit choice via the toggle (persisted), never inferred from the OS. ── */
:root {
color-scheme: light;
--bg: #faf9f7; --fg: #1c1917; --muted: #79716b; --card: #ffffff; --line: #e8e4df;
--accent: #b4530a; --accent-hover: #9c4708; --accent-fg: #ffffff;
--user: #f6ede2; --tool: #fbf7f1; --danger: #b91c1c; --ok: #15803d;
--ring: rgba(180, 83, 10, .28);
--shadow: 0 1px 2px rgba(28, 25, 23, .05), 0 2px 8px rgba(28, 25, 23, .04);
--mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
}
:root[data-theme="dark"] {
color-scheme: dark;
--bg: #14110f; --fg: #ece7e2; --muted: #a29a92; --card: #1e1a17; --line: #302b26;
--accent: #e89a4e; --accent-hover: #f0ab66; --accent-fg: #241505;
--user: #33281b; --tool: #1a1613; --danger: #f87171; --ok: #4ade80;
--ring: rgba(232, 154, 78, .35);
--shadow: 0 1px 2px rgba(0, 0, 0, .35), 0 2px 10px rgba(0, 0, 0, .25);
}
* { box-sizing: border-box; }
html, body { height: 100dvh; }
body {
font: 15px/1.55 system-ui, -apple-system, "Segoe UI", sans-serif;
background: var(--bg); color: var(--fg); margin: 0;
display: flex; flex-direction: column;
-webkit-font-smoothing: antialiased;
}
/* ── header ── */
header { display: flex; align-items: baseline; gap: 10px; padding: 12px 18px; border-bottom: 1px solid var(--line); background: var(--card); }
header .title { font: 600 15px/1 var(--mono); letter-spacing: -.02em; }
header .title::before { content: '▚ '; color: var(--accent); }
header .tag { font-size: 12px; color: var(--muted); }
header .spacer { flex: 1; }
a { color: var(--accent); text-decoration: none; }
a:hover { text-decoration: underline; }
/* ── controls ── */
button, select {
font: inherit; border-radius: 9px; border: 1px solid var(--line);
background: var(--card); color: var(--fg); padding: 8px 13px; cursor: pointer;
transition: border-color .12s, background .12s;
}
button:hover:not(:disabled), select:hover { border-color: var(--muted); }
button.primary { background: var(--accent); color: var(--accent-fg); border-color: var(--accent); font-weight: 600; }
button.primary:hover:not(:disabled) { background: var(--accent-hover); border-color: var(--accent-hover); }
button.icon { padding: 8px 10px; line-height: 1; }
button:disabled { opacity: .45; cursor: default; }
button:focus-visible, select:focus-visible, input:focus-visible, textarea:focus-visible, label.chk:has(input:focus-visible) {
outline: 2px solid var(--ring); outline-offset: 1px;
}
.wrap { width: 100%; max-width: 800px; margin: 0 auto; padding: 0 16px; }
.controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; padding: 14px 0 6px; }
.controls .right { margin-left: auto; display: flex; gap: 8px; align-items: center; }
label.chk {
display: inline-flex; gap: 6px; align-items: center; font-size: 13px; color: var(--muted);
cursor: pointer; user-select: none; border: 1px solid var(--line); border-radius: 999px;
padding: 6px 12px; background: var(--card); transition: border-color .12s, color .12s;
}
label.chk:hover { border-color: var(--muted); }
label.chk:has(input:checked) { color: var(--accent); border-color: var(--accent); background: var(--tool); }
label.chk input { accent-color: var(--accent); margin: 0; }
#status { font-size: 13px; color: var(--muted); min-height: 20px; padding: 4px 0 8px; }
#status b { font-family: var(--mono); font-size: 12.5px; }
#status .err { color: var(--danger); }
#status .ok { color: var(--ok); }
progress { width: 100%; height: 4px; accent-color: var(--accent); border-radius: 2px; }
/* ── chat log ── */
main { flex: 1; overflow-y: auto; overscroll-behavior: contain; }
#log { display: flex; flex-direction: column; gap: 10px; padding: 10px 0 24px; }
.msg { padding: 10px 14px; border-radius: 14px; border: 1px solid var(--line); background: var(--card); white-space: pre-wrap; overflow-wrap: anywhere; box-shadow: var(--shadow); }
.msg.user { background: var(--user); border-color: transparent; align-self: flex-end; max-width: 85%; border-bottom-right-radius: 5px; }
.msg.assistant { align-self: flex-start; max-width: 95%; border-bottom-left-radius: 5px; }
.msg.assistant.pending::after { content: '▍'; color: var(--accent); animation: blink 1s steps(1) infinite; }
.msg.toolcall { align-self: flex-start; max-width: 95%; font: 12.5px/1.6 var(--mono); color: var(--muted); background: var(--tool); box-shadow: none; border-style: dashed; }
.msg.toolcall b { color: var(--accent); font-weight: 600; }
@keyframes blink { 50% { opacity: 0; } }
.msg .meta { display: block; font: 11px/1.5 var(--mono); font-variant-numeric: tabular-nums; color: var(--muted); margin-top: 7px; }
/* markdown-rendered assistant bubbles (plain bubbles keep pre-wrap) */
.msg.md { white-space: normal; }
.msg.md > :first-child { margin-top: 0; }
.msg.md > :last-child:not(.meta) { margin-bottom: 0; }
.msg.md p, .msg.md ul, .msg.md ol, .msg.md pre, .msg.md blockquote, .msg.md table { margin: 8px 0; }
.msg.md h3, .msg.md h4, .msg.md h5 { margin: 12px 0 6px; line-height: 1.3; }
.msg.md h3 { font-size: 16px; } .msg.md h4 { font-size: 14.5px; } .msg.md h5 { font-size: 13.5px; }
.msg.md ul, .msg.md ol { padding-left: 22px; }
.msg.md li { margin: 3px 0; }
.msg.md code { font: 12.5px/1.6 var(--mono); background: var(--tool); border: 1px solid var(--line); border-radius: 4px; padding: 0 5px; }
.msg.md pre { background: var(--tool); border: 1px solid var(--line); border-radius: 8px; padding: 10px 12px; overflow-x: auto; }
.msg.md pre code { background: none; border: 0; padding: 0; white-space: pre; }
.msg.md blockquote { border-left: 3px solid var(--accent); padding: 2px 12px; color: var(--muted); }
.msg.md table { border-collapse: collapse; display: block; overflow-x: auto; max-width: 100%; font-variant-numeric: tabular-nums; }
.msg.md th, .msg.md td { border: 1px solid var(--line); padding: 4px 10px; text-align: left; }
.msg.md th { background: var(--tool); }
.msg.md a { color: var(--accent); }
.msg.md hr { border: 0; border-top: 1px solid var(--line); margin: 10px 0; }
.empty { text-align: center; color: var(--muted); font-size: 13.5px; padding: 44px 24px; max-width: 62ch; margin: 0 auto; }
.empty b { color: var(--fg); }
/* ── composer ── */
footer { border-top: 1px solid var(--line); background: var(--card); padding: 10px 0 calc(10px + env(safe-area-inset-bottom)); }
.inputrow { display: flex; gap: 8px; }
input[type="text"] {
flex: 1; padding: 11px 14px; border-radius: 11px; border: 1px solid var(--line);
background: var(--bg); color: var(--fg); font: inherit; font-size: 16px; min-width: 0;
}
input[type="text"]:focus { outline: 2px solid var(--ring); outline-offset: -1px; border-color: transparent; }
.storage { font: 12px/1.5 var(--mono); font-variant-numeric: tabular-nums; color: var(--muted); display: flex; flex-wrap: wrap; gap: 10px; align-items: center; padding-top: 6px; }
.storage button { font: inherit; font-size: 12px; padding: 3px 9px; }
/* ── schema editor ── */
#schemaBox { display: none; padding: 8px 0 2px; }
#schemaBox.show { display: block; }
#schemaBox .hint { font-size: 12px; color: var(--muted); margin-bottom: 4px; }
#schema { width: 100%; min-height: 96px; font: 12.5px/1.5 var(--mono); border: 1px solid var(--line); border-radius: 9px; background: var(--card); color: var(--fg); padding: 8px 10px; resize: vertical; }
/* ── small screens ── */
@media (max-width: 640px) {
header { padding: 10px 14px; }
header .tag { display: none; }
.controls select { flex: 1 1 100%; }
.msg.user, .msg.assistant, .msg.toolcall { max-width: 100%; }
.empty { padding: 28px 8px; }
}
@media (prefers-reduced-motion: reduce) {
* { animation: none !important; transition: none !important; }
.msg.assistant.pending::after { opacity: 1; }
}
</style>
</head>
<body>
<header>
<span class="title">bitgpu chat</span>
<span class="tag">1-bit LLM · WebGPU · no server</span>
<span class="spacer"></span>
<a href="https://github.com/stfurkan/bitgpu" target="_blank" rel="noreferrer">GitHub</a>
<button id="theme" class="icon" title="Toggle light/dark">◐</button>
</header>
<div class="wrap">
<div class="controls">
<select id="model">
<option value="bonsai-1.7b-gguf">Bonsai 1.7B · ~240 MB</option>
<option value="bonsai-4b-gguf">Bonsai 4B · ~570 MB</option>
<option value="bonsai-8b-gguf">Bonsai 8B · ~1.2 GB</option>
<option value="bonsai-27b-gguf">Bonsai 27B · hybrid · ~3.8 GB · 16 GB+</option>
<option value="bonsai-1.7b">Bonsai 1.7B · ONNX · ~290 MB</option>
<option value="bonsai-4b">Bonsai 4B · ONNX · ~660 MB</option>
<option value="bonsai-8b">Bonsai 8B · ONNX · ~1.3 GB</option>
</select>
<button id="load" class="primary">Load model</button>
<label class="chk"><input type="checkbox" id="jsonMode" /> JSON mode</label>
<label class="chk" title="The model can call a calculator and a clock that run inside this page - the call format is grammar-enforced, so it can never be malformed."><input type="checkbox" id="toolMode" /> Tools</label>
<div class="right">
<button id="clear" disabled>Clear chat</button>
</div>
</div>
<div id="schemaBox">
<div class="hint">Optional JSON Schema (subset: type, properties, required, additionalProperties, items, minItems/maxItems, enum, minLength/maxLength, integer minimum/maximum, discriminated oneOf) - the reply <b>cannot</b> violate it. Clear to allow any valid JSON.</div>
<textarea id="schema" spellcheck="false">{
"type": "array", "minItems": 5, "maxItems": 5,
"items": { "type": "object", "required": ["name", "population"], "additionalProperties": false,
"properties": { "name": { "type": "string" }, "population": { "type": "number" } } }
}</textarea>
</div>
<div id="status">idle - pick a model and press Load. The model runs on <b>your</b> GPU; nothing leaves this page.</div>
<progress id="prog" value="0" max="1" hidden></progress>
<div class="storage">
<span id="usage"></span>
<button id="wipe" hidden>Remove downloaded models</button>
</div>
</div>
<main><div class="wrap"><div id="log">
<div class="empty" id="empty">
<b>Everything here is local.</b><br />
Weights download once (cached in your browser), then the model generates on your GPU -
offline-capable, private by construction.<br /><br />
Try <i>"Explain WebGPU in two sentences"</i> - or flip on <b>JSON mode</b> and ask for
<i>"the 5 largest cities in Turkey as an array of {name, population} objects"</i> -
the output is structurally guaranteed to parse.<br /><br />
Or flip on <b>Tools</b> and ask <i>"What is 12.5% of 4,832? Use the calculator."</i> -
the model calls a calculator that runs inside this page, and the call is grammar-enforced
so it can never be malformed. Every reply also shows a <b>confidence</b> score computed
from the model's own token probabilities.<br /><br />
Conversations <b>survive reloads</b>: close the tab, come back, load the same model - the
chat continues instantly, because the model's working memory (the KV cache) is saved and
restored, not re-computed.
</div>
</div></div></main>
<footer><div class="wrap">
<form id="form">
<div class="inputrow">
<input type="text" id="prompt" placeholder="Load a model first..." autocomplete="off" disabled />
<button id="send" class="primary" disabled>Send</button>
</div>
</form>
</div></footer>
<script type="module">
// Pinned published package from a CDN: this single file runs on GitHub Pages, any static
// host, or saved locally. For development against a checkout use examples/verify.html.
const BITGPU = 'https://esm.sh/bitgpu@0.19.1';
const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@main/models';
const HF = (r) => `https://huggingface.co/onnx-community/${r}/resolve/main`;
const PRISM = (r) => `https://huggingface.co/prism-ml/${r}/resolve/main`;
// GGUF first: same weights as the ONNX exports (sign-bit streams are bit-identical),
// a little smaller on the wire. Tokenizers come from the ONNX repos either way (the
// GGUF repos don't host tokenizer.json).
const MODELS = {
'bonsai-1.7b-gguf': { data: `${PRISM('Bonsai-1.7B-gguf')}/Bonsai-1.7B-Q1_0.gguf`, tok: HF('Bonsai-1.7B-ONNX'), aux: 'Bonsai-1.7B-Q1_0.aux.bin' },
'bonsai-4b-gguf': { data: `${PRISM('Bonsai-4B-gguf')}/Bonsai-4B-Q1_0.gguf`, tok: HF('Bonsai-4B-ONNX'), aux: 'Bonsai-4B-Q1_0.aux.bin' },
'bonsai-8b-gguf': { data: `${PRISM('Bonsai-8B-gguf')}/Bonsai-8B-Q1_0.gguf`, tok: HF('Bonsai-8B-ONNX'), aux: 'Bonsai-8B-Q1_0.aux.bin' },
// Qwen3.5 hybrid 27B: committed manifest + aux like the others; weights stream from HF, tokenizer
// from the -unpacked repo (the GGUF repo ships none). ~3.8 GB - wants 16 GB+. `gen` overrides the
// sampling with PrismML's recommended settings for this model (temp 0.5 / top_p 0.85 / top_k 20).
'bonsai-27b-gguf': { data: `${PRISM('Bonsai-27B-gguf')}/Bonsai-27B-Q1_0.gguf`, tok: PRISM('Bonsai-27B-unpacked'), aux: 'Bonsai-27B-Q1_0.aux.bin', gen: { temperature: 0.5, topP: 0.85, topK: 20 } },
'bonsai-1.7b': { data: `${HF('Bonsai-1.7B-ONNX')}/onnx/model_q1.onnx_data`, tok: HF('Bonsai-1.7B-ONNX'), aux: 'bonsai.aux.bin' },
'bonsai-4b': { data: `${HF('Bonsai-4B-ONNX')}/onnx/model_q1.onnx_data`, tok: HF('Bonsai-4B-ONNX'), aux: 'model_q1.aux.bin' },
'bonsai-8b': { data: `${HF('Bonsai-8B-ONNX')}/onnx/model_q1.onnx_data`, tok: HF('Bonsai-8B-ONNX'), aux: 'model_q1.aux.bin' },
};
const $ = (id) => document.getElementById(id);
const status = (html) => { $('status').innerHTML = html; };
// ── theme: LIGHT by default (deliberate, not OS-inferred); the toggle flips to dark and the
// choice is persisted across visits ──
const applyTheme = (t) => { t === 'dark' ? document.documentElement.setAttribute('data-theme', 'dark') : document.documentElement.removeAttribute('data-theme'); };
applyTheme(localStorage.getItem('bitgpu-theme'));
$('theme').onclick = () => {
const next = (localStorage.getItem('bitgpu-theme') || 'light') === 'dark' ? 'light' : 'dark';
localStorage.setItem('bitgpu-theme', next);
applyTheme(next);
};
// ── model cache: Cache Storage via bitgpu's fetch overrides, so "downloaded once" is real ──
const CACHE = 'bitgpu-models-v1';
async function cachedResponse(url) {
const c = await caches.open(CACHE);
const hit = await c.match(url);
if (hit) return hit;
const res = await fetch(url);
if (!res.ok) throw new Error(`fetch ${url} failed: HTTP ${res.status}`);
c.put(url, res.clone()).catch(() => {}); // streams to cache alongside consumption; quota errors are non-fatal
return res;
}
const fetchJson = async (u) => (await cachedResponse(u)).json();
const fetchArrayBuffer = async (u) => (await cachedResponse(u)).arrayBuffer();
const fetchStream = async (u) => (await cachedResponse(u)).body;
async function refreshStorage() {
try {
const est = await navigator.storage.estimate();
const fmt = (b) => { const mb = b / 1048576; return mb >= 1024 ? (mb / 1024).toFixed(1) + ' GB' : mb.toFixed(0) + ' MB'; };
const has = (await (await caches.open(CACHE)).keys()).length > 0;
const persisted = (await navigator.storage.persisted?.()) ?? false;
$('usage').textContent = has
? `~${fmt(est.usage ?? 0)} of models cached${est.quota ? ` (of ~${fmt(est.quota)} available)` : ''}${persisted ? ' · persistent' : ''}`
: 'no models downloaded yet';
$('wipe').hidden = !has;
} catch { $('usage').textContent = ''; }
}
$('wipe').onclick = async () => {
await caches.delete(CACHE);
await refreshStorage();
status('downloaded models removed - the next load streams from the network again.');
};
refreshStorage();
// ── session persistence: chat.save() snapshots (messages + the KV cache itself) into
// IndexedDB after each turn; the next load of the same model restores the conversation
// with NO re-prefill - the model's memory comes back as bytes ──
const idbOp = (mode, fn) => new Promise((resolve, reject) => {
const open = indexedDB.open('bitgpu-demo', 1);
open.onupgradeneeded = () => open.result.createObjectStore('sessions');
open.onerror = () => reject(open.error);
open.onsuccess = () => {
const db = open.result;
const rq = fn(db.transaction('sessions', mode).objectStore('sessions'));
rq.onsuccess = () => { db.close(); resolve(rq.result); };
rq.onerror = () => { db.close(); reject(rq.error); };
};
});
let sessKey = null;
const saveSession = () => { // fire-and-forget; quota/serialization errors are non-fatal
if (!chat || !sessKey) return;
const msgs = JSON.parse(JSON.stringify(messages));
chat.save().then((snap) => snap && idbOp('readwrite', (s) => s.put({ snap, msgs }, sessKey))).catch(() => {});
};
const dropSession = () => { if (sessKey) idbOp('readwrite', (s) => s.delete(sessKey)).catch(() => {}); };
// ── load ──
let engine = null, chat = null, busy = false, abort = null;
const messages = [];
async function markCached() {
const c = await caches.open(CACHE);
for (const opt of $('model').options) {
const m = MODELS[opt.value];
const hit = await c.match(m.data);
const base = opt.textContent.replace(/ · downloaded$/, '');
opt.textContent = hit ? `${base} · downloaded` : base;
}
}
markCached();
$('load').onclick = async () => {
const key = $('model').value, m = MODELS[key];
$('load').disabled = true; $('model').disabled = true;
// Ask for durable storage so the browser will not silently evict multi-GB model weights
// under storage pressure (best-effort; browsers may grant automatically or prompt).
navigator.storage?.persist?.().catch(() => {});
try {
status('loading bitgpu...');
const [{ createEngine, WebGPUUnavailableError }, { createChat }] = await Promise.all([import(BITGPU), import(`${BITGPU}/chat`)]);
status(`loading <b>${key}</b> - first time streams from the Hugging Face Hub, afterwards it comes from your browser's cache...`);
$('prog').hidden = false;
try {
engine = await createEngine({
manifestUrl: `${REPO}/${key}/manifest.json`,
auxUrl: `${REPO}/${key}/${m.aux}`,
dataUrl: m.data,
// q8 KV: quarter-of-f32 cache memory on ANY adapter (no shader-f16 needed), which
// pays for the 4096-token window and keeps session snapshots small.
kvCache: 'q8',
// f16 activation-compute: auto-falls-back to f32 where shader-f16 is missing; a real
// decode win on packed-f16 GPUs (NVIDIA/AMD), ~neutral on Apple. Bit-exact, safe to default.
activation: 'f16',
maxSeqLen: 4096,
fetchJson, fetchArrayBuffer, fetchStream,
onProgress: (p) => { if (p.total) $('prog').value = p.loaded / p.total; },
});
} catch (e) {
if (e instanceof WebGPUUnavailableError) {
status('<span class="err">WebGPU is not available here. Try Chrome or Edge on desktop, or Safari 26+.</span>');
$('load').disabled = false; $('model').disabled = false; $('prog').hidden = true;
return;
}
throw e;
}
chat = await createChat(engine, {
tokenizerJsonUrl: `${m.tok}/tokenizer.json`,
tokenizerConfigUrl: `${m.tok}/tokenizer_config.json`,
fetchJson,
});
$('prog').hidden = true;
const cap = engine.capabilities;
status(`<span class="ok">ready</span> - ${key} on ${cap.adapter.vendor ?? 'your GPU'} (${cap.useSubgroups ? 'subgroups' : 'fallback'} path, kv ${cap.kvCache}, window ${cap.maxSeqLen} tokens)`);
// restore the previous session for this model, KV cache included - no re-prefill
sessKey = `${key}:${cap.kvCache}`;
try {
const sess = await idbOp('readonly', (s) => s.get(sessKey));
if (sess?.snap && sess.msgs?.length) {
await chat.restore(sess.snap);
messages.push(...sess.msgs);
let pendingCalls = [];
for (const m of sess.msgs) {
if (m.role === 'user') bubble('user', m.content);
else if (m.role === 'assistant') { pendingCalls = [...(m.tool_calls ?? [])]; if (m.content) { const b = bubble('assistant', ''); b.classList.add('md'); setMd(b, m.content); } }
else if (m.role === 'tool') {
const call = pendingCalls.shift();
const tb = bubble('toolcall', '');
tb.innerHTML = '⚙ <b></b> → ';
tb.querySelector('b').textContent = call ? `${call.name}(${JSON.stringify(call.arguments)})` : 'tool';
tb.appendChild(document.createTextNode(m.content));
}
}
status(`<span class="ok">session restored</span> - ${key} picks up where you left off: the model's memory came back from IndexedDB, the next turn just appends (no re-prefill).`);
}
} catch { dropSession(); } // stale/mismatched snapshot (e.g. new engine version): start fresh
$('prompt').disabled = false; $('send').disabled = false; $('clear').disabled = false;
setPlaceholder(); $('prompt').focus();
markCached(); refreshStorage();
} catch (e) {
$('prog').hidden = true;
status(`<span class="err">load failed: ${e.message}</span>`);
$('load').disabled = false; $('model').disabled = false;
}
};
// ── demo tools: executed by THIS PAGE (the engine only returns a validated call) ──
const DEMO_TOOLS = [
{ type: 'function', function: {
name: 'calculate',
description: 'Evaluate a pure arithmetic expression using only numbers and + - * / ( ). Example: for 12.5% of 4832 pass "4832 * 0.125".',
parameters: { type: 'object', required: ['expression'], additionalProperties: false,
properties: { expression: { type: 'string', minLength: 1, maxLength: 80 } } },
} },
{ type: 'function', function: {
name: 'get_time',
description: 'Get the current local date and time.',
parameters: { type: 'object', additionalProperties: false, properties: {} },
} },
];
function runDemoTool(call) {
if (call.name === 'get_time') return new Date().toString();
if (call.name === 'calculate') {
let ex = String(call.arguments.expression ?? '').replace(/,/g, '');
// accept the common "X% of Y" phrasing, then require pure arithmetic
ex = ex.replace(/([\d.]+)\s*%\s*(?:of\s*)?/gi, '($1/100)*').replace(/\*\s*$/, '');
if (!/^[\d\s+\-*/().]+$/.test(ex)) return 'error: only numbers, + - * / and parentheses are allowed';
try {
const v = Function(`"use strict"; return (${ex})`)();
return Number.isFinite(v) ? String(v) : 'error: not a finite number';
} catch { return 'error: could not evaluate the expression'; }
}
return `error: unknown tool ${call.name}`;
}
// ── chat ──
const setPlaceholder = () => {
const json = $('jsonMode').checked, tools = $('toolMode').checked;
$('prompt').placeholder = json ? 'Ask for data: "the 5 largest cities in Turkey with populations"'
: tools ? 'Try: "What is 12.5% of 4,832? Use the calculator."'
: 'Say something...';
$('schemaBox').classList.toggle('show', json);
};
// JSON mode and tools are mutually exclusive (a constrained-JSON reply has no room for calls)
$('jsonMode').onchange = () => { if ($('jsonMode').checked) $('toolMode').checked = false; setPlaceholder(); };
$('toolMode').onchange = () => { if ($('toolMode').checked) $('jsonMode').checked = false; setPlaceholder(); };
// ── minimal streaming markdown renderer ──
// Everything is HTML-escaped FIRST, then markdown structure is layered on top - the model can
// never inject markup. Re-rendered from the full accumulated text on every streamed delta
// (bubbles are small, so a full rebuild per token is cheap and keeps the parser stateless);
// an unclosed ``` fence mid-stream just renders as an open code block until its close arrives.
const esc = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
const inlineMd = (s) => {
const codes = [];
s = s.replace(/`([^`\n]+)`/g, (_, c) => `\x00${codes.push(c) - 1}\x00`); // shield code spans
s = s.replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>')
.replace(/(^|[\s(])\*(\S(?:[^*\n]*\S)?)\*/g, '$1<i>$2</i>')
.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
return s.replace(/\x00(\d+)\x00/g, (_, i) => `<code>${codes[+i]}</code>`);
};
const md = (src) => {
const lines = esc(src).split('\n');
let html = '', i = 0, para = [];
const flush = () => { if (para.length) { html += `<p>${para.map(inlineMd).join('<br>')}</p>`; para = []; } };
while (i < lines.length) {
const l = lines[i];
if (/^\s*```/.test(l)) {
flush();
const buf = [];
for (i++; i < lines.length && !/^\s*```/.test(lines[i]);) buf.push(lines[i++]);
i++;
html += `<pre><code>${buf.join('\n')}</code></pre>`;
continue;
}
const h = l.match(/^(#{1,3})\s+(.*)/);
if (h) { flush(); const n = h[1].length + 2; html += `<h${n}>${inlineMd(h[2])}</h${n}>`; i++; continue; }
if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(l)) { flush(); html += '<hr>'; i++; continue; }
if (/^\s*>\s?/.test(l)) {
flush();
const buf = [];
while (i < lines.length && /^\s*>\s?/.test(lines[i])) buf.push(lines[i++].replace(/^\s*>\s?/, ''));
html += `<blockquote>${buf.map(inlineMd).join('<br>')}</blockquote>`;
continue;
}
if (/^\s*\|.*\|\s*$/.test(l) && /^\s*\|[\s:|-]+\|\s*$/.test(lines[i + 1] ?? '')) {
flush();
const cells = (s) => s.trim().replace(/^\||\|$/g, '').split('|').map((c) => inlineMd(c.trim()));
html += `<table><thead><tr>${cells(l).map((c) => `<th>${c}</th>`).join('')}</tr></thead><tbody>`;
for (i += 2; i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i]);) html += `<tr>${cells(lines[i++]).map((c) => `<td>${c}</td>`).join('')}</tr>`;
html += '</tbody></table>';
continue;
}
if (/^(\s*)([-*+]|\d+[.)])\s+/.test(l)) {
flush();
const items = [];
let m;
while (i < lines.length && (m = lines[i].match(/^(\s*)([-*+]|\d+[.)])\s+(.*)/))) {
items.push({ ind: Math.floor(m[1].replace(/\t/g, ' ').length / 2), ord: /\d/.test(m[2]), text: m[3] });
i++;
}
const stack = [];
for (const it of items) {
const depth = Math.min(it.ind, stack.length) + 1; // clamp: a child can only nest one level at a time
while (stack.length > depth) html += `</li></${stack.pop()}>`;
if (stack.length === depth) html += '</li>';
while (stack.length < depth) { const tag = it.ord ? 'ol' : 'ul'; html += `<${tag}>`; stack.push(tag); }
html += `<li>${inlineMd(it.text)}`;
}
while (stack.length) html += `</li></${stack.pop()}>`;
continue;
}
if (!l.trim()) { flush(); i++; continue; }
para.push(l); i++;
}
flush();
return html;
};
const setMd = (el, raw) => { el.innerHTML = md(raw); };
const bubble = (cls, text) => {
$('empty')?.remove();
const d = document.createElement('div');
d.className = `msg ${cls}`;
d.textContent = text;
$('log').appendChild(d);
d.scrollIntoView({ block: 'end', behavior: 'smooth' });
return d;
};
$('clear').onclick = () => {
if (busy) abort?.abort();
messages.length = 0;
chat?.reset();
dropSession();
$('log').replaceChildren();
status('<span class="ok">chat cleared</span> - the model forgot the conversation (KV cache reset, saved session removed).');
};
// geometric-mean token probability from the per-token logprobs: an honest "how sure was the
// model", straight from its own distribution (100% = every token was the obvious choice)
const confidenceOf = (r) => (r.logprobs?.length ? Math.exp(r.logprobs.reduce((s, e) => s + e.logprob, 0) / r.logprobs.length) : null);
$('form').onsubmit = async (ev) => {
ev.preventDefault();
if (!chat) return;
if (busy) { abort?.abort(); return; } // Send doubles as Stop while generating
const q = $('prompt').value.trim();
if (!q) return;
$('prompt').value = '';
busy = true; $('send').textContent = 'Stop';
abort = new AbortController();
bubble('user', q);
const base = messages.length; // rollback point: error/early-abort unwinds to before this turn
messages.push({ role: 'user', content: q });
let out = bubble('assistant', '');
out.classList.add('pending');
let rawOut = ''; // the bubble's accumulated source text (markdown renders from this)
try {
const json = $('jsonMode').checked;
const toolsOn = $('toolMode').checked;
if (!json) out.classList.add('md'); // JSON replies stay verbatim (pre-wrap), prose renders as markdown
let format;
if (json) {
const st = $('schema').value.trim();
if (st) {
try { format = { json: { schema: JSON.parse(st) } }; }
catch { throw new Error('the schema box does not contain valid JSON'); }
} else format = 'json';
}
// per-model sampling: models with a `gen` override (the 27B) use it; the rest keep the default.
// minP prunes candidates below 5% of the top token's probability - without it, a bare "hello"
// (no language anchor) can sample a Spanish/Russian opening from the top-K tail, and the first
// token locks the reply's language.
const gen = MODELS[$('model').value]?.gen ?? { temperature: 0.5, topK: 20, minP: 0.05, repetitionPenalty: 1.1 };
const sendOnce = () => chat.send(messages, {
...gen,
// generous cap - the engine clamps to the remaining KV window and stops cleanly there,
// so long answers aren't cut short (512 was truncating the 27B's fuller replies)
maxTokens: json ? 512 : 2048,
format,
tools: toolsOn ? DEMO_TOOLS : undefined,
logprobs: 5, // powers the confidence readout; the demo always samples, so this is ~free
promptLookup: json || toolsOn ? undefined : 'auto',
signal: abort.signal,
onText: (d) => {
rawOut += d;
if (json) out.textContent = rawOut; else setMd(out, rawOut);
out.scrollIntoView({ block: 'end' });
},
onOverflow: () => {
// conversation outgrew the KV window: keep the latest turns that fit
let msgs = messages.slice();
while (msgs.length > 1 && chat.countTokens(msgs) > engine.capabilities.maxSeqLen - 256) msgs = msgs.slice(2);
return msgs;
},
});
let r = await sendOnce();
// Tool round trips: the ENGINE only returns a validated call (name locked to the
// declared tools, arguments locked to their schema); executing it and continuing the
// conversation is this page's code. Cap the rounds so a chatty model cannot loop.
let calls = 0;
while (toolsOn && r.finishReason === 'tool_calls' && calls < 3 && !abort.signal.aborted) {
if (!rawOut) out.remove(); // a pure call turn has no visible reply
else out.classList.remove('pending');
messages.push({ role: 'assistant', content: r.text, tool_calls: r.toolCalls });
for (const call of r.toolCalls) {
const result = runDemoTool(call);
const tb = bubble('toolcall', '');
tb.innerHTML = `⚙ <b></b> → `;
tb.querySelector('b').textContent = `${call.name}(${JSON.stringify(call.arguments)})`;
tb.appendChild(document.createTextNode(result));
messages.push({ role: 'tool', content: result });
}
calls++;
out = bubble('assistant', '');
out.classList.add('pending', 'md');
rawOut = '';
r = await sendOnce(); // extends the KV cache: no re-prefill of the conversation
}
if (r.finishReason === 'abort') {
if (calls === 0) messages.length = base; // nothing committed yet: forget the question too
rawOut += ' *[stopped]*';
if (json) out.textContent = rawOut; else setMd(out, rawOut);
} else {
messages.push({ role: 'assistant', content: r.text, ...(r.toolCalls.length ? { tool_calls: r.toolCalls } : {}) });
const conf = confidenceOf(r);
const meta = document.createElement('span');
meta.className = 'meta';
meta.textContent = `${r.tokens.length} tokens · ${r.tokensPerSecond.toFixed(1)} tok/s · prefill ${r.prefillMs.toFixed(0)} ms`
+ (r.reusedCache ? ' · cache reused' : '')
+ (conf !== null ? ` · confidence ${(conf * 100).toFixed(0)}%` : '')
+ (calls ? ` · ${calls} tool round${calls > 1 ? 's' : ''}` : '')
+ (json ? ` · ${r.finishReason === 'stop' ? 'valid JSON' : 'cut by maxTokens'}` : '')
+ (!json && r.finishReason === 'length' ? ' · length-capped' : '');
out.appendChild(meta);
saveSession(); // persist the conversation + KV cache; a reload continues from here
}
} catch (e) {
out.classList.remove('md');
out.textContent = `error: ${e.message}`;
messages.length = base; // unwind the whole turn, including any tool round-trip messages
}
out.classList.remove('pending');
busy = false; abort = null;
$('send').textContent = 'Send';
$('prompt').focus();
};
</script>
</body>
</html>