teststatic / index.js
hsuwill000's picture
Update index.js
e2becb6 verified
import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";
(async () => {
const chatWindow = document.getElementById("chat-window");
const userInput = document.getElementById("userMessage");
const sendBtn = document.getElementById("sendBtn");
let client;
let isConnected = false;
function pushMessage(role, text) {
const wrap = document.createElement("div");
wrap.className = `message ${role}`;
const bubble = document.createElement("div");
bubble.className = "bubble";
bubble.textContent = text;
wrap.appendChild(bubble);
chatWindow.appendChild(wrap);
chatWindow.scrollTop = chatWindow.scrollHeight;
}
async function connectClient() {
pushMessage("assistant", "Connecting to model...");
try {
client = await Client.connect("amd/gpt-oss-120b-chatbot");
isConnected = true;
pushMessage("assistant", "已連線,開始對話吧!");
} catch (err) {
pushMessage("assistant", "連線失敗: " + String(err));
console.error(err);
}
}
async function sendChat() {
if (!isConnected) {
await connectClient();
if (!isConnected) return;
}
const message = userInput.value.trim();
if (!message) return;
sendBtn.disabled = true;
pushMessage("user", message);
try {
// 如果你有固定的 system_prompt 可以直接填這裡
const system_prompt = "You are a helpful assistant.";
const result = await client.predict("/chat", {
message,
system_prompt,
temperature: 0,
});
const assistantText =
result && result.data ? String(result.data) : "No response";
pushMessage("assistant", assistantText);
} catch (err) {
console.error(err);
pushMessage("assistant", "Error: " + String(err));
} finally {
sendBtn.disabled = false;
userInput.value = "";
userInput.focus();
}
}
sendBtn.addEventListener("click", sendChat);
userInput.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
sendChat();
}
});
connectClient();
})();