array( array( "role" => "user", "content" => $content, ) ), "mode" => "instruct", "instruction_template" => "Alpaca", "stream" => true, ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // 保持直接输出模式 curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) { // 处理流式响应数据 $lines = explode("\n", $data); foreach ($lines as $line) { if (strpos($line, 'data:') === 0) { // 转发原始SSE格式数据 echo $line . "\n\n"; ob_flush(); flush(); } } return strlen($data); // 必须返回处理的数据长度 }); // 错误处理 curl_setopt($ch, CURLOPT_TIMEOUT, 86400); curl_setopt($ch, CURLOPT_FAILONERROR, true); // 执行请求 try { curl_exec($ch); // 检查HTTP状态码 $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($statusCode !== 200) { echo "event: error\ndata: HTTP Status {$statusCode}\n\n"; ob_flush(); flush(); } } catch (Exception $e) { echo "event: error\ndata: " . $e->getMessage() . "\n\n"; ob_flush(); flush(); } // 清理资源 curl_close($ch); // 显式结束流 echo "event: end\ndata: Stream ended\n\n"; ob_flush(); flush(); exit;