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; } }