cchat/static/js/index.js

264 lines
7.7 KiB
JavaScript
Raw Normal View History

2024-07-19 00:10:34 +02:00
document.addEventListener("alpine:init", () => {
Alpine.data("state", () => ({
// current state
cstate: {
time: null,
messages: [],
},
2024-07-20 06:07:29 +02:00
allMessages: [],
displayMessages: [],
2024-07-19 00:10:34 +02:00
// historical state
histories: JSON.parse(localStorage.getItem("histories")) || [],
home: 0,
generating: false,
endpoint: window.location.origin + "/v1",
2024-07-20 02:50:56 +02:00
model: "llama3-groq-70b-8192-tool-use-preview",
stopToken: "sfjsdkfjsljflksdkj",
2024-07-19 00:10:34 +02:00
// performance tracking
time_till_first: 0,
tokens_per_second: 0,
total_tokens: 0,
2024-07-19 03:12:21 +02:00
// New property for error messages
errorMessage: null,
2024-07-20 02:50:56 +02:00
// Debug mode
debug: false,
2024-07-19 00:10:34 +02:00
removeHistory(cstate) {
const index = this.histories.findIndex((state) => {
return state.time === cstate.time;
});
if (index !== -1) {
this.histories.splice(index, 1);
localStorage.setItem("histories", JSON.stringify(this.histories));
}
},
2024-07-20 06:07:29 +02:00
resetChat() {
this.cstate = {
time: null,
messages: [],
};
this.allMessages = [];
this.displayMessages = [];
this.total_tokens = 0;
this.time_till_first = 0;
this.tokens_per_second = 0;
},
loadChat(chatState) {
this.cstate = JSON.parse(JSON.stringify(chatState)); // Deep copy
this.allMessages = [...this.cstate.messages];
this.displayMessages = [...this.cstate.messages];
this.home = 1;
this.updateTotalTokens(this.allMessages);
},
2024-07-19 00:10:34 +02:00
async handleSend() {
const el = document.getElementById("input-form");
const value = el.value.trim();
if (!value) return;
if (this.generating) return;
this.generating = true;
2024-07-20 02:50:56 +02:00
this.errorMessage = null;
2024-07-20 06:07:29 +02:00
// If it's a new chat or there are no messages, reset the chat
if (this.home === 0 || this.cstate.messages.length === 0) {
this.resetChat();
}
2024-07-19 00:10:34 +02:00
if (this.home === 0) this.home = 1;
window.history.pushState({}, "", "/");
2024-07-20 06:07:29 +02:00
const userMessage = { role: "user", content: value };
this.cstate.messages.push(userMessage);
this.allMessages.push(userMessage);
this.displayMessages.push(userMessage);
2024-07-19 00:10:34 +02:00
el.value = "";
el.style.height = "auto";
el.style.height = el.scrollHeight + "px";
const prefill_start = Date.now();
let start_time = 0;
let tokens = 0;
this.tokens_per_second = 0;
2024-07-19 03:12:21 +02:00
try {
2024-07-20 06:07:29 +02:00
let currentAssistantMessage = null;
for await (const chunk of this.openaiChatCompletion(this.allMessages)) {
2024-07-20 02:50:56 +02:00
if (chunk.role === "function") {
2024-07-20 06:07:29 +02:00
if (currentAssistantMessage) {
this.allMessages.push(currentAssistantMessage);
this.displayMessages.push(currentAssistantMessage);
currentAssistantMessage = null;
}
this.allMessages.push(chunk);
2024-07-20 02:50:56 +02:00
if (this.debug) {
2024-07-20 06:07:29 +02:00
this.displayMessages.push(chunk);
2024-07-20 02:50:56 +02:00
}
2024-07-19 03:12:21 +02:00
} else {
2024-07-20 06:07:29 +02:00
if (!currentAssistantMessage) {
currentAssistantMessage = { role: "assistant", content: "" };
2024-07-20 02:50:56 +02:00
}
2024-07-20 06:07:29 +02:00
currentAssistantMessage.content += chunk;
2024-07-20 02:50:56 +02:00
tokens += 1;
this.total_tokens += 1;
if (start_time === 0) {
start_time = Date.now();
this.time_till_first = start_time - prefill_start;
} else {
const diff = Date.now() - start_time;
if (diff > 0) {
this.tokens_per_second = tokens / (diff / 1000);
}
2024-07-19 03:12:21 +02:00
}
2024-07-19 00:10:34 +02:00
}
}
2024-07-20 06:07:29 +02:00
// Add any pending assistant message
if (currentAssistantMessage) {
this.allMessages.push(currentAssistantMessage);
this.displayMessages.push(currentAssistantMessage);
}
// Update total tokens using all messages
this.updateTotalTokens(this.allMessages);
// Update cstate.messages with displayMessages
this.cstate.messages = [...this.displayMessages];
2024-07-20 02:50:56 +02:00
const index = this.histories.findIndex(
(cstate) => cstate.time === this.cstate.time,
);
2024-07-19 03:12:21 +02:00
this.cstate.time = Date.now();
if (index !== -1) {
this.histories[index] = this.cstate;
} else {
this.histories.push(this.cstate);
}
localStorage.setItem("histories", JSON.stringify(this.histories));
} catch (error) {
console.error("Error in handleSend:", error);
this.showError(
error.message || "An error occurred processing your request.",
);
} finally {
this.generating = false;
2024-07-19 00:10:34 +02:00
}
},
async handleEnter(event) {
if (!event.shiftKey) {
event.preventDefault();
await this.handleSend();
}
},
2024-07-19 03:12:21 +02:00
showError(message) {
this.errorMessage = message;
setTimeout(() => {
this.errorMessage = null;
2024-07-20 02:50:56 +02:00
}, 3000);
2024-07-19 03:12:21 +02:00
},
2024-07-19 00:10:34 +02:00
updateTotalTokens(messages) {
fetch(`${window.location.origin}/v1/tokenizer/count`, {
method: "POST",
headers: { "Content-Type": "application/json" },
2024-07-20 06:07:29 +02:00
body: JSON.stringify({ messages: this.allMessages }), // Always use allMessages for token counting
2024-07-19 00:10:34 +02:00
})
2024-07-19 03:12:21 +02:00
.then((response) => {
if (!response.ok) {
throw new Error("Failed to count tokens");
}
return response.json();
})
2024-07-19 00:10:34 +02:00
.then((data) => {
this.total_tokens = data.token_count;
})
2024-07-19 03:12:21 +02:00
.catch((error) => {
console.error("Error updating total tokens:", error);
this.showError("Failed to update token count. Please try again.");
});
2024-07-19 00:10:34 +02:00
},
async *openaiChatCompletion(messages) {
2024-07-19 03:12:21 +02:00
try {
const response = await fetch(`${this.endpoint}/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify({
model: this.model,
messages: messages,
stream: true,
stop: [this.stopToken],
}),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || "Failed to fetch");
2024-07-19 00:10:34 +02:00
}
2024-07-19 03:12:21 +02:00
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop();
for (const line of lines) {
if (line.startsWith("data: ")) {
const data = line.slice(6);
if (data === "[DONE]") return;
try {
const json = JSON.parse(data);
2024-07-20 02:50:56 +02:00
if (json.choices && json.choices[0].delta) {
const delta = json.choices[0].delta;
if (delta.role === "function") {
// Yield the entire function message
yield {
role: "function",
name: delta.name,
content: delta.content,
};
} else if (delta.content) {
yield delta.content;
}
2024-07-19 03:12:21 +02:00
}
} catch (error) {
console.error("Error parsing JSON:", error);
2024-07-19 00:10:34 +02:00
}
}
}
}
2024-07-19 03:12:21 +02:00
} catch (error) {
console.error("Error in openaiChatCompletion:", error);
this.showError(
error.message ||
"An error occurred while communicating with the server.",
);
throw error;
2024-07-19 00:10:34 +02:00
}
},
}));
});