Как получить потоковый ответ от openAIchat-gpt-4?

Я слышал, что вы можете получать ответы в потоковом режиме через Chat-GPT-4, но не нашел много информации об этом. Если я спрошу сам чат-gpt, он мне скажет, что по данным 2021 года такой функции нет. Могу ли я использовать потоковую передачу и как?

1 ответ

Да, ты можешь.

Во-первых, ссылка на API находится здесь:https://platform.openai.com/docs/api-reference/chat/create .

Прокрутите вниз до пункта «поток». Это логическое значение.

Во-вторых, вот готовый пример JavaScript с самыми простыми инструментами. Некрасиво, но это работает. Если вы запустите его, вы увидите, как дельты появляются и печатаются в консоли. Веселиться.

      (function() {
// Define the API endpoint
const apiEndpoint = "https://api.openai.com/v1/chat/completions";
const headers = {
  "Content-Type": "application/json",
  "Authorization": "Bearer xxxxx", // replace with your actual OpenAI key
};

// Define the data to be sent
const data = {
  model: "gpt-4",
  messages: [{
    role: "user", 
    content: "Tell me more about XYZ." // <<<<< This is your prompt.
  }],
  stream: true  // <<<< Peek-a-boo
};

// Make the API request
fetch(apiEndpoint, {
  method: "POST",
  headers: headers,
  body: JSON.stringify(data)
})
  .then((response) => {
    const reader = response.body.getReader();
    return new ReadableStream({
      start(controller) {
        return pump();
        function pump() {
          return reader.read().then(({ done, value }) => {
            // When no more data needs to be consumed, close the stream
            if (done) {
              controller.close();
              return;
            }
            // Enqueue the next data chunk into our target stream
            controller.enqueue(value);

            //debugger;

            let chars = new TextDecoder().decode(value);
            let lines = chars.split('data:');
            for (let i=0; i < lines.length; i++) {
                chars = lines[i].replace(/\s*/, '').replace(/\s*$/, '');
                if (!chars) {
                    continue;
                }
                //debugger;
                //chars = lines[i].replace(/data: *(\{.*)\s*/g, '$1');
                //chars = chars.replace('\\"', '"');
                let obj = JSON.parse(chars);
                if (obj && obj.choices[0].delta) {
                    let deltaS = obj.choices[0].delta.content;
                    console.log(deltaS);
                }
            }
//          console.log('Received: ' + chars.join(''));
            return pump();
          });
        }
      },
    });
  })
  .then((stream) => new Response(stream))
  .then((response) => response.json())
  .then((responseJson) => {
    // Here, you get the whole response object.
    // Loop over the 'choices' array to get each individual message.
    responseJson['choices'].forEach((choice) => {
      //console.log(choice['message']['content']);
    });
  })
  .catch((err) => console.error(err));
})();
  
Другие вопросы по тегам