直接写代码了
config 里面是配置文件就不写了,这样要去不同的平台申请去
写一个 service,解释一下代码 写了两个ai,一个是星火,一个是质谱,他们都是调用curl 方法,并返回数据, s t r e a m 为假就是等等返回结果统一返回, stream 为假就是等等返回结果统一返回, stream为假就是等等返回结果统一返回,stream 为真就根据后面的回调方式返回,
<?php
namespace app\service;
use app\model\AdminModel;
use think\facade\Db;
class AiService
{private static function curl($url,$data,$auth_token,$stream,$feedback=''){$ch = curl_init();$headers = ['Content-Type: application/json','Authorization: Bearer '.$auth_token];curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);$params[CURLOPT_URL] = $url; //请求url地址$params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息$params[CURLOPT_SSL_VERIFYPEER] = false;$params[CURLOPT_SSL_VERIFYHOST] = false;if($stream){curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // 不返回结果,直接输出if (!empty($data)) {$data['stream']=true;$params[CURLOPT_POST] = true;$params[CURLOPT_POSTFIELDS] = \json_encode($data);}curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($curl, $data) use (&$receivedData,$feedback) {$feedback($data);return strlen($data);});}else{$params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回if (!empty($data)) {$params[CURLOPT_POST] = true;$params[CURLOPT_POSTFIELDS] = \json_encode($data);}}curl_setopt_array($ch, $params); //传入curl参数$content = curl_exec($ch); //执行curl_close($ch); //关闭连接if(json_decode($content, true)){return json_decode($content, true);}return $content;}public static function zhipuAIv4($message=[],$stream=false,$feedback=''){$zhipu_config=config('ai.zhipu');$data=$zhipu_config['data'];$data['messages']=$message;return self::curl($zhipu_config['url'],$data,$zhipu_config['auth_token'],$stream,$feedback);}public static function xinghuoLite($message=[],$stream=false,$feedback=''){$xinghuo_config=config('ai.xinghuo');$data=$xinghuo_config['data'];$data['messages']=$message;return self::curl($xinghuo_config['url'],$data,$xinghuo_config['auth_token'],$stream,$feedback);}
}
在写一个 controller ,解释代码,如果不传后面参数就统一返回,传了第二个参数为true,就根据回调返回,剩下的是前端了,我回头再写
use app\service\AiService;
use app\service\UpdateFileService;
use think\facade\Db;
use support\Request;
use support\View;
use Workerman\Protocols\Http\Chunk;public function index(Request $request){$connection =$request->connection;$data= AiService::zhipuAIv4([["role"=> "user","content"=> "帮我写一个关于汽车的文章"]]);s($data);AiService::zhipuAIv4([["role"=> "user","content"=> "帮我写一个关于汽车的文章"]],true,function ($data) use ($connection){//这一段是为了截取返回的数据。$pattern = '/"content":"(.*?)"/';if (preg_match_all($pattern,$data, $matches)) {// $matches[1] 将包含所有匹配的 "content" 键的值$contents =$matches[1];if(is_array($contents)){$contents=$contents[0];}} else {$contents ='';}dump($contents);// dump($data,6666,$contents);//根据有没有done 判断是否结束了if (strpos($data, '[DONE]') !== false) {$connection->send(new Chunk(''));} else {$connection->send(new Chunk(json_encode($contents, JSON_UNESCAPED_UNICODE) . "\n"));}});}