JIMMYGGG commited on
Commit
59cc3b4
·
verified ·
1 Parent(s): c9ab6d0

Update src/index.js

Browse files
Files changed (1) hide show
  1. src/index.js +76 -68
src/index.js CHANGED
@@ -1,48 +1,50 @@
1
- const express = require('express')
2
- const { v4: uuidv4 } = require('uuid')
3
- const { stringToHex, chunkToUtf8String } = require('./utils.js')
4
- require('dotenv').config()
5
- const app = express()
6
 
7
  // 中间件配置
8
- app.use(express.json())
9
- app.use(express.urlencoded({ extended: true }))
10
 
11
  app.post('/hf/v1/chat/completions', async (req, res) => {
12
  // o1开头的模型,不支持流式输出
13
  if (req.body.model.startsWith('o1-') && req.body.stream) {
14
  return res.status(400).json({
15
- error: 'Model not supported stream'
16
- })
17
  }
18
 
19
- let currentKeyIndex = 0
20
  try {
21
- const { model, messages, stream = false } = req.body
22
- let authToken = req.headers.authorization?.replace('Bearer ', '')
23
  // 处理逗号分隔的密钥
24
- const keys = authToken.split(',').map(key => key.trim())
25
  if (keys.length > 0) {
26
  // 确保 currentKeyIndex 不会越界
27
  if (currentKeyIndex >= keys.length) {
28
- currentKeyIndex = 0
29
  }
30
  // 使用当前索引获取密钥
31
- authToken = keys[currentKeyIndex]
32
- // 更新索引
33
- currentKeyIndex = (currentKeyIndex + 1)
34
  }
35
  if (authToken && authToken.includes('%3A%3A')) {
36
- authToken = authToken.split('%3A%3A')[1]
37
  }
38
  if (!messages || !Array.isArray(messages) || messages.length === 0 || !authToken) {
39
  return res.status(400).json({
40
- error: 'Invalid request. Messages should be a non-empty array and authorization is required'
41
- })
42
  }
43
 
44
- const formattedMessages = messages.map(msg => `${msg.role}:${msg.content}`).join('\n')
45
- const hexData = stringToHex(formattedMessages, model)
 
 
 
 
 
46
 
47
  const response = await fetch('https://api2.cursor.sh/aiserver.v1.AiService/StreamChat', {
48
  method: 'POST',
@@ -53,91 +55,97 @@ app.post('/hf/v1/chat/completions', async (req, res) => {
53
  'connect-protocol-version': '1',
54
  'user-agent': 'connect-es/1.4.0',
55
  'x-amzn-trace-id': `Root=${uuidv4()}`,
56
- 'x-cursor-checksum': 'zo6Qjequ9b9734d1f13c3438ba25ea31ac93d9287248b9d30434934e9fcbfa6b3b22029e/7e4af391f67188693b722eff0090e8e6608bca8fa320ef20a0ccb5d7d62dfdef',
57
  'x-cursor-client-version': '0.42.3',
58
  'x-cursor-timezone': 'Asia/Shanghai',
59
  'x-ghost-mode': 'false',
60
  'x-request-id': uuidv4(),
61
- Host: 'api2.cursor.sh'
62
  },
63
- body: hexData
64
- })
65
 
66
  if (stream) {
67
- res.setHeader('Content-Type', 'text/event-stream')
68
- res.setHeader('Cache-Control', 'no-cache')
69
- res.setHeader('Connection', 'keep-alive')
70
 
71
- const responseId = `chatcmpl-${uuidv4()}`
72
 
73
  // 使用封装的函数处理 chunk
74
  for await (const chunk of response.body) {
75
- const text = chunkToUtf8String(chunk)
76
 
77
  if (text.length > 0) {
78
- res.write(`data: ${JSON.stringify({
79
- id: responseId,
80
- object: 'chat.completion.chunk',
81
- created: Math.floor(Date.now() / 1000),
82
- model,
83
- choices: [{
84
- index: 0,
85
- delta: {
86
- content: text
87
- }
88
- }]
89
- })}\n\n`)
 
 
 
 
90
  }
91
  }
92
 
93
- res.write('data: [DONE]\n\n')
94
- return res.end()
95
  } else {
96
- let text = ''
97
  // 在非流模式下也使用封装的函数
98
  for await (const chunk of response.body) {
99
- text += chunkToUtf8String(chunk)
100
  }
101
  // 对解析后的字符串进行进一步处理
102
- text = text.replace(/^.*<\|END_USER\|>/s, '')
103
- text = text.replace(/^\n[a-zA-Z]?/, '').trim()
104
- console.log(text)
105
 
106
  return res.json({
107
  id: `chatcmpl-${uuidv4()}`,
108
  object: 'chat.completion',
109
  created: Math.floor(Date.now() / 1000),
110
  model,
111
- choices: [{
112
- index: 0,
113
- message: {
114
- role: 'assistant',
115
- content: text
 
 
 
116
  },
117
- finish_reason: 'stop'
118
- }],
119
  usage: {
120
  prompt_tokens: 0,
121
  completion_tokens: 0,
122
- total_tokens: 0
123
- }
124
- })
125
  }
126
  } catch (error) {
127
- console.error('Error:', error)
128
  if (!res.headersSent) {
129
  if (req.body.stream) {
130
- res.write(`data: ${JSON.stringify({ error: 'Internal server error' })}\n\n`)
131
- return res.end()
132
  } else {
133
- return res.status(500).json({ error: 'Internal server error' })
134
  }
135
  }
136
  }
137
- })
138
 
139
  // 启动服务器
140
- const PORT = process.env.PORT || 3000
141
  app.listen(PORT, () => {
142
- console.log(`服务器运行在端口 ${PORT}`)
143
- })
 
1
+ const express = require('express');
2
+ const { v4: uuidv4 } = require('uuid');
3
+ const { stringToHex, chunkToUtf8String, getRandomIDPro } = require('./utils.js');
4
+ const app = express();
 
5
 
6
  // 中间件配置
7
+ app.use(express.json());
8
+ app.use(express.urlencoded({ extended: true }));
9
 
10
  app.post('/hf/v1/chat/completions', async (req, res) => {
11
  // o1开头的模型,不支持流式输出
12
  if (req.body.model.startsWith('o1-') && req.body.stream) {
13
  return res.status(400).json({
14
+ error: 'Model not supported stream',
15
+ });
16
  }
17
 
18
+ let currentKeyIndex = 0;
19
  try {
20
+ const { model, messages, stream = false } = req.body;
21
+ let authToken = req.headers.authorization?.replace('Bearer ', '');
22
  // 处理逗号分隔的密钥
23
+ const keys = authToken.split(',').map((key) => key.trim());
24
  if (keys.length > 0) {
25
  // 确保 currentKeyIndex 不会越界
26
  if (currentKeyIndex >= keys.length) {
27
+ currentKeyIndex = 0;
28
  }
29
  // 使用当前索引获取密钥
30
+ authToken = keys[currentKeyIndex];
 
 
31
  }
32
  if (authToken && authToken.includes('%3A%3A')) {
33
+ authToken = authToken.split('%3A%3A')[1];
34
  }
35
  if (!messages || !Array.isArray(messages) || messages.length === 0 || !authToken) {
36
  return res.status(400).json({
37
+ error: 'Invalid request. Messages should be a non-empty array and authorization is required',
38
+ });
39
  }
40
 
41
+ const hexData = await stringToHex(messages, model);
42
+
43
+ // 获取checksum,req header中传递优先,环境变量中的等级第二,最后随机生成
44
+ const checksum =
45
+ req.headers['x-cursor-checksum'] ??
46
+ process.env['x-cursor-checksum'] ??
47
+ `zo${getRandomIDPro({ dictType: 'max', size: 6 })}${getRandomIDPro({ dictType: 'max', size: 64 })}/${getRandomIDPro({ dictType: 'max', size: 64 })}`;
48
 
49
  const response = await fetch('https://api2.cursor.sh/aiserver.v1.AiService/StreamChat', {
50
  method: 'POST',
 
55
  'connect-protocol-version': '1',
56
  'user-agent': 'connect-es/1.4.0',
57
  'x-amzn-trace-id': `Root=${uuidv4()}`,
58
+ 'x-cursor-checksum': checksum,
59
  'x-cursor-client-version': '0.42.3',
60
  'x-cursor-timezone': 'Asia/Shanghai',
61
  'x-ghost-mode': 'false',
62
  'x-request-id': uuidv4(),
63
+ Host: 'api2.cursor.sh',
64
  },
65
+ body: hexData,
66
+ });
67
 
68
  if (stream) {
69
+ res.setHeader('Content-Type', 'text/event-stream');
70
+ res.setHeader('Cache-Control', 'no-cache');
71
+ res.setHeader('Connection', 'keep-alive');
72
 
73
+ const responseId = `chatcmpl-${uuidv4()}`;
74
 
75
  // 使用封装的函数处理 chunk
76
  for await (const chunk of response.body) {
77
+ const text = await chunkToUtf8String(chunk);
78
 
79
  if (text.length > 0) {
80
+ res.write(
81
+ `data: ${JSON.stringify({
82
+ id: responseId,
83
+ object: 'chat.completion.chunk',
84
+ created: Math.floor(Date.now() / 1000),
85
+ model,
86
+ choices: [
87
+ {
88
+ index: 0,
89
+ delta: {
90
+ content: text,
91
+ },
92
+ },
93
+ ],
94
+ })}\n\n`,
95
+ );
96
  }
97
  }
98
 
99
+ res.write('data: [DONE]\n\n');
100
+ return res.end();
101
  } else {
102
+ let text = '';
103
  // 在非流模式下也使用封装的函数
104
  for await (const chunk of response.body) {
105
+ text += await chunkToUtf8String(chunk);
106
  }
107
  // 对解析后的字符串进行进一步处理
108
+ text = text.replace(/^.*<\|END_USER\|>/s, '');
109
+ text = text.replace(/^\n[a-zA-Z]?/, '').trim();
110
+ // console.log(text)
111
 
112
  return res.json({
113
  id: `chatcmpl-${uuidv4()}`,
114
  object: 'chat.completion',
115
  created: Math.floor(Date.now() / 1000),
116
  model,
117
+ choices: [
118
+ {
119
+ index: 0,
120
+ message: {
121
+ role: 'assistant',
122
+ content: text,
123
+ },
124
+ finish_reason: 'stop',
125
  },
126
+ ],
 
127
  usage: {
128
  prompt_tokens: 0,
129
  completion_tokens: 0,
130
+ total_tokens: 0,
131
+ },
132
+ });
133
  }
134
  } catch (error) {
135
+ console.error('Error:', error);
136
  if (!res.headersSent) {
137
  if (req.body.stream) {
138
+ res.write(`data: ${JSON.stringify({ error: 'Internal server error' })}\n\n`);
139
+ return res.end();
140
  } else {
141
+ return res.status(500).json({ error: 'Internal server error' });
142
  }
143
  }
144
  }
145
+ });
146
 
147
  // 启动服务器
148
+ const PORT = process.env.PORT || 3000;
149
  app.listen(PORT, () => {
150
+ console.log(`服务器运行在端口 ${PORT}`);
151
+ });