123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- <?php
- namespace App\Repositories\StreamHandler;
- use Illuminate\Support\Facades\Log;
- class AIStreamHandler
- {
- private $basePath;
- private $path;
- private $data_buffer;//缓存,有可能一条data被切分成两部分了,无法解析json,所以需要把上一半缓存起来
- private $counter;//数据接收计数器
- private $qmd5;//问题md5
- private $chars;//字符数组,开启敏感词检测时用于缓存待检测字符
- private $punctuation;//停顿符号
- private $dfa = NULL;
- private $check_sensitive = FALSE;
- public function __construct($params) {
- $ds = DIRECTORY_SEPARATOR;
- $userId = isset($params["user"])?$params["user"]:0;
- $this->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);
- }
- }
|