I tried using showdownjs to translate streamed markdown from OpenAi to HTML
I changed the code given at https://github.com/orhanerday/ChatGPT and just added the showdown part
The system prompt to OpenAi includes returning responses using markdown, which it does
After the showdownjs parsed , the results are weird. Each chunk is in a separate line and the markdown isn't parsed!
let converter = new showdown.Converter({smoothLivePreview: true});
let parsedHtml = converter.makeHtml(txt);
div.innerHTML += parsedHtml;
The data does come back from the backend as a stream
Am totally flummoxed. What am i doing wrong here? I have the references all included and the data does come back from the php file in the backend.
Thanks in advance
EDITED
I just realized that showdown is adding a "html p" tag around every word in every stream:-( And, the text with markdown (sometimes incomplete in the chunk), do not get processed and converted to html :-(
I finally figured out a very simple solution. Duh.
I decided to use the markdown-it library from https://github.com/markdown-it/markdown-it
And in the above code, rather than applying markdown when the text is streamed, i do it at the end on getting "done"
Am reproducing just the relevant part of the code here for brevity, with my solution. works like charm. Should have thought of it before! Ideally, i would like it to happen when the data streams, but looks like that is either not possible or too much hard work !!!
if (e.data == "[DONE]") {
msgerSendBtn.disabled = false;
document.getElementById("userSendButtonAV").value="Send";
var elemB = document.getElementById("userSendButtonAV");
elemB.value = "Send";
const md = window.markdownit();
const renderedText = md.render(div.innerText);
div.innerHTML = renderedText;
document.getElementById('userMessageAV').placeholder='Enter your message now...';
document.getElementById('userMessageAV').disabled = false;
eventSource.close();
} else {
//original code let txt = JSON.parse(e.data).choices[0].delta.content
if (isJsonString(e.data)) {
let txt = JSON.parse(e.data).choices[0].delta.content;
if (txt !== undefined) {
div.innerHTML += txt.replace(/(?:\r\n|\r|\n)/g, '<br>');
}
}
}