dan92 commited on
Commit
7dae2d7
·
verified ·
1 Parent(s): c0786fe

Upload 2 files

Browse files
Files changed (2) hide show
  1. src/index.js +363 -0
  2. src/models.js +14 -0
src/index.js ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const Koa = require('koa')
2
+ const Router = require('koa-router')
3
+ const bodyParser = require('koa-bodyparser')
4
+ const models = require("./models")
5
+ const crypto = require('crypto')
6
+
7
+
8
+ const app = new Koa()
9
+ const router = new Router()
10
+
11
+ // 使用 bodyParser 中间件
12
+ app.use(bodyParser())
13
+
14
+ // 配置 bodyParser
15
+ app.use(bodyParser({
16
+ enableTypes: ['json', 'form', 'text'],
17
+ jsonLimit: '30mb', // JSON 数据大小限制
18
+ formLimit: '30mb', // form 数据大小限制
19
+ textLimit: '30mb', // text 数据大小限制
20
+ }))
21
+
22
+ // 添加 CORS 中间件
23
+ app.use(async (ctx, next) => {
24
+ ctx.set('Access-Control-Allow-Origin', '*');
25
+ ctx.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
26
+ ctx.set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
27
+ ctx.set('Access-Control-Max-Age', '3600');
28
+
29
+ // 处理 OPTIONS 请求
30
+ if (ctx.method === 'OPTIONS') {
31
+ ctx.status = 204;
32
+ return;
33
+ }
34
+
35
+ await next();
36
+ });
37
+
38
+ // 添加请求日志中间件
39
+ app.use(async (ctx, next) => {
40
+ const start = Date.now()
41
+ console.log(`[${new Date().toISOString()}] ${ctx.method} ${ctx.url} - Request started`)
42
+ try {
43
+ await next()
44
+ } catch (err) {
45
+ throw err
46
+ } finally {
47
+ const ms = Date.now() - start
48
+ console.log(`[${new Date().toISOString()}] ${ctx.method} ${ctx.url} - Response ${ctx.status} - ${ms}ms`)
49
+ }
50
+ })
51
+
52
+ // 错误处理中间件
53
+ app.use(async (ctx, next) => {
54
+ try {
55
+ await next()
56
+ // 只有当没有任何路由处理请求时才设置 404
57
+ if (ctx.status === 404 && !ctx.body) {
58
+ ctx.status = 404
59
+ ctx.body = {
60
+ error: 'Not Found',
61
+ message: `The requested path ${ctx.path} was not found`,
62
+ availableEndpoints: [
63
+ '/v1/chat/completions',
64
+ '/hf/v1/chat/completions',
65
+ '/v1/models',
66
+ '/hf/v1/models'
67
+ ]
68
+ }
69
+ }
70
+ } catch (err) {
71
+ console.error('Error details:', {
72
+ path: ctx.path,
73
+ method: ctx.method,
74
+ error: err.message,
75
+ stack: err.stack
76
+ })
77
+ ctx.status = err.status || 500
78
+ ctx.body = {
79
+ error: err.name || 'Internal Server Error',
80
+ message: err.message,
81
+ path: ctx.path
82
+ }
83
+ ctx.app.emit('error', err, ctx)
84
+ }
85
+ })
86
+
87
+ const makeRequest = async (session_id, requestModel, messages) => {
88
+ console.log('开始请求:', { session_id: '***', model: requestModel })
89
+ try {
90
+ // 设置请求头
91
+ const myHeaders = new Headers()
92
+ myHeaders.append("Cookie", `session_id=${session_id}`)
93
+ myHeaders.append("User-Agent", "Apifox/1.0.0 (https://apifox.com)");
94
+ myHeaders.append("Content-Type", "application/json")
95
+ myHeaders.append("Accept", "*/*")
96
+ myHeaders.append("Host", "www.genspark.ai")
97
+ myHeaders.append("Connection", "keep-alive")
98
+
99
+ // 设置请求体
100
+ var body = JSON.stringify({
101
+ "type": "COPILOT_MOA_CHAT",
102
+ "current_query_string": "type=COPILOT_MOA_CHAT",
103
+ "messages": messages,
104
+ "action_params": {},
105
+ "extra_data": {
106
+ "models": [
107
+ models[`${requestModel}`] || models["claude-3-5-sonnet-20241022"]
108
+ ],
109
+ "run_with_another_model": false,
110
+ "writingContent": null
111
+ }
112
+ })
113
+
114
+ const requestConfig = {
115
+ method: 'POST',
116
+ headers: myHeaders,
117
+ body: body,
118
+ redirect: 'follow'
119
+ };
120
+
121
+ const response = await fetch("https://www.genspark.ai/api/copilot/ask", requestConfig)
122
+
123
+ if (!response.ok) {
124
+ throw new Error(`HTTP error! status: ${response.status}`)
125
+ }
126
+
127
+ return response
128
+ } catch (error) {
129
+ console.error('请求出错:', error)
130
+ throw error
131
+ }
132
+ }
133
+
134
+ // 创建处理函数
135
+ const handleChatCompletions = async (ctx) => {
136
+ const { messages, stream = false, model = 'claude-3-5-sonnet' } = ctx.request.body
137
+ const session_id = ctx.get('Authorization')?.replace('Bearer ', '')
138
+
139
+ console.log('收到请求:', {
140
+ path: ctx.path,
141
+ model,
142
+ stream,
143
+ messages_count: messages?.length
144
+ })
145
+
146
+ if (!session_id) {
147
+ ctx.status = 401
148
+ ctx.body = { error: '未提供有效的 session_id' }
149
+ return
150
+ }
151
+
152
+ try {
153
+ const response = await makeRequest(session_id, model, messages)
154
+
155
+ if (!response.body) {
156
+ throw new Error('Response body is null')
157
+ }
158
+
159
+ if (stream == "true" || stream == true) {
160
+ ctx.status = 200
161
+ ctx.set({
162
+ 'Content-Type': 'text/event-stream',
163
+ 'Cache-Control': 'no-cache',
164
+ 'Connection': 'keep-alive',
165
+ })
166
+ } else {
167
+ ctx.status = 200
168
+ ctx.set({
169
+ 'Content-Type': 'application/json',
170
+ })
171
+ }
172
+
173
+ const messageId = crypto.randomUUID()
174
+ const reader = response.body.getReader()
175
+ let resBody = {
176
+ id: `chatcmpl-${messageId}`,
177
+ object: 'chat.completion',
178
+ created: Math.floor(Date.now() / 1000),
179
+ model,
180
+ choices: [],
181
+ usage: {
182
+ prompt_tokens: 0,
183
+ completion_tokens: 0,
184
+ total_tokens: 0,
185
+ },
186
+ }
187
+
188
+ if (stream == "true" || stream == true) {
189
+ ctx.res.write(`data: ${JSON.stringify({
190
+ "id": `chatcmpl-${messageId}`,
191
+ "choices": [
192
+ {
193
+ "index": 0,
194
+ "delta": {
195
+ "content": "",
196
+ "role": "assistant"
197
+ }
198
+ }
199
+ ],
200
+ "created": Math.floor(Date.now() / 1000),
201
+ "model": model,
202
+ "object": "chat.completion.chunk"
203
+ })}\n\n`)
204
+ }
205
+
206
+ try {
207
+ while (true) {
208
+ const { done, value } = await reader.read()
209
+ if (done) {
210
+ if (stream == "true" || stream == true) {
211
+ ctx.res.write('data: [DONE]\n\n')
212
+ }
213
+ break
214
+ }
215
+
216
+ if (stream == "true" || stream == true) {
217
+ const text = new TextDecoder().decode(value)
218
+ const textContent = [...text.matchAll(/data:.*"}/g)]
219
+
220
+ textContent.forEach(item => {
221
+ if (!item[0]) return
222
+ const content = JSON.parse(item[0].replace("data: ", ''))
223
+ if (!content || !content.delta) return
224
+
225
+ ctx.res.write(`data: ${JSON.stringify({
226
+ "id": `chatcmpl-${messageId}`,
227
+ "choices": [
228
+ {
229
+ "index": 0,
230
+ "delta": {
231
+ "content": content.delta
232
+ }
233
+ }
234
+ ],
235
+ "created": Math.floor(Date.now() / 1000),
236
+ "model": model,
237
+ "object": "chat.completion.chunk"
238
+ })}\n\n`)
239
+ })
240
+ } else {
241
+ const text = new TextDecoder().decode(value)
242
+ const textContent = [...text.matchAll(/data:.*"}/g)]
243
+
244
+ textContent.forEach(item => {
245
+ if (!item[0]) return
246
+ const content = JSON.parse(item[0].replace("data: ", ''))
247
+ if (!content || !content.field_value || content.field_name == 'session_state.answer_is_finished' || content.field_name == 'content' || content.field_name == 'session_state' || content.delta || content.type == 'project_field') return
248
+
249
+ resBody.choices.push({
250
+ index: 0,
251
+ message: {
252
+ role: 'assistant',
253
+ content: content.field_value,
254
+ },
255
+ finish_reason: 'stop',
256
+ })
257
+ resBody.usage.total_tokens = content.field_value.length
258
+ })
259
+ }
260
+ }
261
+
262
+ if (stream == "false" || stream == false) {
263
+ if (resBody.choices.length === 0) {
264
+ resBody.choices.push({
265
+ index: 0,
266
+ message: {
267
+ role: 'assistant',
268
+ content: '抱歉,我无法处理您的请求。',
269
+ },
270
+ finish_reason: 'stop',
271
+ })
272
+ }
273
+ ctx.body = resBody
274
+ } else {
275
+ ctx.res.end()
276
+ }
277
+ } catch (error) {
278
+ console.error('响应处理出错:', error)
279
+ if (stream == "true" || stream == true) {
280
+ try {
281
+ ctx.res.write(`data: ${JSON.stringify({
282
+ "id": `chatcmpl-${messageId}`,
283
+ "choices": [
284
+ {
285
+ "index": 0,
286
+ "delta": {
287
+ "content": "\n\n抱歉,处理您的请求时出现错误。"
288
+ }
289
+ }
290
+ ],
291
+ "created": Math.floor(Date.now() / 1000),
292
+ "model": model,
293
+ "object": "chat.completion.chunk"
294
+ })}\n\n`)
295
+ ctx.res.write('data: [DONE]\n\n')
296
+ } catch (e) {
297
+ console.error('发送错误信息失败:', e)
298
+ } finally {
299
+ ctx.res.end()
300
+ }
301
+ } else {
302
+ ctx.status = 500
303
+ ctx.body = { error: '响应处理失败', details: error.toString() }
304
+ }
305
+ }
306
+ } catch (error) {
307
+ console.error('请求处理出错:', error)
308
+ ctx.status = error.status || 500
309
+ ctx.body = {
310
+ error: error.message || '请求处理失败',
311
+ details: error.toString()
312
+ }
313
+ }
314
+ }
315
+
316
+ // 创建获取模型列表处理函数
317
+ const handleModels = async (ctx) => {
318
+ ctx.body = {
319
+ object: "list",
320
+ data: Object.keys(models).map(model => ({
321
+ id: model,
322
+ object: "model",
323
+ created: 1706745938,
324
+ owned_by: "genspark"
325
+ }))
326
+ }
327
+ }
328
+
329
+ // 注册路由 - 同时支持 /v1 和 /hf/v1 路径
330
+ router.post('/v1/chat/completions', handleChatCompletions)
331
+ router.post('/hf/v1/chat/completions', handleChatCompletions)
332
+ router.get('/v1/models', handleModels)
333
+ router.get('/hf/v1/models', handleModels)
334
+
335
+ // 添加根路由处理器
336
+ router.get('/', async (ctx) => {
337
+ ctx.body = {
338
+ status: 'ok',
339
+ message: 'API server is running',
340
+ version: '1.0.0',
341
+ endpoints: [
342
+ '/v1/chat/completions',
343
+ '/hf/v1/chat/completions',
344
+ '/v1/models',
345
+ '/hf/v1/models'
346
+ ]
347
+ }
348
+ })
349
+
350
+ // 注册路由中间件
351
+ app.use(router.routes()).use(router.allowedMethods())
352
+
353
+ // 启动服务器
354
+ const PORT = process.env.PORT || 3000
355
+ app.listen(PORT, '0.0.0.0', () => {
356
+ console.log('='.repeat(50))
357
+ console.log(`服务器启动于 http://0.0.0.0:${PORT}`)
358
+ console.log('环境变量:', {
359
+ PORT: process.env.PORT,
360
+ NODE_ENV: process.env.NODE_ENV
361
+ })
362
+ console.log('='.repeat(50))
363
+ });
src/models.js ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const models = {
2
+ "o1-preview": "o1-preview",
3
+ "o1-mini": "o1-preview",
4
+ "claude-3-5-sonnet-20240620": "claude-3-5-sonnet",
5
+ "claude-3-5-sonnet-20241022": "claude-3-5-sonnet",
6
+ "claude-3-5-haiku-20241022": "claude-3-5-haiku",
7
+ "claude-3-haiku-20240307": "claude-3-5-haiku",
8
+ "gpt-4o": "gpt-4o",
9
+ "gpt-4o-mini": "gpt-4o-mini",
10
+ "gemini-1.5-pro-latest": "gemini-1.5-pro",
11
+ "gemini-1.5-flash-latest": "gemini-1.5-flash"
12
+ }
13
+
14
+ module.exports = models