OffloadGPT API
  • Introduction
  • Quick Start
  • Server Events
  • Reference
    • API Reference
      • stream-chatgpt endpoint
      • async-chatgpt endpoint
      • Status URL endpoints
Powered by GitBook
On this page

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 */
}
PreviousQuick StartNextAPI Reference

Last updated 2 years ago