123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- <?php
- namespace app\controller\api;
- use app\service\api\ImageCensorServiceFacade;
- use app\service\api\InsServiceFacade;
- use app\service\api\UserServiceFacade;
- use app\service\ConfServiceFacade;
- use app\service\MemberServiceFacade;
- use laytp\controller\Api;
- class ErnieBotTurbo extends Api
- {
- public $noNeedLogin = [
- "test",
- ];
- const API_KEY = "biAmXmmAbUX4O4dP1YRL3LuX";
- const SECRET_KEY = "dhTZSa083FfhIsSPahGsroVF5yEPpkHw";
- public function test(){
- $this->run(['messages' => [["role" => "user","content"=>"写一篇2000字的文章,关于我的母亲"]],"stream" => true]); //,
- }
- /**
- * 运行
- * @param array $message
- * @return bool|string
- */
- public function run(array $message) {
- $i = 0;
- // ob_start();
- $callback = function ($ch, $data) use(&$stdout,&$i){
- $i++;
- $jsonString = substr($data, 6, -1);
- $complete = @json_decode($jsonString, true);
- if ($complete['is_end']){
- header('Connection: close');
- // 刷新输出缓冲区并关闭输出缓冲
- ob_end_flush();
- // 结束当前脚本
- exit;
- }
- echo $complete['result'];
- ob_flush();
- flush();
- return strlen($data);
- };
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- curl_setopt($ch, CURLOPT_URL, "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token={$this->getAccessToken()}");
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, array(
- 'Content-Type: application/json'
- ));
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($message,256));
- curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);
- register_shutdown_function(function() use ($ch, $stdout) {
- curl_close($ch);
- fclose($stdout);
- });
- curl_exec($ch);
- }
- /**
- * 使用 AK,SK 生成鉴权签名(Access Token)
- * @return string 鉴权签名信息(Access Token)
- */
- private function getAccessToken(){
- $curl = curl_init();
- $postData = array(
- 'grant_type' => 'client_credentials',
- 'client_id' => self::API_KEY,
- 'client_secret' => self::SECRET_KEY
- );
- curl_setopt_array($curl, array(
- CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
- CURLOPT_CUSTOMREQUEST => 'POST',
- CURLOPT_RETURNTRANSFER => true,
- CURLOPT_POSTFIELDS => http_build_query($postData)
- ));
- $response = curl_exec($curl);
- curl_close($curl);
- $rtn = json_decode($response);
- return $rtn->access_token;
- }
- }
|