-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathindex.html
437 lines (373 loc) · 21.6 KB
/
index.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
<!DOCTYPE html>
<html>
<head>
<title>ReflectionAnyLLM - by ANTIBITCOIN</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/purify.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/anime.min.js"></script>
</head>
<body class="bg-gray-900 text-gray-100 font-sans">
<div id="chat-container" class="flex flex-col h-screen">
<div id="chat-window" class="flex-1 p-4 overflow-y-auto">
</div>
<form id="message-form" class="flex items-center p-4 bg-gray-800">
<input type="text" id="message-input" placeholder="Type your message here..." autocomplete="off" autofocus
class="flex-1 p-2 bg-gray-700 border border-gray-600 text-gray-100 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 rounded-l-md">
<button type="submit" id="send-button"
class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-r-md">
Send
</button>
<button type="button" id="clear-button"
class="ml-2 px-4 py-2 bg-red-600 hover:bg-red-700 text-white font-semibold rounded-md">
Clear
</button>
<button type="button" id="download-button"
class="ml-2 px-4 py-2 bg-green-600 hover:bg-green-700 text-white font-semibold rounded-md">
Download History
</button>
</form>
<footer class="p-4 bg-gray-800 text-center text-gray-400">
<span>Project developed by <a href="https://freemindgpt.com" target="_blank" class="text-blue-400 hover:text-blue-500">FreeMindGPT</a></span>
<a href="https://github.com/antibitcoin/ReflectionAnyLLM/tree/main" target="_blank" class="ml-2 text-gray-400 hover:text-gray-100 inline-flex items-center">
<svg width="18" height="18" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 24 24" width="24" height="24" class="mr-1">
<path d="M12 0C5.373 0 0 5.373 0 12c0 5.303 3.438 9.8 8.207 11.387.6.111.793-.261.793-.581 0-.286-.01-1.04-.015-2.04-3.338.726-4.042-1.609-4.042-1.609-.546-1.385-1.333-1.755-1.333-1.755-1.09-.745.083-.73.083-.73 1.204.085 1.838 1.237 1.838 1.237 1.07 1.835 2.807 1.305 3.492.998.108-.774.418-1.305.761-1.605-2.665-.304-5.466-1.332-5.466-5.93 0-1.31.469-2.382 1.236-3.221-.123-.303-.535-1.524.117-3.176 0 0 1.007-.323 3.3 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.29-1.554 3.294-1.23 3.294-1.23.653 1.653.241 2.874.118 3.176.77.839 1.236 1.911 1.236 3.221 0 4.61-2.805 5.624-5.478 5.92.43.37.814 1.103.814 2.222 0 1.605-.014 2.897-.014 3.289 0 .323.19.698.801.579C20.565 21.796 24 17.299 24 12c0-6.627-5.373-12-12-12z"/>
</svg>
GitHub Repo
</a>
</footer>
</div>
<script>
// Initialize chat history from localStorage
let chatHistory = JSON.parse(localStorage.getItem('chatHistory')) || [];
// Function to save chat history to localStorage
function saveChatHistory() {
localStorage.setItem('chatHistory', JSON.stringify(chatHistory));
}
// Function to clear chat history
function clearChatHistory() {
localStorage.removeItem('chatHistory');
chatHistory = [];
location.reload();
}
// Function to download chat history
function downloadChatHistory() {
const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(chatHistory, null, 2));
const downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", "chat_history.json");
document.body.appendChild(downloadAnchorNode);
downloadAnchorNode.click();
downloadAnchorNode.remove();
}
// Function to load chat history and display messages
function loadChatHistory() {
chatHistory.forEach(entry => {
if (entry.sender === 'system') {
// Handle system messages if any
} else if (entry.sender === 'thought_process') {
// Add "Show Thought Process" button for this thought process
addThoughtProcessButton(entry.text);
} else {
addMessageToChat(entry.sender, entry.text, entry.isMarkdown, false);
}
});
}
// Call loadChatHistory on page load
loadChatHistory();
document.getElementById('clear-button').addEventListener('click', clearChatHistory);
document.getElementById('download-button').addEventListener('click', downloadChatHistory);
document.getElementById('message-form').addEventListener('submit', function(e) {
e.preventDefault();
const inputField = document.getElementById('message-input');
const message = inputField.value.trim();
if (message === '') return;
addMessageToChat('user', message);
chatHistory.push({ sender: 'user', text: message });
saveChatHistory();
inputField.value = '';
// Display "Thinking..." label
addThinkingLabel();
// Prepare the chat history to send to the backend (excluding thought processes)
const historyForBackend = chatHistory.filter(entry => entry.sender !== 'thought_process');
// Send the message to the server via fetch
fetch('chat.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: message,
history: historyForBackend.slice(-10) // Implement rolling window
}),
})
.then(response => {
if (!response.body) {
throw new Error('ReadableStream not supported in this browser.');
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let thoughtProcess = '';
let assistantMessageElement = null;
let assistantContentElement = null;
let isStreaming = false;
// Collect the assistant's response to render after streaming completes
let assistantContentBuffer = '';
function read() {
reader.read().then(({done, value}) => {
if (done) {
// Remove any remaining thinking element
removeThinkingLabel();
// Remove current step element if still present
removeCurrentStep();
// After streaming is done, parse and render the assistant's content
if (assistantContentElement && assistantContentBuffer) {
renderMarkdownContent(assistantContentElement, assistantContentBuffer);
}
// Save assistant's message to chat history
if (assistantContentBuffer) {
chatHistory.push({ sender: 'assistant', text: assistantContentBuffer, isMarkdown: true });
saveChatHistory();
}
// After all steps and assistant's final answer are displayed, show the "Show Thought Process" button
if (thoughtProcess) {
addThoughtProcessButton(thoughtProcess);
}
return;
}
// Decode the chunk and add it to the buffer
let chunk = decoder.decode(value, {stream: true});
buffer += chunk;
// Process the buffer for SSE messages
let sseMessages = buffer.split(/\r?\n\r?\n/);
buffer = sseMessages.pop(); // Save incomplete data for next read
for (let message of sseMessages) {
message = message.trim();
if (message.startsWith('data: ')) {
let dataStr = message.slice(6).trim(); // Remove 'data: ' and trim
if (dataStr === '[DONE]') {
// Streaming finished
removeThinkingLabel();
removeCurrentStep();
// After streaming is done, parse and render the assistant's content
if (assistantContentElement && assistantContentBuffer) {
renderMarkdownContent(assistantContentElement, assistantContentBuffer);
}
// Save assistant's message to chat history
if (assistantContentBuffer) {
chatHistory.push({ sender: 'assistant', text: assistantContentBuffer, isMarkdown: true });
saveChatHistory();
}
// After all steps and assistant's final answer are displayed, show the "Show Thought Process" button
if (thoughtProcess) {
addThoughtProcessButton(thoughtProcess);
}
return;
}
try {
let data = JSON.parse(dataStr);
if (data.error) {
console.error('Error from server:', data.error);
removeThinkingLabel();
removeCurrentStep();
addMessageToChat('assistant', 'Error: ' + data.error);
return;
}
if (data.current_step) {
// Received current step title
// Remove "Thinking..." label if it's still there
removeThinkingLabel();
displayCurrentStep(data.current_step);
} else if (data.full_thought_process) {
// Received full thought process
thoughtProcess = data.full_thought_process;
// Save the thought process in chatHistory
chatHistory.push({ sender: 'thought_process', text: thoughtProcess });
saveChatHistory();
// Remove the current step element
removeCurrentStep();
} else if (data.choices && data.choices[0].delta) {
// Streaming final answer
let content = data.choices[0].delta.content || '';
if (!isStreaming) {
// Prepare the assistant message element
({ messageElement: assistantMessageElement, contentElement: assistantContentElement } = addMessageToChat('assistant', '', true));
isStreaming = true;
}
// Append content to the assistant's message buffer
assistantContentBuffer += content;
// Render the partial content
renderMarkdownContent(assistantContentElement, assistantContentBuffer);
}
} catch (e) {
console.error('Error parsing JSON:', e, 'Data:', dataStr);
// Handle incomplete JSON data
// Accumulate incomplete data for the next read
buffer = dataStr + '\n\n' + buffer;
continue;
}
}
}
// Continue reading
read();
}).catch(error => {
console.error('Error reading stream:', error);
removeThinkingLabel();
removeCurrentStep();
addMessageToChat('assistant', 'Error reading stream.');
});
}
// Start reading the stream
read();
})
.catch(error => {
console.error('Error:', error);
removeThinkingLabel();
removeCurrentStep();
addMessageToChat('assistant', 'Error: Unable to communicate with the server.');
});
});
// Function to add "Thinking..." label with animation
function addThinkingLabel() {
const chatWindow = document.getElementById('chat-window');
const thinkingElement = document.createElement('div');
thinkingElement.id = 'thinking-label';
thinkingElement.className = 'flex items-center my-2';
thinkingElement.innerHTML = `
<div class="loader mr-2"></div>
<span>Thinking...</span>
`;
chatWindow.appendChild(thinkingElement);
scrollChatToBottom();
}
// Function to remove "Thinking..." label
function removeThinkingLabel() {
const thinkingElement = document.getElementById('thinking-label');
if (thinkingElement && thinkingElement.parentNode) {
thinkingElement.parentNode.removeChild(thinkingElement);
}
}
// Function to remove current step element
function removeCurrentStep() {
const stepElement = document.getElementById('current-step');
if (stepElement && stepElement.parentNode) {
stepElement.parentNode.removeChild(stepElement);
}
}
// Function to display current step with fade in/out effect
function displayCurrentStep(stepTitle) {
removeThinkingLabel(); // Ensure "Thinking..." label is removed
const chatWindow = document.getElementById('chat-window');
let stepElement = document.getElementById('current-step');
if (!stepElement) {
stepElement = document.createElement('div');
stepElement.id = 'current-step';
stepElement.className = 'flex items-center my-2';
chatWindow.appendChild(stepElement);
}
// Update the content of the step element with markdown rendering
const loaderElement = '<div class="loader mr-2"></div>';
const titleElement = document.createElement('div');
renderMarkdownContent(titleElement, stepTitle);
stepElement.innerHTML = '';
stepElement.insertAdjacentHTML('beforeend', loaderElement);
stepElement.appendChild(titleElement);
// Animate fade in
anime({
targets: stepElement,
opacity: [0, 1],
duration: 500,
easing: 'easeInOutQuad',
});
}
// Function to add "Show Thought Process" button with toggle
function addThoughtProcessButton(thoughtProcess) {
const chatWindow = document.getElementById('chat-window');
const buttonContainer = document.createElement('div');
buttonContainer.className = 'my-2';
const buttonElement = document.createElement('button');
buttonElement.innerHTML = `Show Thought Process <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" width="16" height="16" stroke-width="1.5" stroke="currentColor" class="size-6"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25L12 15.75 4.5 8.25"></path></svg>`; // Down arrow
buttonElement.className = 'text-blue-500 hover:underline cursor-pointer focus:outline-none inline-flex items-center'; // Adjusted styles
buttonElement.style.gap = '8px'; // Space between text and icon
buttonElement.addEventListener('click', function() {
if (thoughtElement.classList.contains('hidden')) {
thoughtElement.classList.remove('hidden');
buttonElement.innerHTML = `Hide Thought Process <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" width="16" height="16" stroke-width="1.5" stroke="currentColor" class="size-6"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 15.75L12 8.25l7.5 7.5"></path></svg>`;
} else {
thoughtElement.classList.add('hidden');
buttonElement.innerHTML = `Show Thought Process <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" width="16" height="16" stroke-width="1.5" stroke="currentColor" class="size-6"><path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25L12 15.75 4.5 8.25"></path></svg>`;
}
scrollChatToBottom();
});
const thoughtElement = document.createElement('div');
thoughtElement.className = 'thought-process bg-gray-800 p-4 rounded-md mt-2 hidden';
renderMarkdownContent(thoughtElement, thoughtProcess);
thoughtElement.children[0].classList.add('marker:text-blue-300','list-decimal','relative','left-4');
buttonContainer.appendChild(buttonElement);
buttonContainer.appendChild(thoughtElement);
chatWindow.appendChild(buttonContainer);
scrollChatToBottom();
}
// Function to display messages in the chat window
function addMessageToChat(sender, text, isMarkdown = false, saveToHistory = true) {
const chatWindow = document.getElementById('chat-window');
const messageElement = document.createElement('div');
messageElement.classList.add('message', sender === 'user' ? 'user-message' : 'assistant-message', 'my-2');
const contentElement = document.createElement('div');
contentElement.classList.add('message-content', 'px-4', 'py-2', 'rounded-md', 'inline-block', 'max-w-3/4');
if (sender === 'user') {
messageElement.classList.add('text-right');
contentElement.classList.add('bg-blue-600', 'text-white');
contentElement.classList.add('ml-auto');
} else {
messageElement.classList.add('text-left');
contentElement.classList.add('bg-gray-800', 'text-gray-100');
}
messageElement.appendChild(contentElement);
if (isMarkdown) {
renderMarkdownContent(contentElement, text);
} else {
contentElement.textContent = text;
}
chatWindow.appendChild(messageElement);
scrollChatToBottom();
return { messageElement, contentElement };
}
// Function to render Markdown content
function renderMarkdownContent(contentElement, markdownText) {
try {
const rawHTML = marked.parse(markdownText);
const sanitizedHTML = DOMPurify.sanitize(rawHTML);
contentElement.innerHTML = sanitizedHTML;
} catch (e) {
console.error('Error rendering Markdown:', e);
contentElement.textContent = markdownText;
}
scrollChatToBottom();
}
// Function to scroll chat to bottom
function scrollChatToBottom() {
const chatWindow = document.getElementById('chat-window');
chatWindow.scrollTop = chatWindow.scrollHeight;
}
// CSS for the thinking animation
const style = document.createElement('style');
style.innerHTML = `
.loader {
border: 4px solid rgba(255, 255, 255, 0.2);
border-top: 4px solid #ffffff;
border-radius: 50%;
width: 20px;
height: 20px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
`;
document.head.appendChild(style);
</script>
</body>
</html>