|
...
|
...
|
@@ -63,11 +63,39 @@ class ChatLogic extends BaseLogic |
|
|
|
}
|
|
|
|
$data = ['message' => $message];
|
|
|
|
$stream = $gptService->get_ai_chat($data); // 获取流
|
|
|
|
$streamHelper = new Stream($stream);
|
|
|
|
$streamHelper->echo();
|
|
|
|
$res_message = $streamHelper->getData();
|
|
|
|
$this->saveChatItem($chatId, $res_message,1);
|
|
|
|
return $res_message;
|
|
|
|
header('Content-Type: text/event-stream');
|
|
|
|
header('Cache-Control: no-cache');
|
|
|
|
header('Connection: keep-alive');
|
|
|
|
$aiResponse = '';
|
|
|
|
$buffer = '';
|
|
|
|
while (!$stream->eof()) {
|
|
|
|
$chunk = $stream->read(1024);
|
|
|
|
$chunk = str_replace(chr(1), '', $chunk);
|
|
|
|
if ($chunk !== false) {
|
|
|
|
// 累积数据
|
|
|
|
$buffer .= $chunk;
|
|
|
|
// 持续解析完整的 JSON
|
|
|
|
while (preg_match('/^\{[^{}]*\}/', $buffer, $match)) {
|
|
|
|
$jsonStr = $match[0];
|
|
|
|
$jsonData = json_decode($jsonStr, true);
|
|
|
|
// 确保 JSON 解析成功
|
|
|
|
if (json_last_error() === JSON_ERROR_NONE) {
|
|
|
|
if (isset($jsonData['text'])) {
|
|
|
|
$aiResponse .= $jsonData['text'];
|
|
|
|
echo $gptService->en_sse_data(trim($jsonData['text']));
|
|
|
|
ob_flush();
|
|
|
|
flush();
|
|
|
|
}
|
|
|
|
// 移除已解析的 JSON,保留未完成的部分
|
|
|
|
$buffer = substr($buffer, strlen($jsonStr));
|
|
|
|
} else {
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
$this->saveChatItem($chatId, $aiResponse, 1);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
...
|
...
|
|