basePath = storage_path("logs{$ds}curl{$ds}data{$ds}{$userId}{$ds}"); if (!file_exists($this->basePath)){ mkdir($this->basePath,0777,true); } $this->buffer = ''; $this->counter = 0; $this->qmd5 = $params['qmd5'] ?? time(); $this->chars = []; $this->lines = []; $this->punctuation = [',', '。', ';', '?', '!', '……']; $this->path = $this->basePath.'data.'.$this->qmd5.'.log'; } public function getPath(): string { return $this->path; } /** * 得到结果数据 * @param string|null $filePath * @return array * @throws \Exception */ public function getData(string $filePath=null) { $filePath = $filePath==null?$this->path:$filePath; $content = file_get_contents($filePath);// 读取文件内容 // 定义正则表达式模式 // 匹配 JSON 对象(花括号包围的内容) $pattern = '/\{(?:[^{}]|(?R))*\}|(\[(?:[^[\]]|(?R))*\])/s'; // 使用 preg_match_all 匹配所有 JSON 数据 preg_match_all($pattern, $content, $matches); $result = []; // 检查是否找到匹配项 if (!empty($matches[0])) { foreach ($matches[0] as $match) { // 解析 JSON 数据 $jsonData = json_decode($match, true); // 检查解析是否成功 if (json_last_error() === JSON_ERROR_NONE) { $result[] = $jsonData; } } } $answer = ""; $conversation_id = ""; foreach ($result as $val){ if (isset($val["event"])){ switch ($val["event"]){ //获取回答数据 case "agent_message": $answer.=$val["answer"]; break; case "message_end": $conversation_id = $val["conversation_id"]; break; } } } if (empty($answer) || empty($conversation_id)){ throw new \Exception("获取结果失败"); } return array( "answer"=>$answer, "conversation_id"=>$conversation_id, "path"=>$filePath ); } public function callback($ch, $data) { $this->counter += 1; file_put_contents($this->path,$this->counter.'=='.$data.PHP_EOL, FILE_APPEND); $result = json_decode($data, TRUE); if(is_array($result)){ throw new \Exception('openai 请求错误:'.json_encode($result)); } return strlen($data); } }