Spaces:
Running
Running
Update scripts/chat.js
Browse files- scripts/chat.js +75 -30
scripts/chat.js
CHANGED
@@ -1,67 +1,112 @@
|
|
1 |
-
//
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
|
|
3 |
async function sendMessage() {
|
4 |
const userInput = document.getElementById('user-input');
|
5 |
const chatMessages = document.getElementById('chat-messages');
|
6 |
|
7 |
-
if (userInput
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
|
15 |
-
|
|
|
|
|
|
|
|
|
|
|
16 |
userInput.value = '';
|
17 |
|
18 |
-
//
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
window.logToScreen('sendMessage triggered. Preparing to fetch...');
|
20 |
|
21 |
try {
|
22 |
-
|
|
|
23 |
window.logToScreen(`Fetching from: ${workerUrl}`);
|
24 |
|
25 |
const response = await fetch(workerUrl, {
|
26 |
method: 'POST',
|
27 |
-
headers: {
|
|
|
|
|
28 |
body: JSON.stringify({ prompt: userMessageText }),
|
29 |
});
|
30 |
|
31 |
window.logToScreen(`Fetch response received. Status: ${response.status} ${response.statusText}`);
|
32 |
|
33 |
if (!response.ok) {
|
34 |
-
window.logToScreen('Response was not OK. See status above.');
|
35 |
const errorText = await response.text();
|
36 |
window.logToScreen(`Error response body: ${errorText}`);
|
37 |
throw new Error(`Network response was not ok: ${response.statusText}`);
|
38 |
}
|
39 |
|
40 |
-
//
|
41 |
const reader = response.body.getReader();
|
42 |
const decoder = new TextDecoder();
|
43 |
-
|
|
|
44 |
while (true) {
|
45 |
const { done, value } = await reader.read();
|
46 |
-
if (done)
|
|
|
|
|
|
|
47 |
const chunk = decoder.decode(value, { stream: true });
|
48 |
-
|
|
|
49 |
}
|
50 |
-
window.logToScreen('Stream finished.');
|
51 |
-
|
52 |
-
// Add final AI response to chat
|
53 |
-
const aiMessage = document.createElement('div');
|
54 |
-
aiMessage.className = 'chat-bubble ai-bubble p-4 w-3/4 fade-in';
|
55 |
-
aiMessage.innerHTML = `<p>${aiResponseText}</p>`;
|
56 |
-
chatMessages.appendChild(aiMessage);
|
57 |
|
58 |
} catch (error) {
|
|
|
59 |
window.logToScreen(`FETCH FAILED: ${error.message}`);
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
}
|
66 |
-
// --- End Debugging ---
|
67 |
}
|
|
|
1 |
+
// --- Helper function for quick prompts ---
|
2 |
+
function quickPrompt(prompt) {
|
3 |
+
const userInput = document.getElementById('user-input');
|
4 |
+
if (userInput) {
|
5 |
+
userInput.value = prompt;
|
6 |
+
sendMessage();
|
7 |
+
} else {
|
8 |
+
window.logToScreen('ERROR: User input field not found for quickPrompt.');
|
9 |
+
}
|
10 |
+
}
|
11 |
|
12 |
+
// --- Main function to send messages to the AI ---
|
13 |
async function sendMessage() {
|
14 |
const userInput = document.getElementById('user-input');
|
15 |
const chatMessages = document.getElementById('chat-messages');
|
16 |
|
17 |
+
if (!userInput || !chatMessages) {
|
18 |
+
window.logToScreen('ERROR: Cannot find chat UI elements.');
|
19 |
+
return;
|
20 |
+
}
|
21 |
+
|
22 |
+
const userMessageText = userInput.value.trim();
|
23 |
+
if (userMessageText === '') return;
|
24 |
|
25 |
+
// 1. Add user's message to the chat window
|
26 |
+
const userBubble = document.createElement('div');
|
27 |
+
userBubble.className = 'chat-bubble user-bubble p-4 w-3/4 ml-auto mb-4 fade-in';
|
28 |
+
userBubble.innerHTML = `<p>${userMessageText}</p>`;
|
29 |
+
chatMessages.appendChild(userBubble);
|
30 |
+
chatMessages.scrollTop = chatMessages.scrollHeight;
|
31 |
userInput.value = '';
|
32 |
|
33 |
+
// 2. Prepare the AI's response bubble (will be filled in as the stream arrives)
|
34 |
+
const aiBubble = document.createElement('div');
|
35 |
+
aiBubble.className = 'chat-bubble ai-bubble p-4 w-3/4 fade-in';
|
36 |
+
const aiParagraph = document.createElement('p');
|
37 |
+
aiBubble.appendChild(aiParagraph);
|
38 |
+
chatMessages.appendChild(aiBubble);
|
39 |
+
chatMessages.scrollTop = chatMessages.scrollHeight;
|
40 |
+
|
41 |
+
|
42 |
+
// 3. Start the fetch process and log everything
|
43 |
window.logToScreen('sendMessage triggered. Preparing to fetch...');
|
44 |
|
45 |
try {
|
46 |
+
// IMPORTANT: Replace this with your actual Cloudflare Worker URL
|
47 |
+
const workerUrl = 'https://stream-ai-backend.your-username.workers.dev';
|
48 |
window.logToScreen(`Fetching from: ${workerUrl}`);
|
49 |
|
50 |
const response = await fetch(workerUrl, {
|
51 |
method: 'POST',
|
52 |
+
headers: {
|
53 |
+
'Content-Type': 'application/json',
|
54 |
+
},
|
55 |
body: JSON.stringify({ prompt: userMessageText }),
|
56 |
});
|
57 |
|
58 |
window.logToScreen(`Fetch response received. Status: ${response.status} ${response.statusText}`);
|
59 |
|
60 |
if (!response.ok) {
|
|
|
61 |
const errorText = await response.text();
|
62 |
window.logToScreen(`Error response body: ${errorText}`);
|
63 |
throw new Error(`Network response was not ok: ${response.statusText}`);
|
64 |
}
|
65 |
|
66 |
+
// 4. Handle the streaming response
|
67 |
const reader = response.body.getReader();
|
68 |
const decoder = new TextDecoder();
|
69 |
+
window.logToScreen('Stream starting...');
|
70 |
+
|
71 |
while (true) {
|
72 |
const { done, value } = await reader.read();
|
73 |
+
if (done) {
|
74 |
+
window.logToScreen('Stream finished.');
|
75 |
+
break;
|
76 |
+
}
|
77 |
const chunk = decoder.decode(value, { stream: true });
|
78 |
+
aiParagraph.textContent += chunk; // Append chunk to the AI's paragraph
|
79 |
+
chatMessages.scrollTop = chatMessages.scrollHeight; // Keep scrolling
|
80 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
|
82 |
} catch (error) {
|
83 |
+
// Log the error and display a message in the UI
|
84 |
window.logToScreen(`FETCH FAILED: ${error.message}`);
|
85 |
+
aiParagraph.textContent = "Sorry, an error occurred. Check the debug console for details.";
|
86 |
+
aiParagraph.style.color = 'red';
|
87 |
+
}
|
88 |
+
}
|
89 |
+
|
90 |
+
|
91 |
+
// --- Initialization function for the chat module ---
|
92 |
+
export function initChat() {
|
93 |
+
const sendBtn = document.getElementById('send-btn');
|
94 |
+
const userInput = document.getElementById('user-input');
|
95 |
+
|
96 |
+
if (sendBtn && userInput) {
|
97 |
+
sendBtn.addEventListener('click', sendMessage);
|
98 |
+
userInput.addEventListener('keypress', (e) => {
|
99 |
+
if (e.key === 'Enter') {
|
100 |
+
sendMessage();
|
101 |
+
}
|
102 |
+
});
|
103 |
+
|
104 |
+
// Make quickPrompt globally accessible for the inline HTML onclick attributes
|
105 |
+
window.quickPrompt = quickPrompt;
|
106 |
+
} else {
|
107 |
+
// Use the logger in case the elements don't exist
|
108 |
+
if (window.logToScreen) {
|
109 |
+
window.logToScreen("ERROR: Could not find 'send-btn' or 'user-input' to initialize chat.");
|
110 |
+
}
|
111 |
}
|
|
|
112 |
}
|