如何使用服务器发送事件(SSE)从上述API流数据到使用JavaScript和PHP的浏览器客户端?我已经仔细研究了几个小时了,但我似乎不知道出了什么问题。作为参考,我试图在这里适应解决方案:使用PHP从openai GPT-3 API流数据
其余的代码与上面问题中的代码大致相同。我修改的唯一不工作的部分是:
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);
});
首先,我尝试只返回"text"属性在"选项"中。
下面是我得到的回应:
注意:试图访问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]
我应该如何实现这个?我已经无计可施了。提前谢谢。
我使用以下代码找到了解决方法:
//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;
};