chat.php
5.0 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: text/event-stream");
header("X-Accel-Buffering: no");
session_start();
$postData = $_SESSION['data'];
$_SESSION['response'] = "";
$ch = curl_init();
$OPENAI_API_KEY = "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";
if (isset($_SESSION['key'])) {
$OPENAI_API_KEY = $_SESSION['key'];
}
$headers = [
'Accept: application/json',
'Content-Type: application/json',
'Authorization: Bearer ' . $OPENAI_API_KEY
];
setcookie("errcode", ""); //EventSource无法获取错误信息,通过cookie传递
setcookie("errmsg", "");
$callback = function ($ch, $data) {
$complete = json_decode($data);
if (isset($complete->error)) {
setcookie("errcode", $complete->error->code);
setcookie("errmsg", $data);
if (strpos($complete->error->message, "Rate limit reached") === 0) { //访问频率超限错误返回的code为空,特殊处理一下
setcookie("errcode", "rate_limit_reached");
}
if (strpos($complete->error->message, "Your access was terminated") === 0) { //违规使用,被封禁,特殊处理一下
setcookie("errcode", "access_terminated");
}
if (strpos($complete->error->message, "You didn't provide an API key") === 0) { //未提供API-KEY
setcookie("errcode", "no_api_key");
}
if (strpos($complete->error->message, "You exceeded your current quota") === 0) { //API-KEY余额不足
setcookie("errcode", "insufficient_quota");
}
if (strpos($complete->error->message, "That model is currently overloaded") === 0) { //OpenAI服务器超负荷
setcookie("errcode", "model_overloaded");
}
} else {
echo $data;
$_SESSION['response'] .= $data;
}
return strlen($data);
};
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);
//curl_setopt($ch, CURLOPT_PROXY, "http://127.0.0.1:1081");
curl_exec($ch);
$answer = "";
if (substr(trim($_SESSION['response']), -6) == "[DONE]") {
$_SESSION['response'] = substr(trim($_SESSION['response']), 0, -6) . "{";
}
$responsearr = explode("}\n\ndata: {", $_SESSION['response']);
foreach ($responsearr as $msg) {
$contentarr = json_decode("{" . trim($msg) . "}", true);
if (isset($contentarr['choices'][0]['delta']['content'])) {
$answer .= $contentarr['choices'][0]['delta']['content'];
}
}
$questionarr = json_decode($_SESSION['data'], true);
$filecontent = $_SERVER["REMOTE_ADDR"] . " | " . date("Y-m-d H:i:s") . "\n";
$filecontent .= "Q:" . end($questionarr['messages'])['content'] . "\nA:" . trim($answer) . "\n----------------\n";
$myfile = fopen(__DIR__ . "/chat.txt", "a") or die("Writing file failed.");
fwrite($myfile, $filecontent);
fclose($myfile);
curl_close($ch);
/*header('Content-type: text/event-stream');
header('Cache-Control: no-cache');
ob_end_flush();
while (true) {
echo "event: message \n";
echo "data: data\n\n";
flush();
if (connection_aborted()) {
break;
}
sleep(1);
}*/
//use App\Util\OpenAI\src\OpenAi;
//
//$open_api_key = config('openai.api_key') ;// '你的Open Ai key';
//
//$messages[] = ['role' => 'user', 'content' => request('body', '你好')];
//
//record_log($this->log_channel, 'messages:' . my_json_encode($messages));
//$sendData = [
// 'model' => $this->ai_model,
// 'messages' => $messages,
// 'temperature' => 1.0,
//// "max_tokens" => 150,
// "frequency_penalty" => 0,
// "presence_penalty" => 0,
// 'stream' => true
//];
//
//$open_ai = new OpenAi($open_api_key);
//
//header('Content-type: text/event-stream');
//header('Cache-Control: no-cache');
//ob_end_flush();
//$txt = "";
//$complete = $open_ai->chat($sendData, function ($curl_info, $data) use (&$txt) {
// $deltas = explode("\n", $data);
// $content = '';
// foreach ($deltas as $delta) {
// if (strpos($delta, 'data: ') !== 0) {
// continue;
// }
// $json = json_decode(substr($delta, 6));
// if (isset($json->choices[0]->delta)) {
// $content = $json->choices[0]->delta->content ?? "";
// $txt .= $content;
// } elseif (isset($json->error->message)) {
// $content = $json->error->message;
// } elseif(trim($delta) == "data: [DONE]") {
// $content = " ";
// } else {
// $content = "对不起,我不知道怎么去回答。";
// }
// echo "data: " .str_replace("\n", "\\n", $content )."\n\n";
// flush();
// }
//
// if (connection_aborted()) {
// return 0;
// }
//
//// echo PHP_EOL;
//// ob_flush();
// return strlen($data);
//});
//
//echo "event: stop\n";
//echo "data: stopped\n\n";