init
This commit is contained in:
59
assets/js/chat.js
Normal file
59
assets/js/chat.js
Normal file
@@ -0,0 +1,59 @@
|
||||
const mujianSdk = new window.MujianUMD.MujianSdk();
|
||||
|
||||
async function chat(
|
||||
query,
|
||||
cb,
|
||||
) {
|
||||
let lastChunk = '';
|
||||
// 让缓冲区跨回调持久,防止分包导致的半行重复解析
|
||||
let buffer = '';
|
||||
await mujianSdk.ai.chat.complete(query, (data) => {
|
||||
|
||||
// data 可能是块状字符串;避免逐字符遍历
|
||||
buffer += data;
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() || '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line.startsWith('data: ')) continue;
|
||||
const payload = line.slice(6);
|
||||
try {
|
||||
const parsedData = JSON.parse(payload);
|
||||
if (parsedData?.isFinished) {
|
||||
// 结束标志,交给外层 await 完成
|
||||
continue;
|
||||
}
|
||||
|
||||
let content = parsedData?.choices?.[0]?.delta?.content;
|
||||
// if (content && typeof window !== 'undefined') {
|
||||
// const username = localStorage.getItem(USERNAME_KEY) || 'User';
|
||||
// content = content?.replace(new RegExp(FAKE_USERNAME, 'g'), username);
|
||||
// }
|
||||
|
||||
if (content !== undefined && content !== null) {
|
||||
if (content.length > 0) {
|
||||
lastChunk += content;
|
||||
cb && cb(lastChunk);
|
||||
}
|
||||
} else {
|
||||
console.error('data', payload);
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('error', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// console.log('lastChunk', lastChunk);
|
||||
return lastChunk;
|
||||
}
|
||||
|
||||
|
||||
mujianSdk.init().then(() => {
|
||||
chat('你好', (res) => {
|
||||
// console.log('res', res)
|
||||
$('#message').text(res);
|
||||
})
|
||||
});
|
||||
Reference in New Issue
Block a user