Gpt.php
2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
namespace App\Helper;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
/**
* Class Gpt
* @package App\Helper
* @author zbj
* @date 2023/11/3
*/
class Gpt
{
/**
* 头
* @var string[]
*/
public $header = [
'apikey' => 'UkzZljFv83Z2qBi5YR1o3f2otAVWtug6',
'X-CmerApi-Host' => 'bizopenai.p.cmer.com',
];
/**
* 请求域名
* @var string
*/
public $api = 'https://api.cmer.com';
private static $instance;
public static function instance(){
if(!self::$instance){
self::$instance = new static;
}
return self::$instance;
}
/**
* 全球搜-文本生成接口。模型:gpt-3.5-turbo
* @author zbj
* @date 2023/8/25
*
*/
public function openai_chat_qqs($content, $system_content = '')
{
$url = $this->api . '/v1/openai_chat';
$data = [
'messages' => [],
'model' => 'gpt-4o-mini'
];
if ($system_content) {
$data['messages'][] = [
"role" => "system",
"content" => $system_content
];
}
$data['messages'][] = [
"role" => "user",
"content" => $content
];
$time = time();
try {
$result = Http::withHeaders($this->header)->withOptions(['verify' => false])->acceptJson()
->withBody(json_encode($data, JSON_UNESCAPED_UNICODE), 'application/json')
->post($url);
$json = $result->json();
// $client = new \GuzzleHttp\Client();
// $result = $client->request('POST', $url, [
// 'proxy' => 'http://104.255.171.237:51395', // 代理服务器地址和端口号
// 'headers' => $this->header,
// 'json' => $data,
// 'verify' => false,
// ])->getBody()->getContents();
// $json = json_decode($result, true);
if (!isset($json['text']) || $json['code'] !==200) {
Log::error('openai_chat_qqs data:', $data);
Log::error('openai_chat_qqs result:' . (time() - $time), $json === null ? ['null'] : $json);
$json = [];
}
} catch (\Throwable $e) {
Log::error('openai_chat_qqs data:', $data);
Log::error('openai_chat_qqs time ' . (time() - $time) . ' error:' . $e->getMessage());
$json = [];
}
return $json['text'] ?? '';
}
}