作者 lyh

gx

... ... @@ -62,15 +62,17 @@ class ChatLogic extends BaseLogic
}
$data = ['message' => $message];
return response()->stream(function () use ($gptService, $data, $chatId) {
$streamFunction = $gptService->get_ai_chat($data);
ob_start();
$streamFunction();
$fullResponse = ob_get_clean(); // 获取完整内容
$fullResponse = ''; // 存储完整 AI 回复
$stream = $gptService->get_ai_chat($data); // 获取流
while (!$stream->eof()) {
$chunk = $stream->read(1024); // 逐步读取数据块
echo $gptService->en_sse_data($chunk); // **封装 SSE 数据**
ob_flush();
flush();
$fullResponse .= $chunk; // 拼接完整 AI 回复
}
// **流结束后,保存完整的 AI 回复**
$this->saveChatItem($chatId, $fullResponse ?: '服务器繁忙,请重试', 1);
echo $fullResponse;
ob_flush();
flush();
}, 200, [
"Content-Type" => "text/event-stream",
"Cache-Control" => "no-cache",
... ...
... ... @@ -43,18 +43,26 @@ class GptService
}
return json_decode($result,true);
}else {
// **流式模式**
// **流式请求**
$payload->stream = true;
$response = $client->chat($payload);
$stream = $response->getBody();
return function () use ($stream) {
while (!$stream->eof()) {
$chunk = $stream->read(1024);
echo $chunk;
ob_flush();
flush();
}
};
return $stream;
}
}
/**
* @remark :返回格式
* @name :en_sse_data
* @author :lyh
* @method :post
* @time :2025/4/2 16:56
*/
public function en_sse_data($body, string $type='text'){
return 'data:'.json_encode([
'id' => md5(is_array($body) ? json_encode($body) : $body),
'data' => $body,
'type' => $type
],JSON_UNESCAPED_UNICODE)."\n\n";
}
}
... ...