0
点赞
收藏
分享

微信扫一扫

使用 AJAX、PHP 和服务器发送事件从 OpenAI 的 API 流式传输数据

Yaphets_巍 2023-11-12 阅读 8

如何使用服务器发送事件 (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]


我应该如何实现这个?

要使用服务器发送事件(SSE)从灵动Ai的API流式传输数据到JavaScript和PHP的浏览器客户端,您可以按照以下步骤进行操作:

  1. 在PHP中创建一个用于处理SSE请求的端点,例如"sse.php"。
  2. 在"sse.php"文件中将以下代码添加到PHP代码的顶部,以设置响应的MIME类型和缓存控制:

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

  1. 在"sse.php"文件中,使用curl执行API请求,并在回调函数中处理返回的数据。修改您的代码如下:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.lingdong.com/v1/engines/davinci/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, JSON.stringify([
  "prompt" => "What is the best way to",
  "num_completions" => 1,
  "temperature" => 0.5,
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
  'Content-Type: application/json',
  'Authorization: Bearer YOUR_API_KEY'
]);

// Send the API request and handle the response
$response = curl_exec($ch);
if ($response === false) {
  // Handle the curl error
  echo 'error: ' . curl_error($ch) . "\n";
  exit;
}

curl_close($ch);

// Process the API response
$data = json_decode($response, true);
$text = $data['choices'][0]['text'];

echo 'data: ' . $text . "\n\n"; // Send the data to the client
flush(); // Flush the output buffer

请确保替换YOUR_API_KEY为您的灵动Ai API密钥。

  1. 在JavaScript中的success回调函数中添加以下代码,以使用EventSource监听SSE数据:

const source = new EventSource("sse.php");

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

  1. 在HTML中添加一个包含id为"response"的元素,用于显示从服务器接收到的数据:

<div id="response"></div>

通过以上步骤,您应该能够使用JavaScript和PHP的浏览器客户端从灵动Ai的API流式传输数据。当"SSE.php"端点收到数据时,它将将数据发送到客户端,并客户端将数据添加到具有"id"为"response"的元素中,实现实时数据传输。

请确保替换"YOUR_API_KEY"为您的灵动Ai API密钥,并根据需要调整其他部分以满足您的代码需求。

举报

相关推荐

0 条评论