60 lines
2.0 KiB
JavaScript
60 lines
2.0 KiB
JavaScript
document.addEventListener("DOMContentLoaded", async () => {
|
|
const output = document.getElementById("output");
|
|
|
|
llmToken = await getLLMToken();
|
|
const auth = await loadUserToken();
|
|
if (!auth) {
|
|
handleLogout(auth);
|
|
}
|
|
const userToken = auth.token;
|
|
const url = "http://app-test.wisdompulse.cn/api/v1/llm/ask";
|
|
const question = "请背诵王勃的《滕王阁序》全文,开头是'豫章故郡,洪都新府'这句,并基于这篇文章写一个小故事"
|
|
const body = { llmToken, question };
|
|
|
|
fetch(url, {
|
|
method: "POST",
|
|
headers: {
|
|
"Authorization": `${userToken}`,
|
|
"Accept": "text/event-stream",
|
|
"Content-Type": "application/json"
|
|
},
|
|
body: JSON.stringify(body)
|
|
}).then(response => {
|
|
const reader = response.body.getReader();
|
|
const decoder = new TextDecoder("utf-8");
|
|
let buffer = "";
|
|
|
|
function read() {
|
|
reader.read().then(({ done, value }) => {
|
|
if (done) {
|
|
output.textContent += "\n[连接结束]";
|
|
return;
|
|
}
|
|
|
|
buffer += decoder.decode(value, { stream: true });
|
|
|
|
// 拆解成 SSE 事件格式:每段以 \n\n 分隔
|
|
const parts = buffer.split('\n\n');
|
|
buffer = parts.pop(); // 留给下一次未完整的部分
|
|
|
|
for (const part of parts) {
|
|
const line = part.trim();
|
|
if (line.startsWith('data:')) {
|
|
const jsonStr = line.substring(5).trim();
|
|
try {
|
|
const data = JSON.parse(jsonStr);
|
|
output.textContent += `${data.textResponse || '[无内容]'}`;
|
|
} catch (e) {
|
|
output.textContent += `解析失败:${jsonStr}\n`;
|
|
}
|
|
}
|
|
}
|
|
|
|
read();
|
|
});
|
|
}
|
|
|
|
read();
|
|
});
|
|
});
|