about summary refs log tree commit diff stats
path: root/html/matt-chat/index.html
blob: 17dcefeeb394a81b12dce83401239ed666e4d491 (plain) (blame)
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Chatty chat chat chat. A super simple chat interface for the Ollama API.">
    <title>matt chat is not a cat</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f7f7f7;
            max-width: 600px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            align-items: center;
            height: 100vh;
            overflow: hidden;
        }
        #chat-container {
            background-color: white;
            border: 1px solid #ccc;
            border-radius: 8px;
            padding: 1em;
            margin: 0 auto;
            flex: 1;
            overflow-y: auto;
            width: 100%;
            max-height: 400px;
        }
        #user-input {
            width: 100%;
            padding: 10px;
            border-radius: 4px;
            border: 1px solid #ddd;
            font-size: 16px;
            margin-top: 10px;
            box-sizing: border-box;
        }
        #send-button {
            padding: 10px 15px;
            border-radius: 4px;
            background-color: #007BFF;
            color: white;
            border: none;
            cursor: pointer;
            margin-top: 10px;
            width: 100%;
        }
        #send-button:hover {
            background-color: #0056b3;
        }

        .model-select-container {
            align-self: flex-start;
            width: 100%;
            display: flex;
            justify-content: space-between;
            padding: 1em;
        }

        .model-select-container label {
            margin-left: 10px;
        }

        .message {
            white-space: pre-wrap;
            margin-bottom: 10px;
            padding: 1em;
            border-radius: 8px;
            background-color: #f1f1f1;
            display: block;
            max-width: 100%;
        }

        .user-message {
            background-color: #007BFF;
            color: white;
            text-align: right;
            margin-right: 20px;
        }

        .bot-message {
            background-color: #f0f0f0;
            color: #333;
            margin-left: 20px;
        }

        @media (max-width: 600px) {
            #chat-container {
                max-height: 300px; /* Reduce max height for mobile */
            }
        }

        body.dark-mode {
            background-color: #333;
            color: #f7f7f7;
        }

        #chat-container.dark-mode {
            background-color: #444;
            border: 1px solid #555;
        }

        #user-input.dark-mode {
            background-color: #555;
            color: #f7f7f7;
            border: 1px solid #666;
        }

        #send-button.dark-mode {
            background-color: #007BFF;
            color: white;
        }

        .message.dark-mode {
            background-color: #555;
            color: #f7f7f7;
        }

        .user-message.dark-mode {
            background-color: #007BFF;
            color: white;
        }

        .bot-message.dark-mode {
            background-color: #666;
            color: #f7f7f7;
        }

        .bot-time {
            margin: 0.5em 0;
            font-size: 0.9em; /* Smaller font size */
            color: #888; /* Lighter color */
            text-align: center; /* Center the text */
        }
        
    </style>
</head>
<body>

    <div class="model-select-container">
        <select id="model-select"></select>
        <label>
            <input type="checkbox" id="retain-history" /> Build Context As You Chat?
        </label>
    </div>
    
    <div id="chat-container">
        <!-- Messages will appear here -->
    </div>

    <!-- New container for user input and send button -->
    <div id="input-container" style="width: 100%; display: flex; flex-direction: column; margin-top: 10px;">
        <div id="counter" style="text-align: left; font-size: 0.9em; color: #555;">
            Characters: <span id="char-count">0</span> | Words: <span id="word-count">0</span>
        </div>
        <textarea id="user-input" placeholder="Type your message..."></textarea>
        <button id="send-button">Send</button>
    </div>

    <script>
        // ==================================================
        // MATT CHAT IS NOT A CAT
        // This is a simple chat interface for the Ollama API
        // ==================================================
        //
        // This configuration object is used to define all local variables for your needs
        // Set the base url for the ollama api, and then list all the models you want to use
        // The context window size is the number of previous exchanges to keep...
        // though this is relatively naive at the moment
        const config = {
            apiUrl: "http://localhost:11434/v1/chat/completions",
            models: [
                { value: "llama3.1:8b", label: "llama3.1:8b, general tasks" },
                { value: "qwen2.5-coder:1.5b", label: "qwen2.5-coder:1.5b, fast coding" },
                { value: "qwen2.5-coder:7b", label: "qwen2.5-coder:7b, fastish coding" },
                { value: "qwen2.5-coder:32b", label: "qwen2.5-coder:32b, super slow coding" },
            ],
            contextWindowSize: 3, // Number of previous exchanges to remember
            systemMessage: "You are a helpful assistant." // Set the mood and personality for the LLM's responses
        };

        let conversationHistory = [];

        function populateModelSelect() {
            const modelSelect = document.getElementById("model-select");
            modelSelect.innerHTML = ""; // Clear existing options

            config.models.forEach(model => {
                const option = document.createElement("option");
                option.value = model.value;
                option.textContent = model.label;
                modelSelect.appendChild(option);
            });
        }

        document.addEventListener("DOMContentLoaded", () => {
            populateModelSelect(); // Populate the model select dropdown

            const modelSelect = document.getElementById("model-select");

            // Load the saved model from local storage
            const savedModel = localStorage.getItem("selectedModel");
            if (savedModel) {
                modelSelect.value = savedModel;
            }

            // Save the selected model to local storage when changed
            modelSelect.addEventListener("change", () => {
                localStorage.setItem("selectedModel", modelSelect.value);
            });
        });

        // Add a message to the chat container
        function addMessage(message, sender = "user") {
            const chatContainer = document.getElementById("chat-container");
            const messageElement = document.createElement("div");
            messageElement.classList.add("message", sender === "user" ? "user-message" : "bot-message");
            messageElement.textContent = message;
            chatContainer.appendChild(messageElement);
            chatContainer.scrollTop = chatContainer.scrollHeight; // Try to scroll to the bottom
        }

        // Fancy format milliseconds into a more readable format
        function formatDuration(duration) {
            const minutes = Math.floor(duration / (1000 * 60));
            const seconds = Math.floor((duration % (1000 * 60)) / 1000);
            const milliseconds = duration % 1000;
            
            if (minutes > 0) {
                return `${minutes}m ${seconds}.${Math.floor(milliseconds / 10)}s`;
            }
            return `${seconds}.${Math.floor(milliseconds / 10)}s`;
        }

        // Character and word counter
        function updateCounter() {
            const userInput = document.getElementById("user-input");
            const charCount = document.getElementById("char-count");
            const wordCount = document.getElementById("word-count");

            const text = userInput.value;
            const characters = text.length;
            const words = text.trim() ? text.trim().split(/\s+/).length : 0; // Count words

            charCount.textContent = characters;
            wordCount.textContent = words;
        }

        // Event listener to update the counter on input
        document.getElementById("user-input").addEventListener("input", updateCounter);


        async function sendMessage() {
            const userInput = document.getElementById("user-input");
            const userMessage = userInput.value.trim();

            if (!userMessage) return;

            // Check for slash commands
            if (userMessage.toLowerCase() === '/darkmode') {
                toggleDarkMode();
                userInput.value = ""; // Clear input after command
                return;
            }

            if (userMessage.toLowerCase() === '/clear') {
                clearChat();
                userInput.value = ""; // Clear input after command
                return;
            }

            if (userMessage.toLowerCase() === '/help') {
                displayHelp();
                userInput.value = ""; // Clear input after command
                return;
            }

            addMessage(userMessage, "user");
            conversationHistory.push({ role: "user", content: userMessage }); // Add user message to history
            userInput.value = "";

            // Reset the counter
            document.getElementById("char-count").textContent = "0";
            document.getElementById("word-count").textContent = "0";

            // Create and add loading indicator
            const loadingIndicator = document.createElement("div");
            loadingIndicator.id = "loading-indicator";
            loadingIndicator.classList.add("message", "bot-message");
            loadingIndicator.textContent = "...";
            document.getElementById("chat-container").appendChild(loadingIndicator);

            // Start animation for this specific indicator
            const animationInterval = animateLoadingIndicator(loadingIndicator);

            const startTime = Date.now(); // Capture the start time

            try {
                const modelSelect = document.getElementById("model-select");
                const selectedModel = modelSelect.value;
                const retainHistory = document.getElementById("retain-history").checked; // Check the checkbox state

                // Prepare the messages for the API
                const messagesToSend = [
                    { role: "system", content: config.systemMessage },
                    { role: "user", content: userMessage }
                ];

                // Include conversation history only if the checkbox is checked
                if (retainHistory) {
                    messagesToSend.push(...conversationHistory.slice(-config.contextWindowSize * 2)); // Get the last few exchanges
                }

                const response = await fetch(config.apiUrl, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                    },
                    body: JSON.stringify({
                        model: selectedModel,
                        messages: messagesToSend,
                    }),
                });

                if (!response.ok) {
                    throw new Error('Error communicating with Ollama API');
                }

                const data = await response.json();
                console.log("API Response:", data); // Log the response for debugging

                if (data.choices && data.choices.length > 0) {
                    const botResponse = data.choices[0].message.content;

                    // Calculate the duration
                    const duration = Date.now() - startTime; // Time taken in milliseconds

                    // Clear loading indicator
                    clearInterval(animationInterval);
                    loadingIndicator.remove();

                    // Add bot's response to chat
                    addMessage(botResponse, "bot");
                    conversationHistory.push({ role: "bot", content: botResponse }); // Add bot response to history

                    // Display the time taken
                    const timeTakenMessage = formatDuration(duration);
                    const timeDisplay = document.createElement("div");
                    timeDisplay.classList.add("bot-time");
                    timeDisplay.textContent = `Response time: ${timeTakenMessage}`;
                    timeDisplay.style.textAlign = "center"; // Center the text
                    document.getElementById("chat-container").appendChild(timeDisplay); // Append the time display
                } else {
                    console.error("No response from API");
                    loadingIndicator.remove();
                    addMessage("Sorry, I didn't get a response from the assistant.", "bot");
                }

                // Optional: Limit the conversation history to the last 10 messages
                if (conversationHistory.length > 10) {
                    conversationHistory.shift(); // Remove the oldest message
                }

            } catch (error) {
                console.error("Error:", error);
                clearInterval(animationInterval);
                loadingIndicator.remove();
                addMessage("Sorry, there was an error processing your request.", "bot");
            }
        }

        // Basic animmation for the loading indicator
        function animateLoadingIndicator(indicator) {
            let dots = 0;
            return setInterval(() => {
                dots = (dots + 1) % 6;
                if (indicator && document.contains(indicator)) {
                    indicator.textContent = '.'.repeat(dots || 1);
                }
            }, 500);
        }

        // Event listener for the "Send" button
        document.getElementById("send-button").addEventListener("click", sendMessage);

        // Use Enter to send the message, too
        document.getElementById("user-input").addEventListener("keypress", function (e) {
            if (e.key === "Enter") {
                e.preventDefault(); // Prevent line break
                sendMessage();
            }
        });

        function toggleDarkMode() {
            const body = document.body;
            const chatContainer = document.getElementById("chat-container");
            const userInput = document.getElementById("user-input");
            const sendButton = document.getElementById("send-button");

            body.classList.toggle("dark-mode");
            chatContainer.classList.toggle("dark-mode");
            userInput.classList.toggle("dark-mode");
            sendButton.classList.toggle("dark-mode");

            // Update message classes
            const messages = document.querySelectorAll(".message");
            messages.forEach(message => {
                message.classList.toggle("dark-mode");
            });

            // Save preference to local storage
            const isDarkMode = body.classList.contains("dark-mode");
            localStorage.setItem("darkMode", isDarkMode);
        }

        // Load dark mode preference from local storage on page load
        document.addEventListener("DOMContentLoaded", () => {
            const darkModePreference = localStorage.getItem("darkMode");
            if (darkModePreference === "true") {
                toggleDarkMode(); // Activate dark mode if preference is set
            }
        });

        function clearChat() {
            const chatContainer = document.getElementById("chat-container");
            chatContainer.innerHTML = ""; // Clear all messages
            conversationHistory = []; // Clear the conversation history
        }

        function displayHelp() {
            const helpMessage = `
                Available commands:\n
                /darkmode - Toggle dark mode
                /clear - Clear the chat history
                /help - Show this message
            `;
            addMessage(helpMessage, "bot"); // Display help message as a bot message
        }
    </script>
</body>
</html>