購買了 AI 插件基礎(chǔ)版本,想把流式輸出移植到自己的程序里面,現(xiàn)在發(fā)現(xiàn)客戶端請求程序以后在控制臺能正常輸出響應(yīng),但是客戶端 連接報錯,無法流式返回,想請問下問題可能出在哪里
public function chat(Request $request)
{
$input = $request->all();
if (empty($input['id'])) {
$this->error('error id is empty');
}
$connection = $request->connection;
$appInfo = ChatApp::find($input['id']);
$token = $appInfo['token'];
$varialbes = [];
if (!empty($request->input('variable', ''))) {
$varialbes = json_decode($request->input('variable', ''), 1);
}
$msg = $request->input('msg', '簡短回答你是誰');
$client = new AIArticleStream();
$client->gpt_chat($msg, $token, $varialbes);
$buffer = $client->build_tcp_data();
[$schema, $address] = explode('://', $client->url, 2);
$con = new AsyncTcpConnection("tcp://{$address}", ['ssl' => [
'verify_peer' => false,
]]);
$con->transport = 'ssl'; //in_array($schema, ['wss', 'https']) ? 'ssl' : 'tcp';
$callback = '';
$con->send($buffer);
$con->buffer = '';
// 失敗時
$con->onError = function ($con, $code, $msg) use ($connection) {
echo $code, $msg;
$con->buffer = $msg;
if ($connection) {
$connection->send(new Chunk(json_encode(['error' => ['message' => $msg]])));
$connection->send(new Chunk(''));
}
};
$con->onMessage = function ($con, $buffer) use ($connection) {
static $headerCompleted = false, $header = '', $bodyLength = 0, $sentLength = false;
if ( !$headerCompleted) {
$header .= $buffer;
if (!$position = strpos($header, "\r\n\r\n")) {
return;
}
if (preg_match("/Content-Length: (\d+)\r\n/i", $header, $match)) {
$bodyLength = $match[1];
}
if(!$buffer = substr($header, $position + 4)) {
return;
}
$headerCompleted = true;
if ($bodyLength) {
$con->buffer .= $buffer;
if ($connection) {
$sentLength += strlen($buffer);
$connection->send(new Chunk($buffer));
if ($sentLength >= $bodyLength) {
$connection->send(new Chunk(''));
}
}
return;
}
}
dump($buffer);
$con->buffer .= $buffer;
if ($connection) {
if ($bodyLength) {
$sentLength += strlen($buffer);
$connection->send(new Chunk($buffer));
if ($sentLength >= $bodyLength) {
$connection->send(new Chunk(''));
}
} else {
$connection->send($buffer, true);
}
}
};
// 關(guān)閉
$con->onClose = function ($con) use ($connection) {
dump('---conn close---');
if ($con->buffer) {
// call_user_func($callback, $handler->formatResponse($con->buffer));
}
};
$con->connect();
// 向瀏覽器發(fā)送頭部響應(yīng)
return response("\n")->withHeaders([
"Content-Type" => "application/octet-stream",
"Transfer-Encoding" => "chunked",
]);
}