Rouder commited on
Commit
660e6e5
·
verified ·
1 Parent(s): 61a83ff

Delete app.js

Browse files
Files changed (1) hide show
  1. app.js +0 -357
app.js DELETED
@@ -1,357 +0,0 @@
1
- import express from 'express';
2
- import crypto from "crypto";
3
- import {v4} from 'uuid';
4
- import fetch from 'node-fetch';
5
-
6
- const app = express();
7
- // 明确信任的代理数量(例如 1 层代理) 以防报错
8
- app.set('trust proxy', 3);
9
-
10
- // 解析json转为JavaScript对象 添加到req.body中
11
- app.use(express.json({limit: '20mb'}));
12
-
13
- // 构建路由
14
- const router = express.Router();
15
-
16
- // 这个是对外提供api接口的规范
17
- router.post('/v1/chat/completions', async (req, res) => {
18
- await getStandOpenaiAnswer(req, res);
19
- })
20
-
21
- // 封装chat接口
22
- app.use("/chat", router);
23
-
24
- // 接口地址
25
- app.get("/", (req, res) => {
26
- res.send("Hello NodeBackEnd!");
27
- })
28
-
29
- // 端口监听
30
- app.listen(3000, () => {
31
- console.log("Server is running on port 3000");
32
- })
33
-
34
- // 请求处理
35
- async function generateDangBeiAnswer(body, res) {
36
- let thinkingState = {thinking: -1};
37
- let references = [];
38
- let referenceIndex = -1;
39
- let stream = !!body.stream;
40
-
41
- let deviceId = null;
42
- let conversationId = null;
43
-
44
- // 解析消息中的设备ID和对话ID
45
- for (const message of body.messages) {
46
- // 抽出设备ID和对话ID
47
- if (message.role === 'params') {
48
- deviceId = message.content?.deviceId;
49
- conversationId = message.content?.conversationId;
50
- }
51
- }
52
-
53
- // 如果没有设备ID或对话ID,生成新的
54
- if (!deviceId) {
55
- deviceId = generateDeviceId();
56
- }
57
- if (!conversationId) {
58
- conversationId = await createConversation(deviceId);
59
- if (!conversationId) {
60
- return res.status(500).json({error: 'Failed to create conversation'});
61
- }
62
- }
63
-
64
- const userMessage = body.messages[body.messages.length - 1].content;
65
- const modelId = body.model;
66
- const userAction = [];
67
- if (modelId?.indexOf('-deep') !== -1) {
68
- userAction.push('deep');
69
- }
70
- if (modelId?.indexOf('-search') !== -1) {
71
- userAction.push('online');
72
- }
73
-
74
- const payload = {
75
- botCode: 'AI_SEARCH',
76
- conversationId: conversationId,
77
- files: [],
78
- model: 'deepseek',
79
- question: userMessage,
80
- reference: [],
81
- stream: stream,
82
- userAction: userAction.join(','),
83
- };
84
-
85
- const timestamp = getTimestamp();
86
- const nonce = generateNanoid(21);
87
- const sign = generateSign(timestamp, payload, nonce);
88
-
89
- const headers = {
90
- 'Origin': 'https://ai.dangbei.com',
91
- 'Referer': 'https://ai.dangbei.com/',
92
- 'User-Agent': USER_AGENT,
93
- 'deviceId': deviceId,
94
- 'nonce': nonce,
95
- 'sign': sign,
96
- 'timestamp': timestamp,
97
- "Connection": "keep-alive",
98
- 'Content-Type': 'application/json',
99
- };
100
-
101
- const api = `${API_DOMAIN}/ai-search/chatApi/v1/chat`;
102
-
103
- try {
104
- const response = await fetch(api, {
105
- method: 'POST',
106
- headers: headers,
107
- body: JSON.stringify(payload),
108
- });
109
-
110
- if (!response.ok) {
111
- return res.status(500).json({error: `HTTP ${response.status}: ${await response.text()}`});
112
- }
113
-
114
- // 如果是流式数据
115
- if (stream) {
116
- return await transToOAIStream({
117
- resultStream: response.body, res: res, model: modelId, conversationId, deviceId
118
- });
119
- } else {
120
- return success({res, data: "测试成功!"});
121
- // let data = await response.text();
122
- // return success({res, data: JSON.parse(data)});
123
- }
124
- } catch (err) {
125
- return res.status(500).json({error: `Error: ${err.message}`});
126
- }
127
- }
128
-
129
- export async function getStandOpenaiAnswer(req, res) {
130
- let {model, conversation_id, assistant_id, messages, stream, patch} = req.body;
131
- // 取出携带的 authorization
132
- let authorization = req.headers.authorization;
133
-
134
- // DS 模型的特殊处理
135
- if (model?.startsWith("deepseek")) {
136
- // 生成 dangBei 的回复
137
- return await generateDangBeiAnswer(req.body, res);
138
- }
139
-
140
- return fail({res, code: 405, data: "暂不支持该模型!"})
141
- }
142
-
143
- /**
144
- * 将流对象像逐一返回客户端
145
- * @param resultStream
146
- * @param res
147
- * @returns {Promise<void>}
148
- */
149
- export async function responseStream(resultStream, res) {
150
- res.setHeader('Content-Type', 'text/event-stream; charset=utf-8'); // 设置响应头
151
-
152
- // 将回答流逐一返回给客户端
153
- resultStream.on('data', (chunk) => {
154
- res.write(chunk);
155
- });
156
-
157
- // 当回答流结束时结束响应
158
- resultStream.on('end', () => {
159
- res.end();
160
- });
161
- }
162
-
163
- /**
164
- * 封装请求返回
165
- * @param res response
166
- * @param msg message 提示信息
167
- * @param data data 数据
168
- * @returns {*}
169
- */
170
- export function success({res, msg, data}) {
171
- return res.send({code: 200, msg: msg || '请求成���!', data});
172
- }
173
-
174
- /**
175
- * 封装报错请求返回
176
- * @param res response
177
- * @param code 状态码
178
- * @param msg message 提示信息
179
- * @param data data 数据
180
- * @returns {*}
181
- */
182
- export function fail({res, code, msg, data}) {
183
- return res.send({code: code || 999, msg: msg || '网络开小差!', data});
184
- }
185
-
186
- // 配置
187
- const API_DOMAIN = 'https://ai-api.dangbei.net';
188
- const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0';
189
-
190
- // 生成时间戳
191
- function getTimestamp() {
192
- return Math.floor(Date.now() / 1000).toString();
193
- }
194
-
195
- // 生成随机ID
196
- function generateNanoid(size = 21) {
197
- const url_alphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
198
- const random_bytes = crypto.randomBytes(size);
199
- return Array.from(random_bytes)
200
- .map(b => url_alphabet[b & 63]) // 使用位运算确保索引在 0-63 之间
201
- .join('');
202
- }
203
-
204
- // 生成设备ID
205
- function generateDeviceId() {
206
- return `${v4().replace(/-/g, '')}_${generateNanoid(20)}`;
207
- }
208
-
209
- // 生成签名
210
- function generateSign(timestamp, payload, nonce) {
211
- const payload_str = JSON.stringify(payload, null, 0).replace(/\s+/g, ''); // 去除空格
212
- const sign_str = `${timestamp}${payload_str}${nonce}`;
213
- return crypto
214
- .createHash('md5')
215
- .update(sign_str, 'utf-8')
216
- .digest('hex')
217
- .toUpperCase();
218
- }
219
-
220
- // 创建对话
221
- async function createConversation(deviceId) {
222
- const payload = {botCode: 'AI_SEARCH'};
223
- const timestamp = getTimestamp();
224
- const nonce = generateNanoid(21);
225
- const sign = generateSign(timestamp, payload, nonce);
226
-
227
- const headers = {
228
- 'Origin': 'https://ai.dangbei.com',
229
- 'Referer': 'https://ai.dangbei.com/',
230
- 'User-Agent': USER_AGENT,
231
- 'deviceId': deviceId,
232
- 'nonce': nonce,
233
- 'sign': sign,
234
- 'timestamp': timestamp,
235
- 'Content-Type': 'application/json',
236
- };
237
-
238
- const api = `${API_DOMAIN}/ai-search/conversationApi/v1/create`;
239
-
240
- try {
241
- const response = await fetch(api, {
242
- method: 'POST',
243
- headers: headers,
244
- body: JSON.stringify(payload),
245
- });
246
-
247
- if (!response.ok) {
248
- return '';
249
- }
250
-
251
- const data = await response.json();
252
- return data.success ? data.data.conversationId : '';
253
- } catch (err) {
254
- console.error('Error creating conversation:', err);
255
- return '';
256
- }
257
- }
258
-
259
- /**
260
- * 将流对象转为 OAI 规范逐一返回客户端
261
- * @param resultStream
262
- * @param res
263
- * @param model
264
- * @param conversationId
265
- * @param deviceId
266
- * @returns {Promise<void>}
267
- */
268
- export async function transToOAIStream({resultStream, res, model, conversationId, deviceId}) {
269
- // 设置响应头
270
- res.setHeader('Content-Type', 'text/event-stream; charset=utf-8'); // 设置响应头
271
-
272
-
273
- // 缓存未解析完的数据
274
- let buffer = '';
275
-
276
- // 监听流数据
277
- resultStream.on('data', (chunk) => {
278
- try {
279
- // 将 chunk 转换为字符串并拼接到缓存
280
- buffer += chunk.toString();
281
-
282
- // 尝试解析完整的事件块
283
- while (true) {
284
- // 查找第一个完整的事件块
285
- const eventEndIndex = buffer.indexOf('\n\n');
286
- if (eventEndIndex === -1) break; // 没有完整的事件块,退出循环
287
-
288
- // 提取完整的事件块
289
- const eventBlock = buffer.slice(0, eventEndIndex);
290
- buffer = buffer.slice(eventEndIndex + 2); // 移除已解析的部分
291
-
292
- // 解析事件块
293
- const lines = eventBlock.split('\n');
294
- const eventLine = lines.find((line) => line.startsWith('event:'));
295
- const dataLine = lines.find((line) => line.startsWith('data:'));
296
-
297
- if (eventLine && dataLine) {
298
- // 提取 data 字段
299
- const jsonStr = dataLine.slice(5).trim();
300
- const data = JSON.parse(jsonStr);
301
-
302
- // 转换为 OpenAI 格式
303
- const openAIFormat = {
304
- ...data,
305
- content: '',
306
- object: "chat.completion.chunk",
307
- created: Math.floor(Date.now() / 1000), // 当前时间戳
308
- model: model,
309
- choices: [
310
- {
311
- index: 0,
312
- delta: {
313
- content: data.content || "", // 提取 content
314
- },
315
- finish_reason: null,
316
- },
317
- ],
318
- };
319
-
320
- // 发���转换后的数据
321
- res.write(`data: ${JSON.stringify(openAIFormat)}\n\n`);
322
- }
323
- }
324
- } catch (err) {
325
- console.error('Error processing chunk:', err);
326
- }
327
- });
328
-
329
- // 流结束时结束响应
330
- resultStream.on('end', () => {
331
- // 发送结束标记
332
- const endData = {
333
- object: "chat.completion.chunk",
334
- created: Math.floor(Date.now() / 1000), // 当前时间戳
335
- model: model,
336
- conversationId,
337
- deviceId,
338
- choices: [
339
- {
340
- index: 0,
341
- // 空 delta 表示结束
342
- delta: {},
343
- // 结束原因
344
- finish_reason: "stop",
345
- },
346
- ],
347
- };
348
- res.write(`data: ${JSON.stringify(endData)}\n\n`);
349
- res.end();
350
- });
351
-
352
- // 处理错误
353
- resultStream.on('error', (err) => {
354
- console.error('Stream error:', err);
355
- res.status(500).end();
356
- });
357
- }