EventSource
let url="请求地址?message="+str
let content="";
let text="";
// 检查浏览器是否支持原生EventSource
if (typeof EventSource !== "undefined"){
var source = new EventSource(url);
} else {
// 如果不支持,则使用polyfill
var source = new EventSourcePolyfill(url);
}
source.onmessage = function(event) {
if (event.data.endsWith('[DONE]')) {
source.close();
console.log('connection is closed');
list.push({
role:"assistant",
content:content
})
}else{
let obj=JSON.parse(event.data).choices[0];
if(obj.delta.role){
$("#znfw").append(`<div class="znfw_item znfw_ans"><div></div></div> `)
}
if(obj.delta.content){
content+=obj.delta.content;
displayText(content); // 开始显示文本
}
}
};
source.onerror = function(event){
console.log("Error occurred in EventSource.");
source.close();
};
全部代码
let flag=true;
let list=[
{role:"assistant",content:"Hi,我是机器人,可以解答您的问题"}
]
function displayText(data) {
let str_ = '';
let i = 0;
const content = $(".znfw_ans").find(">:first-child")[$(".znfw_ans").length-1];
const timer = setInterval(() => {
if (str_.length < data.length) {
str_ += data[i++];
content.html(str_);
} else {
clearInterval(timer);
content.innerHTML =str_;
}
}, 100);
}
function sendMessage(str){
let url=ajaxUrl+"/ls-ai/chatFlux?message="+str
let content="";
let text="";
// 检查浏览器是否支持原生EventSource
if (typeof EventSource !== "undefined"){
var source = new EventSource(url);
} else {
// 如果不支持,则使用polyfill
var source = new EventSourcePolyfill(url);
}
source.onmessage = function(event) {
if (event.data.endsWith('[DONE]')) {
source.close();
console.log('connection is closed');
list.push({
role:"assistant",
content:content
})
}else{
let obj=JSON.parse(event.data).choices[0];
if(obj.delta.role){
$("#znfw").append(`<div class="znfw_item znfw_ans"><div></div></div> `)
}
if(obj.delta.content){
content+=obj.delta.content;
displayText(content); // 开始显示文本
}
}
};
source.onerror = function(event){
console.log("Error occurred in EventSource.");
source.close();
};
}
$('.search_btn').off('click').on('click',function(){
if(!flag){return}
let text = $('.search_input').val();
if(text.trim().length===0){return}
if(text == '') return;
$('.znfw').append(`<div class="znfw_item znfw_que"><div>${text}</div></div>`);
//请求答案
//清空
$('.search_input').val('');
//滚动到底部
$('.znfw').scrollTop($('.znfw')[0].scrollHeight);
//聚焦
$('.search_input').focus();
sendMessage(text)
});
$('.search_input').off('keyup').on('keyup',function(e){
if(!flag){return}
if(e.keyCode===13){
let text = $(this).val();
if(text.trim().length===0){return}
if(text == '') return;
$('.znfw').append(`<div class="znfw_item znfw_que"><div>${text}</div></div>`);
//请求答案
//清空
$('.search_input').val('');
//滚动到底部
$('.znfw').scrollTop($('.znfw')[0].scrollHeight);
//聚焦
$('.search_input').focus();
sendMessage(text)
}
});