Server Events
(pending section, here will be examples of use)
let html = '';
const eventSource = new EventSource(url);
eventSource.onmessage = function(e) {
if (!e || !e.data) {
onMessageEnd();
return;
}
if (e.data == "[DONE]") {
onMessageEnd();
return;
}
const messageItem = parseEventData(e.data);
if (!messageItem) {
return;
}
const choice = messageItem.choices[0];
let txt = choice.delta.content;
if (null === txt || undefined === txt) {
return;
}
txt = '' + txt;
if ('' !== txt) {
html += txt;
theContentDiv.innerHTML = txt;
}
if (choice.finish_reason) {
onMessageEnd();
}
}
eventSource.onerror = function(e) {
console.log(e);
onMessageEnd();
}
function parseEventData(data) {
let obj = null;
try {
obj = JSON.parse(data);
if (!obj || !obj.choices) {
return false;
}
} catch(e) {
return false;
}
return obj;
}
function onMessageEnd() {
/* Code for finalized message */
}
Last updated