| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- <?php
- namespace app\utils;
- use app\models\QAndASetting;
- class ChatGPT
- {
- const API_URL = 'https://api.openai.com/v1/chat/completions';
- const PROXY_API_URL = 'https://www.pinwen.org/gpt.php';
- /**
- * @param mixed $question
- * @return mixed
- * @throws \GuzzleHttp\Exception\GuzzleException
- * @throws \Exception
- * @author Syan mzsongyan@gmail.com
- * @date 2023-04-04
- * 调用示例:\app\utils\ChatGPT::send('写一首春天的诗');
- * 返回数据格式:
- * [
- * "id" => "chatcmpl-71WbBTONuJCkljl7E7judAfTsMw5P",
- * "object" => "chat.completion",
- * "created" => 1680597993,
- * "model" =>"gpt-3.5-turbo-0301",
- * "usage" => [
- * "prompt_tokens":19,
- * "completion_tokens":138,
- * "total_tokens":157
- * ],
- * "choices" => [
- * [
- * "message" => [
- * "role" => "assistant",
- * "content" => "春风轻抚,万物复苏,\n春雨滋润,花开如锦。\n青翠欲滴,春水涟漪,\n蝴蝶飞舞,鸟儿欢鸣。\n\n春日暖阳,人心欢畅,\n田野耕作,家园丰收。\n春天啊春天,你是万物的希望,\n让我们心怀感恩,珍惜每一天。"
- * ],
- * "finish_reason" => "stop",
- * "index" => 0
- * ]
- * ]
- * ]
- */
- public static function send($question)
- {
- $body = json_encode([
- 'model' => 'gpt-3.5-turbo',
- 'messages' => [
- [
- 'role' => 'user',
- 'content' => $question,
- ],
- ],
- 'temperature' => 0.6,
- ]);
- $res = http_post(static::API_URL, [
- 'body' => $body,
- 'headers' => [
- 'Content-Type' => 'application/json',
- 'Authorization' => 'Bearer ' . static::getKey()
- ],
- ]);
- if ($res->getStatusCode() != 200) {
- throw new \Exception('Error: ' . $res->getStatusCode() . ' ' . $res->getReasonPhrase());
- }
- return json_decode((string)$res->getBody(), true);
- }
- // 代理接口,用于解决国内访问ChatGPT API的问题
- public static function proxySend($question)
- {
- $res = http_post(static::PROXY_API_URL, [
- 'form_params' => [
- 'question' => $question,
- 'key' => static::getKey(),
- ],
- ]);
- if ($res->getStatusCode() != 200) {
- throw new \Exception('Error: ' . $res->getStatusCode() . ' ' . $res->getReasonPhrase());
- }
- return json_decode((string)$res->getBody(), true);
- }
- /**
- * 这里实现获取API KEY的逻辑
- * @return string
- */
- public static function getKey()
- {
- $setting = QAndASetting::find()->where(['store_id' => get_store_id()])->one();
- return $setting->key;
- }
- }
|