在用PHP编写chatgpt聊天代码接口,需要边收边读,不出现明显的停顿卡时,需要以stream流方式获取chatgpt聊天内容,以下下代码通过php 的fopen扩展获取聊天内容在以stream流方式推送客户端。方便大家在编写和调试接口时做参考。

以下代码已经过验证运用ok.

// 读取远程请求中的 JSON 格式数据聊天数据
$input_data = file_get_contents('php://input');

$apikey='sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';    //api.openai.com密匙

$headers = [   //头部认证请求等
'Accept: application/json',
'Content-Type: application/json',
'Authorization: Bearer '.$apikey
];

$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => 'Content-Type: application/json' . "\r\n" . implode("\r\n", $headers),       //头部请求拼接为字符串
'content' => $input_data,       //聊天内容数据,需要按chatGP规范,JSON 数据格式
'ignore_errors' => true,
'protocol_version' => 1.1,
'timeout' => 30,
'follow_location' => false,
'max_redirects' => 0,
'request_fulluri' => true,
],
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
'allow_self_signed' => false,
],
]);

// 打开一个流,以stream流方式访问API
$stream = fopen('https://api.openai.com/v1/chat/completions', 'r', false, $context);

// 将API响应以流式传输的方式返回给访问者
header('Access-Control-Allow-Origin: *');
header('Content-type: text/event-stream');
header('Cache-Control: no-cache');
header('X-Accel-Buffering: no');
while (!feof($stream)) {
echo fgets($stream, 1024);    //输出内容
ob_flush();       // stream流推送
flush();
}
// 关闭流
fclose($stream);

发表回复

后才能评论