BaiduChat.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace app\utils;
  3. use app\models\QAndASetting;
  4. class BaiduChat
  5. {
  6. const ACCESS_TOKEN_API_URL = 'https://aip.baidubce.com/oauth/2.0/token';
  7. const CHAR_API_URL = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions';
  8. // 获取access_token
  9. public static function getAccessToken()
  10. {
  11. $exists = cache()->exists('baidu_chat_access_token');
  12. if ($exists) {
  13. return cache()->get('baidu_chat_access_token');
  14. }
  15. $setting = QAndASetting::find()->where(['store_id' => get_store_id()])->one();
  16. if (!$setting) {
  17. throw new \Exception('请先配置百度千帆');
  18. }
  19. if ($setting->appid == '' || $setting->key == '') {
  20. throw new \Exception('请先配置百度千帆');
  21. }
  22. $res = http_post(static::ACCESS_TOKEN_API_URL, [
  23. 'headers' => [
  24. 'Content-Type' => 'application/json'
  25. ],
  26. 'query' => [
  27. 'grant_type' => 'client_credentials',
  28. 'client_id' => $setting->appid,
  29. 'client_secret' => $setting->key,
  30. ],
  31. ]);
  32. if ($res->getStatusCode() != 200) {
  33. throw new \Exception('Error: ' . $res->getStatusCode() . ' ' . $res->getReasonPhrase());
  34. }
  35. $data = json_decode((string)$res->getBody(), true);
  36. if (isset($data['error'])) {
  37. throw new \Exception('Error: ' . $data['error'] . ' ' . $data['error_description']);
  38. }
  39. cache()->set('baidu_chat_access_token', $data['access_token'], $data['expires_in'] - 60);
  40. return $data['access_token'];
  41. }
  42. /**
  43. * 发送消息
  44. * @param string $question 对话内容
  45. * @param string $system 模型设定,例如: 你是一个画家
  46. * @return void
  47. * @throws \GuzzleHttp\Exception\GuzzleException
  48. * @throws \Exception
  49. * @author Syan mzsongyan@gmail.com
  50. * @date 2023-10-18
  51. */
  52. public static function send(string $question, string $system = '')
  53. {
  54. $body = [
  55. 'messages' => [
  56. [
  57. 'role' => 'user',
  58. 'content' => $question,
  59. ],
  60. ],
  61. 'temperature' => 0.6,
  62. ];
  63. if (!empty($system)) {
  64. $body['system'] = $system;
  65. }
  66. $res = http_post(static::CHAR_API_URL, [
  67. 'body' => json_encode($body),
  68. 'query' => [
  69. 'access_token' => static::getAccessToken(),
  70. ],
  71. 'headers' => [
  72. 'Content-Type' => 'application/json',
  73. ],
  74. ]);
  75. if ($res->getStatusCode() != 200) {
  76. throw new \Exception('Error: ' . $res->getStatusCode() . ' ' . $res->getReasonPhrase());
  77. }
  78. $data = json_decode((string)$res->getBody(), true);
  79. if (isset($data['error_code'])) {
  80. throw new \Exception('Error: ' . $data['error_code'] . ' ' . $data['error_msg']);
  81. }
  82. return $data;
  83. }
  84. }