Spaces:
Running
Running
| // scripts/chat.js | |
| async function sendMessage() { | |
| const userInput = document.getElementById('user-input'); | |
| const chatMessages = document.getElementById('chat-messages'); | |
| if (userInput.value.trim() === '') return; | |
| // ... (rest of the code to add user message to chat) ... | |
| const userMessage = document.createElement('div'); | |
| userMessage.className = 'chat-bubble user-bubble p-4 w-3/4 ml-auto mb-4 fade-in'; | |
| userMessage.innerHTML = `<p>${userInput.value}</p>`; | |
| chatMessages.appendChild(userMessage); | |
| const userMessageText = userInput.value; | |
| userInput.value = ''; | |
| // --- Start Debugging --- | |
| window.logToScreen('sendMessage triggered. Preparing to fetch...'); | |
| try { | |
| const workerUrl = 'https://YOUR-WORKER-NAME.workers.dev'; // <-- Make sure this URL is correct! | |
| window.logToScreen(`Fetching from: ${workerUrl}`); | |
| const response = await fetch(workerUrl, { | |
| method: 'POST', | |
| headers: { 'Content-Type': 'application/json' }, | |
| body: JSON.stringify({ prompt: userMessageText }), | |
| }); | |
| window.logToScreen(`Fetch response received. Status: ${response.status} ${response.statusText}`); | |
| if (!response.ok) { | |
| window.logToScreen('Response was not OK. See status above.'); | |
| const errorText = await response.text(); | |
| window.logToScreen(`Error response body: ${errorText}`); | |
| throw new Error(`Network response was not ok: ${response.statusText}`); | |
| } | |
| // ... (rest of the code to handle the streaming response) ... | |
| const reader = response.body.getReader(); | |
| const decoder = new TextDecoder(); | |
| let aiResponseText = ''; | |
| while (true) { | |
| const { done, value } = await reader.read(); | |
| if (done) break; | |
| const chunk = decoder.decode(value, { stream: true }); | |
| aiResponseText += chunk; | |
| } | |
| window.logToScreen('Stream finished.'); | |
| // Add final AI response to chat | |
| const aiMessage = document.createElement('div'); | |
| aiMessage.className = 'chat-bubble ai-bubble p-4 w-3/4 fade-in'; | |
| aiMessage.innerHTML = `<p>${aiResponseText}</p>`; | |
| chatMessages.appendChild(aiMessage); | |
| } catch (error) { | |
| window.logToScreen(`FETCH FAILED: ${error.message}`); | |
| // Display a user-friendly error in the chat | |
| const errorMessage = document.createElement('div'); | |
| errorMessage.className = 'chat-bubble ai-bubble p-4 w-3/4 fade-in'; | |
| errorMessage.innerHTML = `<p class="text-red-500">Sorry, an error occurred. Check the debug console for details.</p>`; | |
| chatMessages.appendChild(errorMessage); | |
| } | |
| // --- End Debugging --- | |
| } |