|
@@ -63,11 +63,39 @@ class ChatLogic extends BaseLogic |
|
@@ -63,11 +63,39 @@ class ChatLogic extends BaseLogic |
|
63
|
}
|
63
|
}
|
|
64
|
$data = ['message' => $message];
|
64
|
$data = ['message' => $message];
|
|
65
|
$stream = $gptService->get_ai_chat($data); // 获取流
|
65
|
$stream = $gptService->get_ai_chat($data); // 获取流
|
|
66
|
- $streamHelper = new Stream($stream);
|
|
|
|
67
|
- $streamHelper->echo();
|
|
|
|
68
|
- $res_message = $streamHelper->getData();
|
|
|
|
69
|
- $this->saveChatItem($chatId, $res_message,1);
|
|
|
|
70
|
- return $res_message;
|
66
|
+ header('Content-Type: text/event-stream');
|
|
|
|
67
|
+ header('Cache-Control: no-cache');
|
|
|
|
68
|
+ header('Connection: keep-alive');
|
|
|
|
69
|
+ $aiResponse = '';
|
|
|
|
70
|
+ $buffer = '';
|
|
|
|
71
|
+ while (!$stream->eof()) {
|
|
|
|
72
|
+ $chunk = $stream->read(1024);
|
|
|
|
73
|
+ $chunk = str_replace(chr(1), '', $chunk);
|
|
|
|
74
|
+ if ($chunk !== false) {
|
|
|
|
75
|
+ // 累积数据
|
|
|
|
76
|
+ $buffer .= $chunk;
|
|
|
|
77
|
+ // 持续解析完整的 JSON
|
|
|
|
78
|
+ while (preg_match('/^\{[^{}]*\}/', $buffer, $match)) {
|
|
|
|
79
|
+ $jsonStr = $match[0];
|
|
|
|
80
|
+ $jsonData = json_decode($jsonStr, true);
|
|
|
|
81
|
+ // 确保 JSON 解析成功
|
|
|
|
82
|
+ if (json_last_error() === JSON_ERROR_NONE) {
|
|
|
|
83
|
+ if (isset($jsonData['text'])) {
|
|
|
|
84
|
+ $aiResponse .= $jsonData['text'];
|
|
|
|
85
|
+ echo $gptService->en_sse_data(trim($jsonData['text']));
|
|
|
|
86
|
+ ob_flush();
|
|
|
|
87
|
+ flush();
|
|
|
|
88
|
+ }
|
|
|
|
89
|
+ // 移除已解析的 JSON,保留未完成的部分
|
|
|
|
90
|
+ $buffer = substr($buffer, strlen($jsonStr));
|
|
|
|
91
|
+ } else {
|
|
|
|
92
|
+ break;
|
|
|
|
93
|
+ }
|
|
|
|
94
|
+ }
|
|
|
|
95
|
+ }
|
|
|
|
96
|
+ }
|
|
|
|
97
|
+ $this->saveChatItem($chatId, $aiResponse, 1);
|
|
|
|
98
|
+ return true;
|
|
71
|
}
|
99
|
}
|
|
72
|
|
100
|
|
|
73
|
/**
|
101
|
/**
|