Spaces:
ainz
/
Configuration error

File size: 5,261 Bytes
688d352
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const Chat = require('./lib/chat.js')
const { uuid, isJson } = require('./lib/tools')


const ChatManager = new Chat()

app.use(bodyParser.json({ limit: '32mb' }))
app.use(bodyParser.urlencoded({ extended: true, limit: '32mb' }))

app.get("/v1/models", async (req, res) => {
  res.json({
    object: "list",
    data: [{
      "id": "deepseek-reasoner",
      "object": "model",
      "created": 1686935002,
      "owned_by": "hixai"
    }],
    object: "list"
  })
})

app.post("/v1/chat/completions", async (req, res) => {

  const token = req.headers.authorization?.replace("Bearer ", "")
  if (!token) {
    res.status(401).json({
      error: "未提供Token!!!"
    })
    return
  }

  const stream = req.body.stream || false
  let { message, chatId, status } = await ChatManager.parserMessagesMode(req.body.messages)
  if (status === 500) {
    res.status(500).json({
      error: "服务器服务错误!!!"
    })
    return
  }

  if (stream) {
    res.setHeader('Content-Type', 'text/event-stream')
    res.setHeader('Cache-Control', 'no-cache')
    res.setHeader('Connection', 'keep-alive')
  } else {
    res.setHeader('Content-Type', 'application/json')
  }

  const returnResponse = async (response, req, res, stream, chatId) => {
    let reasoningStatus = false
    let notStreamContent = ''
    const decoder = new TextDecoder('utf-8')

    const signText = `\n\n\n[ChatID: ${chatId}]\n`

    const StreamTemplate = {
      "id": `chatcmpl-${uuid()}`,
      "object": "chat.completion.chunk",
      "created": new Date().getTime(),
      "choices": [
        {
          "index": 0,
          "delta": {
            "content": null
          },
          "finish_reason": null
        }
      ]
    }

    response.on('data', (chunk) => {
      const decodeText = decoder.decode(chunk)

      const lists = decodeText.split('\n').filter(item => item.trim() !== '')

      for (const item of lists) {
        try {
          if (!item.includes('data')) {
            continue
          }

          const decodeJson = isJson(item.replace(/^data: /, '')) ? JSON.parse(item.replace(/^data: /, '')) : null
          let content = ''
          if (decodeJson === null || (decodeJson.reasoning_content === undefined && decodeJson.content === undefined && decodeJson.thinking_time === undefined)) {
            continue
          }
          content = decodeJson.content || decodeJson.reasoning_content
          if (reasoningStatus === false && decodeJson.reasoning_content) {
            content = `<think>\n${decodeJson.reasoning_content}`
            reasoningStatus = true
          }
          if (decodeJson.thinking_time) {
            content = `\n</think>\n`
          }
          if (content === undefined) {
            continue
          }

          if (stream) {
            StreamTemplate.choices[0].delta.content = content
            res.write(`data: ${JSON.stringify(StreamTemplate)}\n\n`)
          } else {
            notStreamContent += content
          }

        } catch (error) {
          // console.log(error)
          res.status(500)
            .json({
              error: "服务错误!!!"
            })
        }
      }
    })

    response.on('end', () => {
      if (stream) {
        StreamTemplate.choices[0].delta.content = signText
        res.write(`data: ${JSON.stringify(StreamTemplate)}\n\n`)
        res.write(`data: [DONE]\n\n`)
        res.end()
      } else {
        notStreamContent += signText
        const bodyTemplate = {
          "id": `chatcmpl-${uuid()}`,
          "object": "chat.completion",
          "created": new Date().getTime(),
          "model": req.body.model,
          "choices": [
            {
              "index": 0,
              "message": {
                "role": "assistant",
                "content": notStreamContent
              },
              "finish_reason": "stop"
            }
          ],
          "usage": {
            "prompt_tokens": 1024,
            "completion_tokens": notStreamContent.length,
            "total_tokens": 1024 + notStreamContent.length
          }
        }
        res.json(bodyTemplate)
      }
    })
  }

  for (let i = 0; i < 3; i++) {
    try {

      if (!chatId) {
        chatId = await ChatManager.createChat(token)
        if (!chatId) {
          res.status(500).json({
            error: "创建聊天失败!!!"
          })
          return
        }
      }

      let { response, status } = await ChatManager.sendMessage(chatId, message, token, stream)
      if (status === 200 && response) {
        await returnResponse(response, req, res, stream, chatId)
        return
      } else if (status === 403) {
        message = await ChatManager.createForgeChat(req.body.messages)
        chatId = null
      } else {
        res.status(500).json({
          error: "请求发送失败!!!"
        })
        return
      }

    }
    catch (error) {
      res.status(500).json({
        error: "服务器服务错误!!!"
      })
      return
    }

  }

  res.status(500).json({
    error: "多次尝试后依旧失败!!!"
  })

})


app.listen(8999, () => {
  console.log('Server is running on port 8999')
})