-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
346 lines (302 loc) · 11 KB
/
index.js
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
import express from 'express';
import fetch from 'node-fetch';
import dotenv from 'dotenv';
import cors from 'cors';
import createError from 'http-errors';
dotenv.config();
const VERSION = '1.1.0';
// ===== 常量定义 =====
// 开放端口
const PORT = process.env.PORT || 3000;
// API 密钥
const API_KEYS = new Set(process.env.API_KEYS ? process.env.API_KEYS.split(',') : []);
// DEBUG 模式
const DEBUG_MODE = process.env.DEBUG_MODE === 'true';
// 自定义前缀
const PATH_PREFIX = process.env.PATH_PREFIX?'/'+process.env.PATH_PREFIX:'';
// 模型映射
const MODELS = {
'gpt-4o-mini': 'gpt-4o-mini',
'claude-3-haiku-20240307': 'claude-3-haiku-20240307',
'meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo': 'meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo',
'mistralai/Mixtral-8x7B-Instruct-v0.1': 'mistralai/Mixtral-8x7B-Instruct-v0.1'
};
// DuckDuckGo 端点
const DDGAPI_ENDPOINTS = {
STATUS: 'https://duckduckgo.com/duckchat/v1/status', // 获取VQD令牌
CHAT: 'https://duckduckgo.com/duckchat/v1/chat' // 聊天API端点
};
// 用于向 DuckDuckGo 发送请求的默认头部
const DEFAULT_HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:129.0) Gecko/20100101 Firefox/129.0',
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br, zstd',
'Referer': 'https://duckduckgo.com/',
'Cache-Control': 'no-store',
'x-vqd-accept': '1',
'Connection': 'keep-alive',
'Cookie': 'dcm=3',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-origin',
'Priority': 'u=4',
'Pragma': 'no-cache',
'TE': 'trailers'
};
// ===== 工具函数 =====
// 获取当前时间
function getFormattedTime() {
return new Date().toISOString();
}
// 错误响应模板
function formatErrorResponse(status, message, type = 'api_error') {
return {
error: {
message: message,
type: type,
code: status,
param: null,
}
};
}
// 格式化为 OpenAI 标准响应 [非流式]
function formatOpenAIResponse(assistantMessage, modelName) {
return {
id: 'chatcmpl-' + Math.random().toString(36).slice(2, 11),
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
model: modelName,
choices: [{
index: 0,
message: {role: 'assistant', content: assistantMessage},
finish_reason: 'stop'
}]
};
}
// 格式化为 OpenAI 标准响应 [流式]
function formatStreamingChunk(messageContent, isLastChunk = false, modelName) {
const chunk = {
id: 'chatcmpl-' + Math.random().toString(36).slice(2, 11),
object: 'chat.completion.chunk',
created: Math.floor(Date.now() / 1000),
model: modelName,
choices: [{
index: 0,
delta: isLastChunk ? {} : {content: messageContent},
finish_reason: isLastChunk ? 'stop' : null
}]
};
return `data: ${JSON.stringify(chunk)}\n\n`;
}
// 获取DuckDuckGo VQD令牌
async function getDuckVQDToken(requestHeaders) {
const statusResponse = await fetch(DDGAPI_ENDPOINTS.STATUS, {headers: requestHeaders});
if (!statusResponse.ok) {
throw createError(500, `DuckDuckGo status API failed with ${statusResponse.status}`);
}
return statusResponse.headers.get('x-vqd-4');
}
// 将客户端发送的消息数组拼接为 DuckDuckGo 能处理的消息格式
function processMessages(messages) {
const validRoles = new Set(['user', 'assistant', 'system']);
const results = [];
for (const msg of messages) {
if (msg?.content && validRoles.has(msg.role)) {
const content = Array.isArray(msg.content)
? msg.content.reduce((acc, item) => item?.text ? acc + item.text : acc, '')
: msg.content;
if (content.trim()) {
results.push(`${msg.role === 'system' ? 'user' : msg.role}: ${content}`);
}
}
}
return results.join('\n');
}
// 统一响应处理函数
async function handleResponse(response, options = {}) {
const {stream = false, res = null, modelName = null} = options;
if (stream && res) {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
for await (const chunk of response.body) {
const lines = chunk.toString().split('\n');
for (const line of lines) {
if (!line.trim() || !line.startsWith('data: ')) continue;
const content = line.slice(6);
if (content === '[DONE]') {
res.write(formatStreamingChunk('', true, modelName));
return res.end();
}
try {
const data = JSON.parse(content);
// 处理错误响应
if (data.action === 'error') {
const errorResponse = formatErrorResponse(data.status, `DuckDuckGo Error: ${data.type}`, "duck_error");
res.write(`data: ${JSON.stringify(errorResponse)}\n\n`);
return res.end();
}
if (data.message) {
res.write(formatStreamingChunk(data.message, false, modelName));
}
} catch (error) {
if (DEBUG_MODE) {
console.error(`[${getFormattedTime()}] Error:`, error);
}
}
}
}
} else {
const responseText = await response.text();
const lines = responseText.split('\n');
let fullMessage = '';
let errorFound = false;
for (const line of lines) {
if (!line.trim() || !line.includes('data: ')) continue;
try {
const jsonStr = line.slice(6);
if (jsonStr === '[DONE]') continue;
const data = JSON.parse(jsonStr);
// 处理错误响应
if (data.action === 'error') {
errorFound = true;
throw createError(data.status, `DuckDuckGo Error: ${data.type}`);
}
if (data.message) {
fullMessage += data.message; // 累积所有消息片段
}
} catch (e) {
if (errorFound) throw e;
}
}
return fullMessage || responseText; // 返回完整消息
}
}
// 发送聊天消息到DuckDuckGo
async function sendDuckChatMessage(messages, modelName) {
if (!messages?.length) {
throw createError(400, "Messages array is required and cannot be empty");
}
const actualModelName = MODELS[modelName];
if (!actualModelName) {
throw createError(400, `Invalid model name: ${modelName}`);
}
try {
const headers = {
...DEFAULT_HEADERS,
'Content-Type': 'application/json',
'Accept': 'text/event-stream',
'x-vqd-4': await getDuckVQDToken(DEFAULT_HEADERS)
};
const content = processMessages(messages);
return await fetch(DDGAPI_ENDPOINTS.CHAT, {
method: 'POST',
headers,
body: JSON.stringify({
model: actualModelName,
messages: [{
role: 'user',
content
}]
})
});
} catch (error) {
if (!error.status) {
throw createError(500, `DuckDuckGo Error: ${error.message}`);
}
throw error;
}
}
// API密钥验证中间件
const validateApiKey = (req, res, next) => {
if (API_KEYS.size === 0) return next();
const authHeader = req.headers.authorization;
if (!authHeader) {
if (DEBUG_MODE) {
console.error(`[${getFormattedTime()}] Error 401: Missing Authorization header`);
}
return res.status(401).json(formatErrorResponse(401, "Missing Authorization header", "auth_error"));
}
const [bearer, apiKey] = authHeader.split(' ');
if (bearer !== 'Bearer' || !apiKey || !API_KEYS.has(apiKey)) {
if (DEBUG_MODE) {
console.error(`[${getFormattedTime()}] Error 401: Invalid API key`);
}
return res.status(401).json(formatErrorResponse(401, "Invalid API key", "auth_error"));
}
next();
};
// Express 应用初始化
const app = express();
app.use(express.json());
//Cors 请求头
app.use(cors({
origin: '*',
methods: ['GET', 'POST', 'OPTIONS'],
allowedHeaders: '*', // 接受所有请求头
exposedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
maxAge: 86400,
preflightContinue: false,
}));
app.options('*', cors());
// v1/models 路由
app.get(PATH_PREFIX+'/v1/models', validateApiKey, (req, res) => {
res.json({
object: "list",
data: Object.keys(MODELS).map(modelName => ({
id: modelName,
object: "model",
owned_by: "duckduckgo",
}))
});
});
// v1/chat/completions 路由
app.post(PATH_PREFIX+'/v1/chat/completions', validateApiKey, async (req, res, next) => {
const {messages, model, stream = false} = req.body;
if (!messages?.length) {
if (DEBUG_MODE) {
console.error(`[${getFormattedTime()}] Error 400: Messages is required and must be a non-empty array`);
}
return res.status(400).json(formatErrorResponse(400, "Messages is required and must be a non-empty array", "invalid_request_error"));
}
if (!model || !MODELS.hasOwnProperty(model)) {
const errorMsg = `Please select the correct model: ${Object.keys(MODELS).join(', ')}`;
if (DEBUG_MODE) {
console.error(`[${getFormattedTime()}] Error 400: ${errorMsg}`);
}
return res.status(400).json(formatErrorResponse(400, errorMsg, "invalid_request_error"));
}
try {
const chatResponse = await sendDuckChatMessage(messages, model);
if (stream) {
await handleResponse(chatResponse, {stream: true, res, modelName: model});
} else {
const response = await handleResponse(chatResponse);
res.json(formatOpenAIResponse(response, model));
}
} catch (error) {
next(error);
}
});
// 错误处理中间件
app.use((err, req, res, next) => {
const status = err.status || 500;
const message = err.message || 'Internal Server Error';
if (DEBUG_MODE) {
console.error(`[${getFormattedTime()}] Error ${status}: ${message}`);
}
res.status(status).json(formatErrorResponse(status, message));
});
// 导出 app 供 Vercel 使用
export default app;
// 如果不是在 Vercel 环境下运行,则启动独立服务器
if (process.env.VERCEL !== '1') {
app.listen(PORT, () => {
console.log(`[${getFormattedTime()}] DDG2API ${VERSION} is running at port ${PORT}`);
if (DEBUG_MODE) {
console.log(`[${getFormattedTime()}] Debug mode is enabled`);
}
});
}