|
@@ -61,18 +61,24 @@ class ChatLogic extends BaseLogic |
|
@@ -61,18 +61,24 @@ class ChatLogic extends BaseLogic |
|
61
|
];
|
61
|
];
|
|
62
|
}
|
62
|
}
|
|
63
|
$data = ['message' => $message];
|
63
|
$data = ['message' => $message];
|
|
|
|
64
|
+
|
|
64
|
return response()->stream(function () use ($gptService, $data, $chatId) {
|
65
|
return response()->stream(function () use ($gptService, $data, $chatId) {
|
|
65
|
- $fullResponse = ''; // 存储完整 AI 回复
|
|
|
|
66
|
- $response = $gptService->get_ai_chat($data); // 获取流
|
|
|
|
67
|
- while (!$response->eof()) {
|
|
|
|
68
|
- $chunk = $response->read(1024); // 逐步读取数据块
|
|
|
|
69
|
- echo $gptService->en_sse_data($chunk); // **封装 SSE 数据**
|
|
|
|
70
|
- ob_flush();
|
|
|
|
71
|
- flush();
|
|
|
|
72
|
- $fullResponse .= $chunk; // 拼接完整 AI 回复
|
66
|
+ $fullResponse = ''; // **存储完整 AI 回复**
|
|
|
|
67
|
+ $stream = $gptService->get_ai_chat($data); // 获取流
|
|
|
|
68
|
+ if ($stream) {
|
|
|
|
69
|
+ while (!$stream->eof()) {
|
|
|
|
70
|
+ $chunk = $stream->read(1024); // **逐步读取数据块**
|
|
|
|
71
|
+ echo "data: " . json_encode(['message' => $chunk], JSON_UNESCAPED_UNICODE) . "\n\n";
|
|
|
|
72
|
+ ob_flush();
|
|
|
|
73
|
+ flush();
|
|
|
|
74
|
+ $fullResponse .= $chunk; // **拼接完整 AI 回复**
|
|
|
|
75
|
+ }
|
|
|
|
76
|
+ } else {
|
|
|
|
77
|
+ $fullResponse = '服务器繁忙,请重试';
|
|
|
|
78
|
+ echo "data: " . json_encode(['message' => $fullResponse], JSON_UNESCAPED_UNICODE) . "\n\n";
|
|
73
|
}
|
79
|
}
|
|
74
|
- // **流结束后,保存完整的 AI 回复**
|
|
|
|
75
|
- $this->saveChatItem($chatId, $fullResponse ?: '服务器繁忙,请重试', 1);
|
80
|
+ // **流结束后,保存完整 AI 回复**
|
|
|
|
81
|
+ $this->saveChatItem($chatId, $fullResponse, 1);
|
|
76
|
}, 200, [
|
82
|
}, 200, [
|
|
77
|
"Content-Type" => "text/event-stream",
|
83
|
"Content-Type" => "text/event-stream",
|
|
78
|
"Cache-Control" => "no-cache",
|
84
|
"Cache-Control" => "no-cache",
|