作者 lyh

gx

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