【Nuxt.js】Displaying Streaming Responses from ChatGPT API using Nuxt.js

2023年4月14日

In this article, we’ll explain how to display streaming responses from the ChatGPT API or other streaming APIs using Nuxt.js. Since the standard Nuxt.js library Axios does not support responseType: 'stream', we will provide a code example that uses XMLHttpRequest to send a request to the API and update the user interface with the received data in real-time.

<template>
  <div>
    <input v-model="text" type="text" placeholder="Enter text here" />
    <button @click="getStreamMessage" :disabled="btn_loading">Get Streaming Message</button>
    <pre>{{ message }}</pre>
  </div>
</template>

<script>
import { getCookie } from '~/utils/cookies';

export default {
  data() {
    return {
      text: '',
      message: '',
      btn_loading: false,
    };
  },
  methods: {
    getStreamMessage() {
      this.message = '';
      const data = JSON.stringify({
        text: this.text,
      });
      const xhr = new XMLHttpRequest();
      xhr.open('POST', `${process.env.BASE_URL}/api/stream_sns`);
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.setRequestHeader('Authorization', ***);
      xhr.responseType = 'text';
      xhr.addEventListener('readystatechange', () => {
        if (xhr.readyState === xhr.HEADERS_RECEIVED) {
          const contentLength = xhr.getResponseHeader('Content-Length');
          console.log(`Content-Length: ${contentLength}`);
        } else if (xhr.readyState === xhr.LOADING) {
          const text = xhr.responseText;
          this.message = text;
        } else if (xhr.readyState === xhr.DONE) {
          console.log('Streaming response finished.');
        }
      });
      xhr.send(data);
    },
  },
};
</script>

When using the fetch API

async getStreamMessage() {
  this.message = '';
  const data = JSON.stringify({
    text: this.text,
  });

  try {
    const response = await fetch(`${process.env.BASE_URL}/api/stream_sns`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': *****,
      },
      body: data,
    });

    if (response.status !== 200) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();

    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        console.log('Streaming response finished.');
        break;
      }

      const text = decoder.decode(value, { stream: true });
      this.message += text;
    }
  } catch (error) {
    console.error('Error fetching streaming response:', error);
  } finally {
  }
},

This code example demonstrates how to use XMLHttpRequest to send a request containing user-input text to the API and display the streaming response in real-time. By doing this, users can benefit from real-time responses and efficient data processing.

other

Posted by Next-k