ChatLogic.php
5.3 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
<?php
/**
* @remark :
* @name :ChatLogic.php
* @author :lyh
* @method :post
* @time :2025/4/1 14:37
*/
namespace App\Http\Logic\Bside\Gpt;
use App\Http\Logic\Bside\BaseLogic;
use App\Models\Gpt\Chat;
use App\Models\Gpt\ChatItem;
use App\Services\GptService;
class ChatLogic extends BaseLogic
{
public function __construct()
{
parent::__construct();
$this->param = $this->requestAll;
$this->model = new Chat();
$this->itemModel = new ChatItem();
}
/**
* @remark :发送消息
* @name :sendMessage
* @author :lyh
* @method :post
* @time :2025/4/2 10:01
*/
public function sendMessage()
{
$gptService = new GptService();
$message = [];
if (isset($this->param['chat_id'])) {
$chatInfo = $this->model->read(['id' => $this->param['chat_id']]);
if ($chatInfo !== false) {
$this->saveChatItem($chatInfo['id'], $this->param['message']);
// 获取最近 2 条对话记录
$list = $this->itemModel->list(['chat_id' => $chatInfo['id']], 'id', ['*'], 'desc', 2);
$message[] = ['role' => 'system', 'content' => "You are now the marketing customer service of 深圳创贸集团"];
foreach ($list as $val) {
if ($val['is_reply'] == 2) {
$message[] = ['role' => 'user', 'content' => $val['content']];
} else {
$message[] = ['role' => 'assistant', 'content' => $val['content']];
}
}
$message[] = ['role' => 'user', 'content' => $this->param['message']];
$chatId = $chatInfo['id'];
}else{
$chatId = $this->saveChat($this->param['message']);
$this->saveChatItem($chatId, $this->param['message']);
$message = [
['role' => 'system', 'content' => "You are now the marketing customer service of 深圳创贸集团"],
['role' => 'user', 'content' => $this->param['message']],
];
}
} else {
$chatId = $this->saveChat($this->param['message']);
$this->saveChatItem($chatId, $this->param['message']);
$message = [
['role' => 'system', 'content' => "You are now the marketing customer service of 深圳创贸集团"],
['role' => 'user', 'content' => $this->param['message']],
];
}
$data = ['message' => $message];
$stream = $gptService->get_ai_chat($data); // 获取流
// 允许跨域访问
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
$aiResponse = '';
$buffer = '';
while (!$stream->eof()) {
$chunk = $stream->read(1024);
$chunk = str_replace(chr(1), '', $chunk);
if ($chunk !== false) {
// 累积数据
$buffer .= $chunk;
// 持续解析完整的 JSON
while (preg_match('/^\{[^{}]*\}/', $buffer, $match)) {
$jsonStr = $match[0];
$jsonData = json_decode($jsonStr, true);
// 确保 JSON 解析成功
if (json_last_error() === JSON_ERROR_NONE) {
if (isset($jsonData['text'])) {
$aiResponse .= $jsonData['text'];
echo $gptService->en_sse_data($jsonData['text']);
ob_flush();
flush();
}
// 移除已解析的 JSON,保留未完成的部分
$buffer = substr($buffer, strlen($jsonStr));
} else {
break;
}
}
}
}
$this->saveChatItem($chatId, $aiResponse, 1);
return true;
}
/**
* @remark :创建一条新会话
* @name :saveChat
* @author :lyh
* @method :post
* @time :2025/4/2 10:06
*/
public function saveChat($message){
//创建一个会话
$saveData = [
'user_id'=>$this->user['id'],
'input_content'=>mb_substr($message, 0, 50, "UTF-8").'...',
];
return $this->model->addReturnId($saveData);
}
/**
* @remark :消息详情表保存一条记录
* @name :saveChatItem
* @author :lyh
* @method :post
* @time :2025/4/2 13:45
*/
public function saveChatItem($id,$message,$is_reply = 2){
//创建一个会话
$saveData = [
'user_id'=>$this->user['id'],
'is_reply'=>$is_reply,
'chat_id'=>$id,
'content'=>$message,
];
//同时更改主任务
$this->itemModel->addReturnId($saveData);
$data = ['last_created_at'=>date('Y-m-d H:i:s'),'last_input_content'=>mb_substr($message, 0, 50, "UTF-8").'...'];
return $this->model->edit($data,['id'=>$id]);
}
}