XD2Sketch / react-chat-stream

⚛️ React Hook to add 🤖 ChatGPT-like word-by-word event streams
https://www.npmjs.com/package/@magicul/react-chat-stream
MIT License
55 stars 10 forks source link

Parse Server Response #20

Open ttessarolo opened 9 months ago

ttessarolo commented 9 months ago

Hi – the decode process works fine only if the server respond with just strings.

But the Server-Sent Events (SSE) standard implies a more complex response:

interface EventMessage {
  /**
   * Message payload
   */
  data?: string;

  /**
   * Message identifier, if set, client will send `Last-Event-ID: <id>` header on reconnect
   */
  id?: string;

  /**
   * Message type
   */
  event?: string;

  /**
   * Update client reconnect interval (how long will client wait before trying to reconnect).
   */
  retry?: number;

  /**
   * Message comment
   */
  comment?: string;
}

Fort that reason I suggest to add an option to let the code not just parse simple text answers but also a SSE compliant response.

Inside the decodeStreamToJson function you could parse the complex response like that:

const decoded = decoder.decode(value);
        const splitted = decoded
          .split("\n")
          .filter((s) => {
            if (s?.startsWith("data:")) return true;
            return false;
          })
          .map((s) => s.replace("data: ", ""));

        if (splitted.length > 0 && splitted[0] !== "Stream closed") {
          yield splitted[0];
        }

Just a suggestion. Thanks for this Hook ;)

niels-bosman commented 7 months ago

Hi @ttessarolo, thanks for the suggestion! Feel free to create a PR with this solution and I will test it out.