作者 lyh

gx

@@ -137,12 +137,8 @@ class SuppliersController extends BaseController @@ -137,12 +137,8 @@ class SuppliersController extends BaseController
137 if(isset($this->param['position'])){ 137 if(isset($this->param['position'])){
138 $param['position'] = $this->param['position']; 138 $param['position'] = $this->param['position'];
139 } 139 }
140 -// try {  
141 - $res = $this->_action($api_url,$action_name,$param);  
142 - $this->response('success',Code::SUCCESS,$res);  
143 -// }catch (\Exception $e){  
144 -// $this->fail('请求失败,请联系管理员');  
145 -// } 140 + $res = $this->_action($api_url,$action_name,$param);
  141 + $this->response('success',Code::SUCCESS,$res);
146 } 142 }
147 143
148 /** 144 /**
@@ -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 /**