-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathchat_ui.py
More file actions
543 lines (485 loc) · 21.2 KB
/
Copy pathchat_ui.py
File metadata and controls
543 lines (485 loc) · 21.2 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
#!/usr/bin/env python3
"""Chat Web UI with streaming, markdown rendering, thinking display, and in-page API URL input.
Usage:
python chat_ui.py
python chat_ui.py --port 8081
"""
import argparse
import json
from http.server import HTTPServer, BaseHTTPRequestHandler
from socketserver import ThreadingMixIn
import urllib.request
import urllib.error
HTML_PAGE = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat</title>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/styles/github.min.css">
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/highlight.min.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f5f5f5; height: 100vh; display: flex; flex-direction: column; }
#header { background: #1a1a2e; color: #fff; padding: 12px 20px; font-size: 18px; display: flex; justify-content: space-between; align-items: center; }
#header .info { font-size: 12px; color: #aaa; }
#chat-box { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 12px; }
.msg { max-width: 80%; padding: 10px 14px; border-radius: 12px; line-height: 1.6; word-break: break-word; font-size: 14px; }
.msg.user { align-self: flex-end; background: #0084ff; color: #fff; border-bottom-right-radius: 4px; white-space: pre-wrap; }
.msg.assistant { align-self: flex-start; background: #fff; color: #333; border-bottom-left-radius: 4px; box-shadow: 0 1px 2px rgba(0,0,0,0.1); }
.msg.error { align-self: flex-start; background: #ffe0e0; color: #c00; }
.think-block { background: #f0f0f0; border-left: 3px solid #999; padding: 8px 12px; margin-bottom: 6px; border-radius: 4px; color: #666; font-size: 13px; font-style: italic; max-height: 200px; overflow-y: auto; white-space: pre-wrap; }
.think-label { font-size: 11px; color: #999; margin-bottom: 2px; font-style: normal; font-weight: bold; cursor: pointer; }
.think-label:hover { color: #666; }
.think-block.collapsed .think-content { display: none; }
.speed-info { font-size: 11px; color: #999; margin-top: 6px; padding-top: 4px; border-top: 1px solid #eee; }
#input-area { padding: 12px 20px; background: #fff; border-top: 1px solid #ddd; display: flex; gap: 10px; }
#input-area textarea { flex: 1; padding: 10px; border: 1px solid #ccc; border-radius: 8px; font-size: 14px; resize: none; min-height: 44px; max-height: 120px; font-family: inherit; }
#input-area button { padding: 0 20px; background: #0084ff; color: #fff; border: none; border-radius: 8px; font-size: 14px; cursor: pointer; white-space: nowrap; }
#input-area button:disabled { background: #aaa; cursor: not-allowed; }
#clear-btn { background: #666; }
#settings { padding: 8px 20px; background: #fff; border-top: 1px solid #eee; display: flex; gap: 16px; align-items: center; font-size: 13px; color: #666; flex-wrap: wrap; }
#settings label { display: flex; align-items: center; gap: 4px; }
#settings input, #settings select { padding: 2px 6px; border: 1px solid #ccc; border-radius: 4px; font-size: 13px; }
#settings input[type=number] { width: 70px; }
#api-url { width: 360px; }
.status-dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; }
.status-dot.ok { background: #4caf50; }
.status-dot.err { background: #f44336; }
.status-dot.unknown { background: #999; }
/* Markdown rendered content styles */
.md-content { line-height: 1.7; }
.md-content p { margin: 0.4em 0; }
.md-content p:first-child { margin-top: 0; }
.md-content p:last-child { margin-bottom: 0; }
.md-content h1, .md-content h2, .md-content h3, .md-content h4 { margin: 0.8em 0 0.4em; font-weight: 600; }
.md-content h1 { font-size: 1.4em; }
.md-content h2 { font-size: 1.25em; }
.md-content h3 { font-size: 1.1em; }
.md-content ul, .md-content ol { margin: 0.4em 0; padding-left: 1.5em; }
.md-content li { margin: 0.2em 0; }
.md-content code {
background: #f0f0f0; padding: 1px 5px; border-radius: 3px;
font-family: "SF Mono", "Fira Code", "Consolas", monospace; font-size: 0.9em; color: #d63384;
}
.md-content pre { margin: 0.6em 0; border-radius: 8px; overflow-x: auto; position: relative; }
.md-content pre code {
display: block; padding: 12px 14px; background: #1e1e2e; color: #cdd6f4;
font-size: 13px; line-height: 1.5; border-radius: 8px; overflow-x: auto;
}
.md-content pre .copy-btn {
position: absolute; top: 6px; right: 6px; background: rgba(255,255,255,0.15);
border: none; color: #cdd6f4; font-size: 11px; padding: 3px 8px; border-radius: 4px;
cursor: pointer; opacity: 0; transition: opacity 0.2s;
}
.md-content pre:hover .copy-btn { opacity: 1; }
.md-content pre .copy-btn:hover { background: rgba(255,255,255,0.3); }
.md-content blockquote {
border-left: 3px solid #ddd; margin: 0.5em 0; padding: 0.3em 0.8em; color: #666; background: #fafafa; border-radius: 0 4px 4px 0;
}
.md-content table { border-collapse: collapse; margin: 0.5em 0; font-size: 13px; width: 100%; }
.md-content th, .md-content td { border: 1px solid #ddd; padding: 6px 10px; text-align: left; }
.md-content th { background: #f5f5f5; font-weight: 600; }
.md-content hr { border: none; border-top: 1px solid #ddd; margin: 0.8em 0; }
.md-content a { color: #0066cc; text-decoration: none; }
.md-content a:hover { text-decoration: underline; }
.md-content strong { font-weight: 600; }
.md-content img { max-width: 100%; border-radius: 6px; }
/* streaming cursor */
.streaming-cursor::after { content: '▊'; animation: blink 1s step-end infinite; color: #999; }
@keyframes blink { 50% { opacity: 0; } }
</style>
</head>
<body>
<div id="header">
<span>Chat UI</span>
<span class="info"><span class="status-dot unknown" id="status-dot"></span><span id="status-text">Not connected</span></span>
</div>
<div id="chat-box"></div>
<div id="settings">
<label>API URL <input type="text" id="api-url" placeholder="http://localhost:8080/v1" value="http://localhost:8080/v1"></label>
<label>Max Tokens <input type="number" id="max-tokens" value="4096" min="1" max="32768"></label>
<label>Temperature <input type="number" id="temperature" value="0.7" min="0" max="2" step="0.1"></label>
<label>System Prompt <input type="text" id="system-prompt" value="You are a helpful assistant." style="width:240px"></label>
</div>
<div id="input-area">
<textarea id="user-input" placeholder="Type a message... (Enter to send, Shift+Enter for newline)" rows="1"></textarea>
<button id="send-btn" onclick="sendMessage()">Send</button>
<button id="clear-btn" onclick="clearChat()">Clear</button>
</div>
<script>
const chatBox = document.getElementById('chat-box');
const userInput = document.getElementById('user-input');
const sendBtn = document.getElementById('send-btn');
const apiUrlInput = document.getElementById('api-url');
const statusDot = document.getElementById('status-dot');
const statusText = document.getElementById('status-text');
let history = [];
let sending = false;
// Configure marked
marked.setOptions({
highlight: function(code, lang) {
if (lang && hljs.getLanguage(lang)) {
try { return hljs.highlight(code, {language: lang}).value; } catch(e) {}
}
try { return hljs.highlightAuto(code).value; } catch(e) {}
return code;
},
breaks: true,
gfm: true,
});
function renderMarkdown(text) {
const html = marked.parse(text);
// Add copy buttons to code blocks
const div = document.createElement('div');
div.innerHTML = html;
div.querySelectorAll('pre code').forEach(block => {
const btn = document.createElement('button');
btn.className = 'copy-btn';
btn.textContent = 'Copy';
btn.onclick = function() {
navigator.clipboard.writeText(block.textContent).then(() => {
btn.textContent = 'Copied!';
setTimeout(() => btn.textContent = 'Copy', 1500);
});
};
block.parentElement.style.position = 'relative';
block.parentElement.appendChild(btn);
});
return div.innerHTML;
}
const saved = localStorage.getItem('chat_api_url');
if (saved) apiUrlInput.value = saved;
else apiUrlInput.value = 'http://localhost:8080/v1';
apiUrlInput.addEventListener('change', () => {
localStorage.setItem('chat_api_url', apiUrlInput.value.trim());
checkConnection();
});
apiUrlInput.addEventListener('keydown', e => {
if (e.key === 'Enter') { e.preventDefault(); localStorage.setItem('chat_api_url', apiUrlInput.value.trim()); checkConnection(); }
});
let checkTimer = null;
apiUrlInput.addEventListener('input', () => {
clearTimeout(checkTimer);
checkTimer = setTimeout(() => {
localStorage.setItem('chat_api_url', apiUrlInput.value.trim());
setStatus('unknown', 'Checking...');
checkConnection();
}, 800);
});
function setStatus(state, msg) {
statusDot.className = 'status-dot ' + state;
statusText.textContent = msg;
}
async function checkConnection() {
const base = apiUrlInput.value.trim().replace(/\/+$/, '');
if (!base) { setStatus('unknown', 'Not connected'); return; }
try {
const resp = await fetch('/api/check', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({api_url: base})
});
const data = await resp.json();
if (data.ok) {
const models = (data.models || []).map(m => m.split('/').pop());
setStatus('ok', 'Connected' + (models.length ? ' - ' + models[0] : ''));
} else {
setStatus('err', 'Failed: ' + (data.error || ''));
}
} catch(e) {
setStatus('err', 'Connection failed');
}
}
userInput.addEventListener('keydown', e => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }
});
userInput.addEventListener('input', () => {
userInput.style.height = 'auto';
userInput.style.height = Math.min(userInput.scrollHeight, 120) + 'px';
});
function addMsg(role, text) {
const div = document.createElement('div');
div.className = 'msg ' + role;
div.textContent = text || '';
chatBox.appendChild(div);
chatBox.scrollTop = chatBox.scrollHeight;
return div;
}
async function sendMessage() {
const text = userInput.value.trim();
const apiUrl = apiUrlInput.value.trim().replace(/\/+$/, '');
if (!text || sending) return;
if (!apiUrl) { alert('Please enter an API URL first'); apiUrlInput.focus(); return; }
sending = true;
sendBtn.disabled = true;
sendBtn.textContent = 'Sending...';
userInput.value = '';
userInput.style.height = 'auto';
addMsg('user', text);
history.push({role: 'user', content: text});
const sysPrompt = document.getElementById('system-prompt').value.trim();
const maxTokens = parseInt(document.getElementById('max-tokens').value) || 4096;
const temperature = parseFloat(document.getElementById('temperature').value) || 0;
const messages = [];
if (sysPrompt) messages.push({role: 'system', content: sysPrompt});
messages.push(...history);
// Create assistant message container
const assistantDiv = document.createElement('div');
assistantDiv.className = 'msg assistant';
chatBox.appendChild(assistantDiv);
// Think block (hidden initially)
const thinkBlock = document.createElement('div');
thinkBlock.className = 'think-block';
thinkBlock.style.display = 'none';
const thinkLabel = document.createElement('div');
thinkLabel.className = 'think-label';
thinkLabel.textContent = '💭 Thinking...';
thinkLabel.onclick = function() { thinkBlock.classList.toggle('collapsed'); };
thinkBlock.appendChild(thinkLabel);
const thinkContent = document.createElement('div');
thinkContent.className = 'think-content';
thinkBlock.appendChild(thinkContent);
assistantDiv.appendChild(thinkBlock);
// Content block (markdown rendered)
const contentBlock = document.createElement('div');
contentBlock.className = 'md-content streaming-cursor';
assistantDiv.appendChild(contentBlock);
contentBlock.textContent = '...';
// Speed info block
const speedBlock = document.createElement('div');
speedBlock.className = 'speed-info';
speedBlock.style.display = 'none';
assistantDiv.appendChild(speedBlock);
let thinkText = '';
let contentText = '';
let chunkCount = 0;
let thinkChunkCount = 0;
let firstTokenTime = null;
let usageData = null;
const startTime = Date.now();
let renderTimer = null;
// Debounced markdown render during streaming
function scheduleRender() {
if (renderTimer) return;
renderTimer = setTimeout(() => {
renderTimer = null;
contentBlock.innerHTML = renderMarkdown(contentText);
contentBlock.classList.add('streaming-cursor');
chatBox.scrollTop = chatBox.scrollHeight;
}, 80);
}
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 600000); // 10 min
const resp = await fetch('/api/chat/stream', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({api_url: apiUrl, messages, max_tokens: maxTokens, temperature}),
signal: controller.signal
});
clearTimeout(timeoutId);
if (!resp.ok) {
const err = await resp.json();
throw new Error(err.error || 'HTTP ' + resp.status);
}
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
contentBlock.textContent = '';
while (true) {
const {done, value} = await reader.read();
if (done) break;
buffer += decoder.decode(value, {stream: true});
const lines = buffer.split('\n');
buffer = lines.pop(); // keep incomplete line
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
const data = line.slice(6);
if (data === '[DONE]') continue;
try {
const parsed = JSON.parse(data);
const delta = parsed.choices?.[0]?.delta || {};
// Handle thinking/reasoning content
const rc = delta.reasoning_content || delta.thinking || '';
if (rc) {
if (!firstTokenTime) firstTokenTime = Date.now();
thinkText += rc;
thinkChunkCount++;
thinkBlock.style.display = 'block';
thinkContent.textContent = thinkText;
if (contentBlock.textContent === '') contentBlock.textContent = '';
}
// Handle regular content
const c = delta.content || '';
if (c) {
if (!firstTokenTime) firstTokenTime = Date.now();
if (contentText === '' && thinkText) {
thinkLabel.textContent = '💭 Thought (click to toggle)';
}
contentText += c;
chunkCount++;
scheduleRender();
}
// Capture usage from final chunk
if (parsed.usage) {
usageData = parsed.usage;
}
// Update speed display (real-time estimate using chunks)
const totalChunks = chunkCount + thinkChunkCount;
if (totalChunks > 0 && firstTokenTime) {
const elapsed = (Date.now() - firstTokenTime) / 1000;
const ttft = (firstTokenTime - startTime) / 1000;
const cps = elapsed > 0 ? (totalChunks / elapsed).toFixed(1) : '...';
speedBlock.style.display = 'block';
speedBlock.textContent = `⚡ ${totalChunks} chunks | ~${cps} chunk/s | TTFT ${ttft.toFixed(2)}s | ${elapsed.toFixed(1)}s`;
}
} catch(e) { /* skip bad JSON */ }
}
chatBox.scrollTop = chatBox.scrollHeight;
}
// Final markdown render
if (renderTimer) { clearTimeout(renderTimer); renderTimer = null; }
contentBlock.classList.remove('streaming-cursor');
if (contentText) {
contentBlock.innerHTML = renderMarkdown(contentText);
} else if (thinkText) {
contentBlock.textContent = '[No content, only thinking output]';
}
// Final speed summary using actual usage data
if (firstTokenTime) {
const totalTime = (Date.now() - startTime) / 1000;
const genTime = (Date.now() - firstTokenTime) / 1000;
const ttft = (firstTokenTime - startTime) / 1000;
let parts = [];
if (usageData) {
const compTokens = usageData.completion_tokens || 0;
const promptTokens = usageData.prompt_tokens || 0;
const tps = genTime > 0 ? (compTokens / genTime).toFixed(1) : '-';
parts.push(`⚡ ${compTokens} tokens generated`);
parts.push(`| ${tps} tok/s`);
parts.push(`| prompt: ${promptTokens}`);
} else {
const totalChunks = chunkCount + thinkChunkCount;
const cps = genTime > 0 ? (totalChunks / genTime).toFixed(1) : '-';
parts.push(`⚡ ~${totalChunks} chunks`);
parts.push(`| ~${cps} chunk/s`);
}
parts.push(`| TTFT ${ttft.toFixed(2)}s`);
parts.push(`| total ${totalTime.toFixed(1)}s`);
speedBlock.textContent = parts.join(' ');
speedBlock.style.display = 'block';
}
history.push({role: 'assistant', content: contentText || thinkText});
} catch(e) {
assistantDiv.className = 'msg error';
thinkBlock.style.display = 'none';
contentBlock.classList.remove('streaming-cursor');
if (e.name === 'AbortError') {
contentBlock.textContent = 'Error: Request timed out (10min), please check if the API is reachable';
} else {
contentBlock.textContent = 'Error: ' + e.message;
}
}
sending = false;
sendBtn.disabled = false;
sendBtn.textContent = 'Send';
userInput.focus();
}
function clearChat() {
history = [];
chatBox.innerHTML = '';
}
if (apiUrlInput.value.trim()) checkConnection();
userInput.focus();
</script>
</body>
</html>
"""
class ChatHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/" or self.path == "/index.html":
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.end_headers()
self.wfile.write(HTML_PAGE.encode("utf-8"))
else:
self.send_error(404)
def do_POST(self):
length = int(self.headers.get("Content-Length", 0))
body = json.loads(self.rfile.read(length))
if self.path == "/api/chat/stream":
try:
self._stream_chat(body)
except Exception as e:
print(f"[ERROR] stream chat failed: {type(e).__name__}: {e}")
try:
self._json_response(500, {"error": f"{type(e).__name__}: {e}"})
except Exception:
pass
elif self.path == "/api/check":
try:
api_url = body["api_url"].rstrip("/")
req = urllib.request.Request(
f"{api_url}/models",
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(req, timeout=5) as resp:
data = json.loads(resp.read())
models = [m["id"] for m in data.get("data", [])]
self._json_response(200, {"ok": True, "models": models})
except Exception as e:
print(f"[ERROR] check failed: {type(e).__name__}: {e}")
self._json_response(200, {"ok": False, "error": f"{type(e).__name__}: {e}"})
else:
self.send_error(404)
def _stream_chat(self, body):
api_url = body["api_url"].rstrip("/")
payload = json.dumps({
"model": "default",
"messages": body["messages"],
"max_tokens": body.get("max_tokens", 4096),
"temperature": body.get("temperature", 0.7),
"stream": True,
"stream_options": {"include_usage": True},
}).encode("utf-8")
req = urllib.request.Request(
f"{api_url}/chat/completions",
data=payload,
headers={"Content-Type": "application/json"},
)
self.send_response(200)
self.send_header("Content-Type", "text/event-stream; charset=utf-8")
self.send_header("Cache-Control", "no-cache")
self.send_header("X-Accel-Buffering", "no")
self.end_headers()
with urllib.request.urlopen(req, timeout=600) as resp:
for line in resp:
decoded = line.decode("utf-8", errors="replace")
self.wfile.write(decoded.encode("utf-8"))
self.wfile.flush()
def _json_response(self, code, obj):
self.send_response(code)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.end_headers()
self.wfile.write(json.dumps(obj, ensure_ascii=False).encode("utf-8"))
def log_message(self, format, *args):
print(f"[{self.log_date_time_string()}] {format % args}")
def main():
parser = argparse.ArgumentParser(description="Chat Web UI")
parser.add_argument("--port", type=int, default=8081, help="Web UI port")
args = parser.parse_args()
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
daemon_threads = True
server = ThreadingHTTPServer(("0.0.0.0", args.port), ChatHandler)
print(f"Chat UI running at http://0.0.0.0:{args.port}")
print("Open in browser, enter API URL (e.g. http://localhost:8080/v1), and start chatting.")
print("Press Ctrl+C to stop.")
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nShutting down.")
server.shutdown()
if __name__ == "__main__":
main()