-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
263 lines (229 loc) · 7.94 KB
/
main.js
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
const express = require('express');
const axios = require('axios');
const { appendToFile } = require('./fileWriter');
const path = require('path');
const db = require('./database');
const app = express();
const PORT = 3000;
const UPSTREAM_URL = 'http://127.0.0.1:8300';
app.use(express.json());
app.use(express.text());
function isValidJson(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}
// 发送消息
app.post('/backend-api/conversation', async (req, res) => {
try {
// res.status(429).json({ detail: '测试' });
// return;
console.log(UPSTREAM_URL + req.url);
const response = await axios({
method: req.method,
url: UPSTREAM_URL + req.url,
headers: req.headers,
data: req.body,
responseType: 'stream'
});
// 设置状态码和响应头
res.status(response.status);
res.set(response.headers);
// 处理json响应
let jsonData = '';
// 处理响应数据
if (response.headers['content-type'].includes('application/json'))
{
response.data.on('data', (chunk) => { jsonData += chunk; });
response.data.on('end', () => {
res.send(jsonData);
});
}
else if (response.headers['content-type'].includes('text/event-stream'))
{
const fileName = Date.now() + '.txt';
const filePath = path.join(__dirname, 'msg', fileName);
let msg_id = '';
let conversation_id = '';
// 处理sse响应
response.data.on('data', chunk => {
// console.log(`Received chunk: ${chunk}`);
res.write(chunk);
jsonData += chunk;
// 把数据写入文件(此处换成写入数据库)
// appendToFile(chunk, filePath);
// // 解析数据,如果以data: 开头,则截取其中的消息内容并转换成json格式
// const data = chunk.toString();
// if (data.startsWith('data:')) {
// const msg = (data.slice(5)).trim();
// if(isValidJson(msg))
// {
// const jsonMsg = JSON.parse(msg);
// if(jsonMsg.conversation_id && !conversation_id) {
// conversation_id = jsonMsg.conversation_id;
// }
// if(jsonMsg.message.id && !msg_id) {
// msg_id = jsonMsg.message.id;
// }
// }
// }
});
// 响应结束后关闭连接
response.data.on('end', () => {
let body = JSON.stringify(req.body);
// console.log(body);
// 删除会话内容
db.deleteRecord('chat_conversation_detail', conversation_id, (err, result) => {});
// 写入数据库
db.addRecord('chat_msg', {
conversation_id: conversation_id,
msg_id: msg_id,
body: body,
result: jsonData,
createtime: Math.floor(Date.now() / 1000)
}, (err, result) => {
if (err) {
console.log(err);
}
console.log(result);
});
res.end();
});
}
else
{
// 处理其他响应
response.data.pipe(res);
}
}
catch (error)
{
console.log(error);
// res.status(429).json({ detail: error.message });
}
});
// 获取历史会话记录
app.get('/backend-api/conversations', async (req, res) => {
// const { offset, limit, order } = req.query;
try {
const response = await axios({
method: req.method,
url: UPSTREAM_URL + req.url,
headers: req.headers,
data: req.body,
responseType: 'stream'
});
res.status(response.status);
res.set(response.headers);
response.data.pipe(res);
// 处理业务逻辑
if (response.headers['content-type'].includes('application/json')) {
let jsonData = '';
response.data.on('data', (chunk) => { jsonData += chunk; });
response.data.on('end', () => {
// res.send(jsonData);
});
}
} catch (error) {
res.status(429).json({ detail: error.message });
}
});
// 获取单条消息详情
app.get('/backend-api/conversation/:id', async (req, res) => {
try {
// 获取会话id
const conversation_id = req.params.id;
// 根据会话id,然后查询数据库,如何数据库存在。则返回数据,否则返回上游数据并写入数据库
db.getRecord('chat_conversation_detail', { conversation_id: conversation_id }, async (err, result) => {
if (err) {
console.log(err);
}
if (result) {
console.log(result);
res.send(result.content);
} else {
// 不存在则查询上游数据并写入数据库
const response = await axios({
method: req.method,
url: UPSTREAM_URL + req.url,
headers: req.headers,
data: req.body,
responseType: 'stream'
});
res.status(response.status);
res.set(response.headers);
// 处理响应数据
let jsonData = '';
response.data.on('data', (chunk) => { jsonData += chunk; });
response.data.on('end', () => {
// 写入数据库
db.addRecord('chat_conversation_detail', {
conversation_id: conversation_id,
content: jsonData,
createtime: Math.floor(Date.now() / 1000)
}, (err, result) => {
if (err) {
console.log(err);
}
console.log(result);
});
// 响应数据
res.send(jsonData);
});
}
});
// response.data.pipe(res);
}
catch (error)
{
res.status(429).json({ detail: error.message });
}
});
// 修改标题接口
app.post('/backend-api/conversation/gen_title/:id', async (req, res) => {
try {
const response = await axios({
method: req.method,
url: UPSTREAM_URL + req.url,
headers: req.headers,
data: req.body,
responseType: 'stream'
});
res.status(response.status);
res.set(response.headers);
response.data.pipe(res);
}
catch (error)
{
res.status(429).json({ detail: error.message });
}
});
// 查询chatgpt模型接口
app.post('/backend-api/models', async (req, res) => {
try {
const response = await axios({
method: 'get',
url: 'https://free.18230.work/chatgpt/backend-api/models',
headers: {
'Authorization': 'Bearer ' + req.headers.token
}
});
res.status(200);
response.data.pipe(res);
}
catch (error)
{
res.status(200).json({ detail: error.message });
}
});
// 启动服务器
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
// res.type('txt'); // Content-Type: text/plain
// res.type('html'); // Content-Type: text/html
// res.type('json'); // Content-Type: application/json
// res.type('text/event-stream'); // Content-Type: text/event-stream