我如何使用服务器发送事件来流数据从OpenAI的API使用 AJAX 和PHP?

wljmcqd8  于 2023-02-15  发布在  PHP
关注(0)|答案(1)|浏览(299)

如何使用服务器发送事件(SSE)将数据从上述API流传输到使用JavaScript和PHP的浏览器客户端?我已经研究了几个小时,但似乎找不出问题所在。作为参考,我尝试在这里修改解决方案:Stream DATA From openai GPT-3 API using PHP
我的代码的其余部分与上面问题中的代码基本相同,我修改的唯一不起作用的部分是:

curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($curl, $data) {
        # str_repeat(' ',1024*8) is needed to fill the buffer and will make streaming the data possible
        $data = json_decode($data, true);

        $text = $data['choices'][0]['text'];

        echo $text . str_repeat(' ', 1024 * 8);
        return strlen($data);
    });

首先,我尝试只返回“choices”数组中的“text”属性(参见下面的API响应示例)。
这是我得到的回应:
注意:尝试访问C:\FILE_PATH\sse.php中null类型值的数组偏移量。
其次,如何真实的地将“文本”流传输到客户机上的元素?下面是我目前为止的实现。
JavaScript语言

$.ajax({
          type: "POST",
          url: "sse.php",
          data: JSON.stringify({
            prompt: "What is the best way to",
            num_completions: 1,
            temperature: 0.5,
          }),
          contentType: "application/json",
          success: function (response) {
            const source = new EventSource("sse.php");

            source.onmessage = function (event) {
              const div = document.getElementById("response");
              div.innerHTML += event.data + "<br>";
              console.log(event);
            };
          },
        });

由API流传输的示例数据块看起来是这样的。我试图只将“文本”部分流回浏览器。

data: {"id": "cmpl-XXXXXXXXXXXXXXXXXXXXXXX", "object": "text_completion", "created": 1671700494, "choices": [{"text": " Best", "index": 0, "logprobs": null, "finish_reason": null}], "model": "text-davinci-003"}

data: {"id": "cmpl-XXXXXXXXXXXXXXXXXXXXXXX", "object": "text_completion", "created": 1671700494, "choices": [{"text": " way", "index": 0, "logprobs": null, "finish_reason": null}], "model": "text-davinci-003"}

data: {"id": "cmpl-XXXXXXXXXXXXXXXXXXXXXXX", "object": "text_completion", "created": 1671700494, "choices": [{"text": " to", "index": 0, "logprobs": null, "finish_reason": null}], "model": "text-davinci-003"}

data: [DONE]

我该如何实现呢?我已经无计可施了。先谢谢你了。

6qftjkof

6qftjkof1#

我使用以下代码找到了解决方法:

//Placed at the beginning of the script
@ini_set('zlib.output_compression', 0);
ob_implicit_flush(true);
ob_end_flush();

header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");

//Initialize cURL and set the necessary headers and request parameters
...
...
curl_setopt($curl, CURLOPT_WRITEFUNCTION, function ($curl, $data) {
    echo $data;
    return strlen($data);
});

$curl_response = curl_exec($curl);

echo $curl_response;

然后,我使用JavaScript提取文本如下:

source.onmessage = function (event) {
  const div = document.getElementById("response");
  text = JSON.parse(event.data).choices[0].text;
  div.innerHTML += text;
};

相关问题