| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- <?php
- namespace app\utils\Baidu;
- class BaiduAiTools {
- const ACCESS_TOKEN_API_URL = 'https://aip.baidubce.com/oauth/2.0/token';
- const CHAR_API_URL = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions';
- // 获取access_token
- public static function test() {
- $ret = self::chat([
- 'appid' => 'qng71IaZ',
- 'key' => 'xuccpM9rPM',
- ], '小米手机 好看 好用');
- var_dump($ret);
- die;
- }
- // 获取access_token
- public static function getAccessToken($appid, $key) {
- $access_token = '';
- try {
- if ($appid == '' || $key == '') {
- throw new \Exception('请先配置接口参数');
- }
- $cacheK = ['BaiduToken', $appid, $key];
- $cacheV = cache()->get($cacheK);
- if ($cacheV) {
- $access_token = $cacheV;
- } else {
- $res = http_post(static::ACCESS_TOKEN_API_URL, [
- 'headers' => [
- 'Content-Type' => 'application/json'
- ],
- 'query' => [
- 'grant_type' => 'client_credentials',
- 'client_id' => $appid,
- 'client_secret' => $key,
- ],
- ]);
- if ($res->getStatusCode() != 200) {
- throw new \Exception('getAccessToken Error: ' . $res->getStatusCode() . ' ' . $res->getReasonPhrase());
- }
- $data = json_decode((string) $res->getBody(), true);
- if (isset($data['error'])) {
- throw new \Exception('getAccessToken Error: ' . $data['error'] . ' ' . $data['error_description']);
- }
- cache()->set($cacheK, $data['access_token'], $data['expires_in'] - 60);
- $access_token = $data['access_token'];
- }
- return [
- 'code' => 0,
- 'data' => $access_token,
- ];
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
- /**
- * 发送消息
- */
- public static function chat($conf, $question, $system = '你是一个小红书博主') {
- try {
- $body = [
- 'messages' => [
- [
- 'role' => 'user',
- 'content' => $question,
- ],
- ],
- 'temperature' => 0.6,
- ];
- if (!empty($system)) {
- $body['system'] = $system;
- }
- $token = static::getAccessToken($conf['appid'], $conf['key']);
- if($token['code']){
- throw new \Exception($token['msg']);
- }
- $res = http_post(static::CHAR_API_URL, [
- 'body' => json_encode($body),
- 'query' => [
- 'access_token' => $token['data'],
- ],
- 'headers' => [
- 'Content-Type' => 'application/json',
- ],
- ]);
- if ($res->getStatusCode() != 200) {
- throw new \Exception('StatusCode Error: ' . $res->getStatusCode() . ' ' . $res->getReasonPhrase());
- }
- $data = json_decode((string) $res->getBody(), true);
- if (isset($data['error_code'])) {
- throw new \Exception('error_code Error: ' . $data['error_code'] . ' ' . $data['error_msg']);
- }
- return [
- 'code' => 0,
- 'data' => $data,
- ];
- } catch (\Exception $ex) {
- \Yii::error($ex);
- return [
- 'code' => 1,
- 'msg' => $ex->getMessage(),
- ];
- }
- }
- }
|