ChatGPT.php 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace app\utils;
  3. use app\models\QAndASetting;
  4. class ChatGPT
  5. {
  6. const API_URL = 'https://api.openai.com/v1/chat/completions';
  7. const PROXY_API_URL = 'https://www.pinwen.org/gpt.php';
  8. /**
  9. * @param mixed $question
  10. * @return mixed
  11. * @throws \GuzzleHttp\Exception\GuzzleException
  12. * @throws \Exception
  13. * @author Syan mzsongyan@gmail.com
  14. * @date 2023-04-04
  15. * 调用示例:\app\utils\ChatGPT::send('写一首春天的诗');
  16. * 返回数据格式:
  17. * [
  18. * "id" => "chatcmpl-71WbBTONuJCkljl7E7judAfTsMw5P",
  19. * "object" => "chat.completion",
  20. * "created" => 1680597993,
  21. * "model" =>"gpt-3.5-turbo-0301",
  22. * "usage" => [
  23. * "prompt_tokens":19,
  24. * "completion_tokens":138,
  25. * "total_tokens":157
  26. * ],
  27. * "choices" => [
  28. * [
  29. * "message" => [
  30. * "role" => "assistant",
  31. * "content" => "春风轻抚,万物复苏,\n春雨滋润,花开如锦。\n青翠欲滴,春水涟漪,\n蝴蝶飞舞,鸟儿欢鸣。\n\n春日暖阳,人心欢畅,\n田野耕作,家园丰收。\n春天啊春天,你是万物的希望,\n让我们心怀感恩,珍惜每一天。"
  32. * ],
  33. * "finish_reason" => "stop",
  34. * "index" => 0
  35. * ]
  36. * ]
  37. * ]
  38. */
  39. public static function send($question)
  40. {
  41. $body = json_encode([
  42. 'model' => 'gpt-3.5-turbo',
  43. 'messages' => [
  44. [
  45. 'role' => 'user',
  46. 'content' => $question,
  47. ],
  48. ],
  49. 'temperature' => 0.6,
  50. ]);
  51. $res = http_post(static::API_URL, [
  52. 'body' => $body,
  53. 'headers' => [
  54. 'Content-Type' => 'application/json',
  55. 'Authorization' => 'Bearer ' . static::getKey()
  56. ],
  57. ]);
  58. if ($res->getStatusCode() != 200) {
  59. throw new \Exception('Error: ' . $res->getStatusCode() . ' ' . $res->getReasonPhrase());
  60. }
  61. return json_decode((string)$res->getBody(), true);
  62. }
  63. // 代理接口,用于解决国内访问ChatGPT API的问题
  64. public static function proxySend($question)
  65. {
  66. $res = http_post(static::PROXY_API_URL, [
  67. 'form_params' => [
  68. 'question' => $question,
  69. 'key' => static::getKey(),
  70. ],
  71. ]);
  72. if ($res->getStatusCode() != 200) {
  73. throw new \Exception('Error: ' . $res->getStatusCode() . ' ' . $res->getReasonPhrase());
  74. }
  75. return json_decode((string)$res->getBody(), true);
  76. }
  77. /**
  78. * 这里实现获取API KEY的逻辑
  79. * @return string
  80. */
  81. public static function getKey()
  82. {
  83. $setting = QAndASetting::find()->where(['store_id' => get_store_id()])->one();
  84. return $setting->key;
  85. }
  86. }