php的curl如何以steam流的方式请求chatgpt接口

$ch = curl_init();

$url = 'https://api.openai.com/v1/completions';
$data = array(
'prompt' => 'Hello',
'max_tokens' => 5,
'n' => 1,
'stop' => ''
);
$json_data = json_encode($data);

$output_file = fopen('output.txt', 'w');

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $output) use ($output_file) { # $output就是每次返回的内容,把内容追加到文件中 fwrite($output_file, $output);
return strlen($output);
});

curl_exec($ch);
curl_close($ch);
fclose($output_file);

参考地址:这里