File size: 10,428 Bytes
f66aefe
 
 
 
5cc3417
f66aefe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
863deaf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
872264e
 
863deaf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f66aefe
056a2d0
f66aefe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0384372
 
 
 
 
 
 
f66aefe
42aa48d
 
f66aefe
 
 
e4be06a
 
f66aefe
 
 
056a2d0
0eba76f
 
 
 
 
 
f66aefe
 
 
 
 
 
 
 
0384372
 
 
 
 
f66aefe
056a2d0
f66aefe
 
 
 
 
 
056a2d0
f66aefe
 
 
 
 
 
 
4ba6a3e
 
 
 
 
 
 
 
 
 
 
 
 
f66aefe
 
 
 
 
 
 
 
 
 
 
 
 
0eba76f
f66aefe
 
 
 
 
 
 
 
 
 
 
 
 
 
4ba6a3e
f66aefe
 
 
 
e4be06a
f66aefe
e4be06a
f66aefe
 
 
 
 
 
 
 
 
 
 
 
0eba76f
f66aefe
 
 
 
 
 
 
 
e4be06a
f66aefe
e4be06a
f66aefe
4ba6a3e
 
 
 
 
f66aefe
4ba6a3e
 
 
f66aefe
 
 
 
 
4ba6a3e
 
 
 
 
 
 
 
 
 
f66aefe
 
 
 
 
056a2d0
872264e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
056a2d0
 
872264e
f66aefe
 
 
0384372
 
 
 
 
f66aefe
e4be06a
b385d50
863deaf
e4be06a
f66aefe
 
 
 
 
 
 
 
 
e4be06a
f66aefe
e4be06a
 
 
 
 
 
ff08534
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ba6a3e
e4be06a
f66aefe
 
ce8ed19
 
42aa48d
 
 
 
 
 
 
 
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
const Koa = require('koa')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const models = require("./models")
const crypto = require('crypto')


const app = new Koa()
const router = new Router()

// 使用 bodyParser 中间件
app.use(bodyParser())

// 配置 bodyParser
app.use(bodyParser({
  enableTypes: ['json', 'form', 'text'],
  jsonLimit: '30mb',  // JSON 数据大小限制
  formLimit: '30mb',  // form 数据大小限制
  textLimit: '30mb',  // text 数据大小限制
}))

// 添加 CORS 中间件
app.use(async (ctx, next) => {
  ctx.set('Access-Control-Allow-Origin', '*');
  ctx.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  ctx.set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
  ctx.set('Access-Control-Max-Age', '3600');
  
  // 处理 OPTIONS 请求
  if (ctx.method === 'OPTIONS') {
    ctx.status = 204;
    return;
  }
  
  await next();
});

// 添加请求日志中间件
app.use(async (ctx, next) => {
  const start = Date.now()
  console.log(`[${new Date().toISOString()}] ${ctx.method} ${ctx.url} - Request started`)
  try {
    await next()
  } catch (err) {
    throw err
  } finally {
    const ms = Date.now() - start
    console.log(`[${new Date().toISOString()}] ${ctx.method} ${ctx.url} - Response ${ctx.status} - ${ms}ms`)
  }
})

// 错误处理中间件
app.use(async (ctx, next) => {
  try {
    await next()
    // 只有当没有任何路由处理请求时才设置 404
    if (ctx.status === 404 && !ctx.body) {
      ctx.status = 404
      ctx.body = {
        error: 'Not Found',
        message: `The requested path ${ctx.path} was not found`,
        availableEndpoints: [
          '/v1/chat/completions',
          '/hf/v1/chat/completions',
          '/v1/models',
          '/hf/v1/models'
        ]
      }
    }
  } catch (err) {
    console.error('Error details:', {
      path: ctx.path,
      method: ctx.method,
      error: err.message,
      stack: err.stack
    })
    ctx.status = err.status || 500
    ctx.body = {
      error: err.name || 'Internal Server Error',
      message: err.message,
      path: ctx.path
    }
    ctx.app.emit('error', err, ctx)
  }
})

const makeRequest = async (session_id, requestModel, messages) => {
  console.log('开始请求:', { session_id: '***', model: requestModel })
  try {
    // 设置请求头
    const myHeaders = new Headers()
    myHeaders.append("Cookie", `session_id=${session_id}`)
    myHeaders.append("User-Agent", "Apifox/1.0.0 (https://apifox.com)");
    myHeaders.append("Content-Type", "application/json")
    myHeaders.append("Accept", "*/*")
    myHeaders.append("Host", "www.genspark.ai")
    myHeaders.append("Connection", "keep-alive")

    // 设置请求体
    var body = JSON.stringify({
      "type": "COPILOT_MOA_CHAT",
      "current_query_string": "type=COPILOT_MOA_CHAT",
      "messages": messages,
      "action_params": {},
      "extra_data": {
        "models": [
          models[`${requestModel}`] || models["claude-3-5-sonnet-20241022"]
        ],
        "run_with_another_model": false,
        "writingContent": null
      }
    })

    const requestConfig = {
      method: 'POST',
      headers: myHeaders,
      body: body,
      redirect: 'follow'
    };

    const response = await fetch("https://www.genspark.ai/api/copilot/ask", requestConfig)
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    return response
  } catch (error) {
    console.error('请求出错:', error)
    throw error
  }
}

// 创建处理函数
const handleChatCompletions = async (ctx) => {
  const { messages, stream = false, model = 'claude-3-5-sonnet' } = ctx.request.body
  const session_id = ctx.get('Authorization')?.replace('Bearer ', '')

  console.log('收到请求:', {
    path: ctx.path,
    model,
    stream,
    messages_count: messages?.length
  })

  if (!session_id) {
    ctx.status = 401
    ctx.body = { error: '未提供有效的 session_id' }
    return
  }

  try {
    const response = await makeRequest(session_id, model, messages)
    
    if (!response.body) {
      throw new Error('Response body is null')
    }

    if (stream == "true" || stream == true) {
      ctx.status = 200
      ctx.set({
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
      })
    } else {
      ctx.status = 200
      ctx.set({
        'Content-Type': 'application/json',
      })
    }

    const messageId = crypto.randomUUID()
    const reader = response.body.getReader()
    let resBody = {
      id: `chatcmpl-${messageId}`,
      object: 'chat.completion',
      created: Math.floor(Date.now() / 1000),
      model,
      choices: [],
      usage: {
        prompt_tokens: 0,
        completion_tokens: 0,
        total_tokens: 0,
      },
    }

    if (stream == "true" || stream == true) {
      ctx.res.write(`data: ${JSON.stringify({

        "id": `chatcmpl-${messageId}`,

        "choices": [

          {

            "index": 0,

            "delta": {

              "content": "",

              "role": "assistant"

            }

          }

        ],

        "created": Math.floor(Date.now() / 1000),

        "model": model,

        "object": "chat.completion.chunk"

      })}\n\n`)
    }

    try {
      while (true) {
        const { done, value } = await reader.read()
        if (done) {
          if (stream == "true" || stream == true) {
            ctx.res.write('data: [DONE]\n\n')
          }
          break
        }

        if (stream == "true" || stream == true) {
          const text = new TextDecoder().decode(value)
          const textContent = [...text.matchAll(/data:.*"}/g)]

          textContent.forEach(item => {
            if (!item[0]) return
            const content = JSON.parse(item[0].replace("data: ", ''))
            if (!content || !content.delta) return

            ctx.res.write(`data: ${JSON.stringify({

              "id": `chatcmpl-${messageId}`,

              "choices": [

                {

                  "index": 0,

                  "delta": {

                    "content": content.delta

                  }

                }

              ],

              "created": Math.floor(Date.now() / 1000),

              "model": model,

              "object": "chat.completion.chunk"

            })}\n\n`)
          })
        } else {
          const text = new TextDecoder().decode(value)
          const textContent = [...text.matchAll(/data:.*"}/g)]

          textContent.forEach(item => {
            if (!item[0]) return
            const content = JSON.parse(item[0].replace("data: ", ''))
            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

            resBody.choices.push({
              index: 0,
              message: {
                role: 'assistant',
                content: content.field_value,
              },
              finish_reason: 'stop',
            })
            resBody.usage.total_tokens = content.field_value.length
          })
        }
      }

      if (stream == "false" || stream == false) {
        if (resBody.choices.length === 0) {
          resBody.choices.push({
            index: 0,
            message: {
              role: 'assistant',
              content: '抱歉,我无法处理您的请求。',
            },
            finish_reason: 'stop',
          })
        }
        ctx.body = resBody
      } else {
        ctx.res.end()
      }
    } catch (error) {
      console.error('响应处理出错:', error)
      if (stream == "true" || stream == true) {
        try {
          ctx.res.write(`data: ${JSON.stringify({

            "id": `chatcmpl-${messageId}`,

            "choices": [

              {

                "index": 0,

                "delta": {

                  "content": "\n\n抱歉,处理您的请求时出现错误。"

                }

              }

            ],

            "created": Math.floor(Date.now() / 1000),

            "model": model,

            "object": "chat.completion.chunk"

          })}\n\n`)
          ctx.res.write('data: [DONE]\n\n')
        } catch (e) {
          console.error('发送错误信息失败:', e)
        } finally {
          ctx.res.end()
        }
      } else {
        ctx.status = 500
        ctx.body = { error: '响应处理失败', details: error.toString() }
      }
    }
  } catch (error) {
    console.error('请求处理出错:', error)
    ctx.status = error.status || 500
    ctx.body = { 
      error: error.message || '请求处理失败',
      details: error.toString()
    }
  }
}

// 创建获取模型列表处理函数
const handleModels = async (ctx) => {
  ctx.body = {
    object: "list",
    data: Object.keys(models).map(model => ({
      id: model,
      object: "model",
      created: 1706745938,
      owned_by: "genspark"
    }))
  }
}

// 注册路由 - 同时支持 /v1 和 /hf/v1 路径
router.post('/v1/chat/completions', handleChatCompletions)
router.post('/hf/v1/chat/completions', handleChatCompletions)
router.get('/v1/models', handleModels)
router.get('/hf/v1/models', handleModels)

// 添加根路由处理器
router.get('/', async (ctx) => {
  ctx.body = {
    status: 'ok',
    message: 'API server is running',
    version: '1.0.0',
    endpoints: [
      '/v1/chat/completions',
      '/hf/v1/chat/completions',
      '/v1/models',
      '/hf/v1/models'
    ]
  }
})

// 注册路由中间件
app.use(router.routes()).use(router.allowedMethods())

// 启动服务器
const PORT = process.env.PORT || 3000
app.listen(PORT, '0.0.0.0', () => {
  console.log('='.repeat(50))
  console.log(`服务器启动于 http://0.0.0.0:${PORT}`)
  console.log('环境变量:', {
    PORT: process.env.PORT,
    NODE_ENV: process.env.NODE_ENV
  })
  console.log('='.repeat(50))
});