Streaming data from json into chat bubble

25 Views Asked by At

I am doing a POC application for streaming content from GPT into my conversation application using angular. I am collecting the streamed data using fetch and pushing the data into json and displaying them in a chat bubble UI. If its shorter chunk the content is pushed into one value in json and i am able to display the content as received within a bubble but when the content chunk is more than 1 .. the json collects multiple value and each chat bubble display one content. I want all stream values getting display within same chat bubble.

I tried to add a input field and write the content directly by document.getElementById('chat').innerHTML += token + "
" this works fine but i am looking option to write the stream value in a chat bubble.

Any idea or suggestion to get it achieved.

    let response = await fetch(environment.stream, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: data
        });
    
        const reader = response.body?.pipeThrough(new TextDecoderStream()).getReader();
        if (!reader) return;
        // eslint-disable-next-line no-constant-condition
        while (true) {
          // eslint-disable-next-line no-await-in-loop
          const { value, done } = await reader.read();
          if (done) break;
          let dataDone = false;
          const arr = value.split('\n');
          let jsonContent: string
          arr.forEach((data) => {
            if (data.length === 0) return; // ignore empty message
            if (data.startsWith(':')) return; // ignore sse comment message
            if (data === 'data: [DONE]') {
              dataDone = true;
              return;
            }
    
            if (data.endsWith('.') || data.endsWith('!') || data.endsWith('?') || data.endsWith(":")) {
              this.messageObj.push({ "Msg": data, "user": "GPT" })     
              this.scrollToBottom()
            } else {
              this.messageObj.push({ "Msg": data, "user": "GPT" })
              this.scrollToBottom()
            }
          });
          if (dataDone)
            break;

angular.component.html

<div class="chat-area">
          <div *ngFor="let msg of messageObj" class="chat-bubble-container" [ngClass]="{'sender' : msg.user === uName}">
            <div class="chat-bubble" id="bubble">
              <p [innerText]="msg.Msg"></p>
              <span class="chat-date">
                {{msg.user}}
              </span>
            </div>
          </div>
      </div>
0

There are 0 best solutions below