File size: 8,788 Bytes
5cd566d |
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 |
import { createServerAdapter } from '@whatwg-node/server'
import { AutoRouter, json, error, cors } from 'itty-router'
import { createServer } from 'http'
import dotenv from 'dotenv'
dotenv.config()
class Config {
constructor() {
this.API_PREFIX = process.env.API_PREFIX || '/'
this.API_KEY = process.env.API_KEY || ''
this.MAX_RETRY_COUNT = process.env.MAX_RETRY_COUNT || 3
this.RETRY_DELAY = process.env.RETRY_DELAY || 5000
this.FAKE_HEADERS = process.env.FAKE_HEADERS || {
Accept: '*/*',
'Accept-Encoding': 'gzip, deflate, br, zstd',
'Accept-Language': 'zh-CN,zh;q=0.9',
Origin: 'https://duckduckgo.com/',
Cookie: 'l=wt-wt; ah=wt-wt; dcm=6',
Dnt: '1',
Priority: 'u=1, i',
Referer: 'https://duckduckgo.com/',
'Sec-Ch-Ua': '"Microsoft Edge";v="129", "Not(A:Brand";v="8", "Chromium";v="129"',
'Sec-Ch-Ua-Mobile': '?0',
'Sec-Ch-Ua-Platform': '"Windows"',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-origin',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36',
}
}
}
const config = new Config()
const { preflight, corsify } = cors({
origin: '*',
allowMethods: '*',
exposeHeaders: '*',
})
const withBenchmarking = (request) => {
request.start = Date.now()
}
const withAuth = (request) => {
if (config.API_KEY) {
const authHeader = request.headers.get('Authorization')
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return error(401, 'Unauthorized: Missing or invalid Authorization header')
}
const token = authHeader.substring(7)
if (token !== config.API_KEY) {
return error(403, 'Forbidden: Invalid API key')
}
}
}
const logger = (res, req) => {
console.log(req.method, res.status, req.url, Date.now() - req.start, 'ms')
}
const router = AutoRouter({
before: [withBenchmarking, preflight, withAuth],
missing: () => error(404, '404 not found.'),
finally: [corsify, logger],
})
router.get('/', () => json({ message: 'API 服务运行中~' }))
router.get('/ping', () => json({ message: 'pong' }))
router.get(config.API_PREFIX + '/v1/models', () =>
json({
object: 'list',
data: [
{ id: 'gpt-4o-mini', object: 'model', owned_by: 'ddg' },
{ id: 'claude-3-haiku', object: 'model', owned_by: 'ddg' },
{ id: 'llama-3.1-70b', object: 'model', owned_by: 'ddg' },
{ id: 'mixtral-8x7b', object: 'model', owned_by: 'ddg' },
],
})
)
router.post(config.API_PREFIX + '/v1/chat/completions', (req) => handleCompletion(req))
async function handleCompletion(request) {
try {
const { model: inputModel, messages, stream: returnStream } = await request.json()
const model = convertModel(inputModel)
const content = messagesPrepare(messages)
return createCompletion(model, content, returnStream)
} catch (err) {
error(500, err.message)
}
}
async function createCompletion(model, content, returnStream, retryCount = 0) {
const token = await requestToken()
try {
const response = await fetch(`https://duckduckgo.com/duckchat/v1/chat`, {
method: 'POST',
headers: {
...config.FAKE_HEADERS,
Accept: 'text/event-stream',
'Content-Type': 'application/json',
'x-vqd-4': token,
},
body: JSON.stringify({
model: model,
messages: [
{
role: 'user',
content: content,
},
],
}),
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
return handlerStream(model, response.body, returnStream)
} catch (err) {
console.log(err)
if (retryCount < config.MAX_RETRY_COUNT) {
console.log('Retrying... count', ++retryCount)
await new Promise((resolve) => setTimeout(resolve, config.RETRY_DELAY))
return await createCompletion(model, content, returnStream, retryCount)
}
throw err
}
}
async function handlerStream(model, rb, returnStream) {
let bwzChunk = ''
let previousText = ''
const handChunkData = (chunk) => {
chunk = chunk.trim()
if (bwzChunk != '') {
chunk = bwzChunk + chunk
bwzChunk = ''
}
if (chunk.includes('[DONE]')) {
return chunk
}
if (chunk.slice(-2) !== '"}') {
bwzChunk = chunk
}
return chunk
}
const reader = rb.getReader()
const decoder = new TextDecoder()
const encoder = new TextEncoder()
const stream = new ReadableStream({
async start(controller) {
while (true) {
const { done, value } = await reader.read()
if (done) {
return controller.close()
}
const chunkStr = handChunkData(decoder.decode(value))
if (bwzChunk !== '') {
continue
}
chunkStr.split('\n').forEach((line) => {
if (line.length < 6) {
return
}
line = line.slice(6)
if (line !== '[DONE]') {
const originReq = JSON.parse(line)
if (originReq.action !== 'success') {
return controller.error(new Error('Error: originReq stream chunk is not success'))
}
if (originReq.message) {
previousText += originReq.message
if (returnStream) {
controller.enqueue(
encoder.encode(`data: ${JSON.stringify(newChatCompletionChunkWithModel(originReq.message, originReq.model))}\n\n`)
)
}
}
} else {
if (returnStream) {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(newStopChunkWithModel('stop', model))}\n\n`))
} else {
controller.enqueue(encoder.encode(JSON.stringify(newChatCompletionWithModel(previousText, model))))
}
return controller.close()
}
})
continue
}
},
})
return new Response(stream, {
headers: {
'Content-Type': returnStream ? 'text/event-stream' : 'application/json',
},
})
}
function messagesPrepare(messages) {
let content = ''
for (const message of messages) {
let role = message.role === 'system' ? 'user' : message.role
if (['user', 'assistant'].includes(role)) {
const contentStr = Array.isArray(message.content)
? message.content
.filter((item) => item.text)
.map((item) => item.text)
.join('') || ''
: message.content
content += `${role}:${contentStr};\r\n`
}
}
return content
}
async function requestToken() {
const response = await fetch(`https://duckduckgo.com/duckchat/v1/status`, {
method: 'GET',
headers: {
...config.FAKE_HEADERS,
'x-vqd-accept': '1',
},
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
const token = response.headers.get('x-vqd-4')
return token
}
function convertModel(inputModel) {
let model
switch (inputModel.toLowerCase()) {
case 'claude-3-haiku':
model = 'claude-3-haiku-20240307'
break
case 'llama-3.1-70b':
model = 'meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo'
break
case 'mixtral-8x7b':
model = 'mistralai/Mixtral-8x7B-Instruct-v0.1'
break
}
return model || 'gpt-4o-mini'
}
function newChatCompletionChunkWithModel(text, model) {
return {
id: 'chatcmpl-QXlha2FBbmROaXhpZUFyZUF3ZXNvbWUK',
object: 'chat.completion.chunk',
created: 0,
model,
choices: [
{
index: 0,
delta: {
content: text,
},
finish_reason: null,
},
],
}
}
function newStopChunkWithModel(reason, model) {
return {
id: 'chatcmpl-QXlha2FBbmROaXhpZUFyZUF3ZXNvbWUK',
object: 'chat.completion.chunk',
created: 0,
model,
choices: [
{
index: 0,
finish_reason: reason,
},
],
}
}
function newChatCompletionWithModel(text, model) {
return {
id: 'chatcmpl-QXlha2FBbmROaXhpZUFyZUF3ZXNvbWUK',
object: 'chat.completion',
created: 0,
model,
usage: {
prompt_tokens: 0,
completion_tokens: 0,
total_tokens: 0,
},
choices: [
{
message: {
content: text,
role: 'assistant',
},
index: 0,
},
],
}
}
// Serverless Service
;(async () => {
//For Cloudflare Workers
if (typeof addEventListener === 'function') return
// For Nodejs
const ittyServer = createServerAdapter(router.fetch)
console.log(`Listening on http://localhost:${process.env.PORT || 8787}`)
const httpServer = createServer(ittyServer)
httpServer.listen(8787)
})()
// export default router
|