How can show a streaming output in a frontend and do it progressively?

Hi, I am making an app using assistants api and I was wondering.

How does openai do to show their outputs in a frontend with a specific format?

For example, if I use stream I can watch the output, but it is in plain text, then I tell chatgpt that give the text in markdown format to after that render the text and add it in my html template.

But how can I give it format while I add the text progressively?.

This is a code example, I was using streams, but I think that this represents the situation:

 const parser = new DOMParser();
 const doc = parser.parseFromString(msg, 'text/html');

      // -----------------If there is an image-----------------
      if('img' in data){

        resultHtml = md.render(msg); // render markdown text
        $(`#${id} .m-2`).append(resultHtml); // add text
        $(`#${id} .m-2`).append(`<img src="data:image/png;base64,${data['img']}" class="img-fluid">`);// add img

      // -----------------If the response is a table in html format-----------------
      }else if (Array.from(doc.body.childNodes).some(node => node.nodeType === 1)) {

        const table = `
        <div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
      <p class="fw-semibold">Tabla generada</p>
    </div>
    <div class="card-body">
      <div class="container">
        <div class="table-responsive">
          ${doc.body.innerHTML}
        </div>
      </div>
    </div>
  </div>`;

        $(`#${id} .m-2 p`).html(table);//add html table
        $('table').addClass('table table-warning table-bordered table-hover');
        $(`#${id} #chatbot-message-content`).addClass('flex-column');

      // -----------------If the response is markdown text-----------------
      }else{
      
        resultHtml = md.render(msg); // render markdown text
        $(`#${id} .m-2 p`).append(resultHtml);// add text
      
      }

If after get a stream chunk I try to render and put in my html template, the library that I use to transform markdown to html ‘markdown-it.min.js’ add strange characters when a chunk is not complete and I get a strange mix of characteres in my html, for example:

sentence:
# Hello world

stream:
<h1>Hello

render:
#$Hello)?

as you can see I don’t get html tags while I stream.

How does openai do to show their outputs in a frontend with a specific format while do streams?

Thank you.

the default text output is already in markdown format. it may not be apparent just looking at the plain text but it contains newline. if you ask it to make some parts bold or italics, you’ll see the markdown. right now, i just tested sending text chunks is to some other markdown lib (i’m using react) and it has no problem rendering partial texts.