AI implementation for openai and claude.
This commit is contained in:
73
script.js
73
script.js
@@ -4,6 +4,8 @@ const chatMessages = document.getElementById("chatMessages");
|
||||
const welcomeInput = document.getElementById("welcomeInput");
|
||||
const chatInput = document.getElementById("chatInput");
|
||||
|
||||
const API_URL = "http://localhost:8000/api/chat";
|
||||
|
||||
let isInChat = false;
|
||||
|
||||
function switchToChat() {
|
||||
@@ -53,7 +55,7 @@ function escapeHtml(text) {
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
function sendMessage(text) {
|
||||
async function sendMessage(text) {
|
||||
if (!text.trim()) return;
|
||||
|
||||
if (!isInChat) {
|
||||
@@ -66,15 +68,72 @@ function sendMessage(text) {
|
||||
|
||||
showTyping();
|
||||
|
||||
setTimeout(() => {
|
||||
try {
|
||||
const response = await fetch(`${API_URL}/stream`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
message: text,
|
||||
provider: null,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
hideTyping();
|
||||
addMessage(
|
||||
"I'm DevDen - your AI assistant. Soon I'll be connected to your knowledge base!",
|
||||
"assistant",
|
||||
);
|
||||
|
||||
// Create message element for streaming
|
||||
const msgDiv = document.createElement("div");
|
||||
msgDiv.className = "message assistant";
|
||||
const textDiv = document.createElement("div");
|
||||
textDiv.className = "message-text";
|
||||
msgDiv.appendChild(textDiv);
|
||||
chatMessages.appendChild(msgDiv);
|
||||
|
||||
// Read stream
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let assistantMessage = "";
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
const chunk = decoder.decode(value);
|
||||
const lines = chunk.split("\n");
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith("data: ")) {
|
||||
const data = JSON.parse(line.slice(6));
|
||||
|
||||
if (data.error) {
|
||||
textDiv.textContent = `Error: ${data.error}`;
|
||||
break;
|
||||
}
|
||||
|
||||
if (data.chunk) {
|
||||
assistantMessage += data.chunk;
|
||||
textDiv.textContent = assistantMessage;
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
if (data.done) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
hideTyping();
|
||||
addMessage(`Error: ${error.message}`, "assistant");
|
||||
} finally {
|
||||
chatInput.disabled = false;
|
||||
chatInput.focus();
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
// Welcome screen input handler
|
||||
|
||||
Reference in New Issue
Block a user