使用 AJAX、PHP 和伺服器發送事件從 OpenAI 的 API 串流數據
P粉762447363
P粉762447363 2023-11-11 12:03:23

如何使用伺服器傳送事件 (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_PATHsse.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]

我應該如何實現這個?我已經無計可施了。提前致謝。

P粉762447363
P粉762447363

全部回覆(1)
P粉821808309

我使用以下程式碼找到了解決方法:

//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;
};
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!