| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- <?php
- namespace app\utils;
- use app\models\QAndASetting;
- class BaiduChat
- {
- 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 getAccessToken()
- {
- $exists = cache()->exists('baidu_chat_access_token');
- if ($exists) {
- return cache()->get('baidu_chat_access_token');
- }
- $setting = QAndASetting::find()->where(['store_id' => get_store_id()])->one();
- if (!$setting) {
- throw new \Exception('请先配置百度千帆');
- }
- if ($setting->appid == '' || $setting->key == '') {
- throw new \Exception('请先配置百度千帆');
- }
- $res = http_post(static::ACCESS_TOKEN_API_URL, [
- 'headers' => [
- 'Content-Type' => 'application/json'
- ],
- 'query' => [
- 'grant_type' => 'client_credentials',
- 'client_id' => $setting->appid,
- 'client_secret' => $setting->key,
- ],
- ]);
- if ($res->getStatusCode() != 200) {
- throw new \Exception('Error: ' . $res->getStatusCode() . ' ' . $res->getReasonPhrase());
- }
- $data = json_decode((string)$res->getBody(), true);
- if (isset($data['error'])) {
- throw new \Exception('Error: ' . $data['error'] . ' ' . $data['error_description']);
- }
- cache()->set('baidu_chat_access_token', $data['access_token'], $data['expires_in'] - 60);
- return $data['access_token'];
- }
- /**
- * 发送消息
- * @param string $question 对话内容
- * @param string $system 模型设定,例如: 你是一个画家
- * @return void
- * @throws \GuzzleHttp\Exception\GuzzleException
- * @throws \Exception
- * @author Syan mzsongyan@gmail.com
- * @date 2023-10-18
- */
- public static function send(string $question, string $system = '')
- {
- $body = [
- 'messages' => [
- [
- 'role' => 'user',
- 'content' => $question,
- ],
- ],
- 'temperature' => 0.6,
- ];
- if (!empty($system)) {
- $body['system'] = $system;
- }
- $res = http_post(static::CHAR_API_URL, [
- 'body' => json_encode($body),
- 'query' => [
- 'access_token' => static::getAccessToken(),
- ],
- 'headers' => [
- 'Content-Type' => 'application/json',
- ],
- ]);
- if ($res->getStatusCode() != 200) {
- throw new \Exception('Error: ' . $res->getStatusCode() . ' ' . $res->getReasonPhrase());
- }
- $data = json_decode((string)$res->getBody(), true);
- if (isset($data['error_code'])) {
- throw new \Exception('Error: ' . $data['error_code'] . ' ' . $data['error_msg']);
- }
- return $data;
- }
- }
|