如何使用伺服器傳送事件 (SSE) 將資料從上述 API 串流傳輸?shù)绞褂?JavaScript 和 PHP 的瀏覽器用戶端?我已經(jīng)研究這個問題好幾個小時了,但我似乎無法弄清楚出了什麼問題。作為參考,我嘗試在這裡調(diào)整解決方案: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」數(shù)組中的「text」屬性(請參閱下面的範(fàn)例 API 回應(yīng))。
這是我收到的回覆:
注意:嘗試存取 C:FILE_PATHsse.php 中 null 類型值的陣列偏移量。
其次,如何將「文字」即時傳輸?shù)娇蛻舳松系脑兀窟@是我到目前為止的實作。
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 串流傳輸?shù)馁Y料樣本區(qū)塊如下所示。我試圖僅將“文字”部分流回瀏覽器。
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]
我應(yīng)該如何實現(xiàn)這個?我已經(jīng)無計可施了。提前致謝。
我使用以下程式碼找到了解決方法:
//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; };