'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(), ]; } } }