Richardlsr commited on
Commit
37224fb
·
verified ·
1 Parent(s): 01c8bd3

Create server.js

Browse files
Files changed (1) hide show
  1. server.js +381 -0
server.js ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from 'express';
2
+ import { fal } from '@fal-ai/client';
3
+
4
+ // 从环境变量读取 Fal AI API Key 和自定义 API Key
5
+ const FAL_KEY = process.env.FAL_KEY;
6
+ const API_KEY = process.env.API_KEY; // 添加自定义 API Key 环境变量
7
+
8
+ if (!FAL_KEY) {
9
+ console.error("Error: FAL_KEY environment variable is not set.");
10
+ process.exit(1);
11
+ }
12
+
13
+ if (!API_KEY) {
14
+ console.error("Error: API_KEY environment variable is not set.");
15
+ process.exit(1);
16
+ }
17
+
18
+ // 配置 fal 客户端
19
+ fal.config({
20
+ credentials: FAL_KEY,
21
+ });
22
+
23
+ const app = express();
24
+ app.use(express.json({ limit: '50mb' }));
25
+ app.use(express.urlencoded({ extended: true, limit: '50mb' }));
26
+
27
+ const PORT = process.env.PORT || 3000;
28
+
29
+ // API Key 鉴权中间件
30
+ const apiKeyAuth = (req, res, next) => {
31
+ const authHeader = req.headers['authorization'];
32
+
33
+ if (!authHeader) {
34
+ console.warn('Unauthorized: No Authorization header provided');
35
+ return res.status(401).json({ error: 'Unauthorized: No API Key provided' });
36
+ }
37
+
38
+ const authParts = authHeader.split(' ');
39
+ if (authParts.length !== 2 || authParts[0].toLowerCase() !== 'bearer') {
40
+ console.warn('Unauthorized: Invalid Authorization header format');
41
+ return res.status(401).json({ error: 'Unauthorized: Invalid Authorization header format' });
42
+ }
43
+
44
+ const providedKey = authParts[1];
45
+ if (providedKey !== API_KEY) {
46
+ console.warn('Unauthorized: Invalid API Key');
47
+ return res.status(401).json({ error: 'Unauthorized: Invalid API Key' });
48
+ }
49
+
50
+ next();
51
+ };
52
+
53
+ // 应用 API Key 鉴权中间件到所有 API 路由
54
+ app.use(['/v1/models', '/v1/chat/completions'], apiKeyAuth);
55
+
56
+ // === 全局定义限制 ===
57
+ const PROMPT_LIMIT = 4800;
58
+ const SYSTEM_PROMPT_LIMIT = 4800;
59
+ // === 限制定义结束 ===
60
+
61
+ // 定义 fal-ai/any-llm 支持的模型列表
62
+ const FAL_SUPPORTED_MODELS = [
63
+ "anthropic/claude-3.7-sonnet",
64
+ "anthropic/claude-3.5-sonnet",
65
+ "anthropic/claude-3-5-haiku",
66
+ "anthropic/claude-3-haiku",
67
+ "google/gemini-pro-1.5",
68
+ "google/gemini-flash-1.5",
69
+ "google/gemini-flash-1.5-8b",
70
+ "google/gemini-2.0-flash-001",
71
+ "meta-llama/llama-3.2-1b-instruct",
72
+ "meta-llama/llama-3.2-3b-instruct",
73
+ "meta-llama/llama-3.1-8b-instruct",
74
+ "meta-llama/llama-3.1-70b-instruct",
75
+ "openai/gpt-4o-mini",
76
+ "openai/gpt-4o",
77
+ "deepseek/deepseek-r1",
78
+ "meta-llama/llama-4-maverick",
79
+ "meta-llama/llama-4-scout"
80
+ ];
81
+
82
+ // Helper function to get owner from model ID
83
+ const getOwner = (modelId) => {
84
+ if (modelId && modelId.includes('/')) {
85
+ return modelId.split('/')[0];
86
+ }
87
+ return 'fal-ai';
88
+ }
89
+
90
+ // GET /v1/models endpoint
91
+ app.get('/v1/models', (req, res) => {
92
+ console.log("Received request for GET /v1/models");
93
+ try {
94
+ const modelsData = FAL_SUPPORTED_MODELS.map(modelId => ({
95
+ id: modelId, object: "model", created: 1700000000, owned_by: getOwner(modelId)
96
+ }));
97
+ res.json({ object: "list", data: modelsData });
98
+ console.log("Successfully returned model list.");
99
+ } catch (error) {
100
+ console.error("Error processing GET /v1/models:", error);
101
+ res.status(500).json({ error: "Failed to retrieve model list." });
102
+ }
103
+ });
104
+
105
+ // === 修改后的 convertMessagesToFalPrompt 函数 (System置顶 + 分隔符 + 对话历史Recency) ===
106
+ function convertMessagesToFalPrompt(messages) {
107
+ let fixed_system_prompt_content = "";
108
+ const conversation_message_blocks = [];
109
+ console.log(`Original messages count: ${messages.length}`);
110
+
111
+ // 1. 分离 System 消息,格式化 User/Assistant 消息
112
+ for (const message of messages) {
113
+ let content = (message.content === null || message.content === undefined) ? "" : String(message.content);
114
+ switch (message.role) {
115
+ case 'system':
116
+ fixed_system_prompt_content += `System: ${content}\n\n`;
117
+ break;
118
+ case 'user':
119
+ conversation_message_blocks.push(`Human: ${content}\n\n`);
120
+ break;
121
+ case 'assistant':
122
+ conversation_message_blocks.push(`Assistant: ${content}\n\n`);
123
+ break;
124
+ default:
125
+ console.warn(`Unsupported role: ${message.role}`);
126
+ continue;
127
+ }
128
+ }
129
+
130
+ // 2. 截断合并后的 system 消息(如果超长)
131
+ if (fixed_system_prompt_content.length > SYSTEM_PROMPT_LIMIT) {
132
+ const originalLength = fixed_system_prompt_content.length;
133
+ fixed_system_prompt_content = fixed_system_prompt_content.substring(0, SYSTEM_PROMPT_LIMIT);
134
+ console.warn(`Combined system messages truncated from ${originalLength} to ${SYSTEM_PROMPT_LIMIT}`);
135
+ }
136
+ // 清理末尾可能多余的空白,以便后续判断和拼接
137
+ fixed_system_prompt_content = fixed_system_prompt_content.trim();
138
+
139
+
140
+ // 3. 计算 system_prompt 中留给对话历史的剩余空间
141
+ // 注意:这里计算时要考虑��隔符可能占用的长度,但分隔符只在需要时添加
142
+ // 因此先计算不含分隔符的剩余空间
143
+ let space_occupied_by_fixed_system = 0;
144
+ if (fixed_system_prompt_content.length > 0) {
145
+ // 如果固定内容不为空,计算其长度 + 后面可能的分隔符的长度(如果需要)
146
+ // 暂时只计算内容长度,分隔符在组合时再考虑
147
+ space_occupied_by_fixed_system = fixed_system_prompt_content.length + 4; // 预留 \n\n...\n\n 的长度
148
+ }
149
+ const remaining_system_limit = Math.max(0, SYSTEM_PROMPT_LIMIT - space_occupied_by_fixed_system);
150
+ console.log(`Trimmed fixed system prompt length: ${fixed_system_prompt_content.length}. Approx remaining system history limit: ${remaining_system_limit}`);
151
+
152
+
153
+ // 4. 反向填充 User/Assistant 对话历史
154
+ const prompt_history_blocks = [];
155
+ const system_prompt_history_blocks = [];
156
+ let current_prompt_length = 0;
157
+ let current_system_history_length = 0;
158
+ let promptFull = false;
159
+ let systemHistoryFull = (remaining_system_limit <= 0);
160
+
161
+ console.log(`Processing ${conversation_message_blocks.length} user/assistant messages for recency filling.`);
162
+ for (let i = conversation_message_blocks.length - 1; i >= 0; i--) {
163
+ const message_block = conversation_message_blocks[i];
164
+ const block_length = message_block.length;
165
+
166
+ if (promptFull && systemHistoryFull) {
167
+ console.log(`Both prompt and system history slots full. Omitting older messages from index ${i}.`);
168
+ break;
169
+ }
170
+
171
+ // 优先尝试放入 prompt
172
+ if (!promptFull) {
173
+ if (current_prompt_length + block_length <= PROMPT_LIMIT) {
174
+ prompt_history_blocks.unshift(message_block);
175
+ current_prompt_length += block_length;
176
+ continue;
177
+ } else {
178
+ promptFull = true;
179
+ console.log(`Prompt limit (${PROMPT_LIMIT}) reached. Trying system history slot.`);
180
+ }
181
+ }
182
+
183
+ // 如果 prompt 满了,尝试放入 system_prompt 的剩余空间
184
+ if (!systemHistoryFull) {
185
+ if (current_system_history_length + block_length <= remaining_system_limit) {
186
+ system_prompt_history_blocks.unshift(message_block);
187
+ current_system_history_length += block_length;
188
+ continue;
189
+ } else {
190
+ systemHistoryFull = true;
191
+ console.log(`System history limit (${remaining_system_limit}) reached.`);
192
+ }
193
+ }
194
+ }
195
+
196
+ // 5. *** 组合最终的 prompt 和 system_prompt (包含分隔符逻辑) ***
197
+ const system_prompt_history_content = system_prompt_history_blocks.join('').trim();
198
+ const final_prompt = prompt_history_blocks.join('').trim();
199
+
200
+ // 定义分隔符
201
+ const SEPARATOR = "\n\n-------下面是比较早之前的对话内容-----\n\n";
202
+
203
+ let final_system_prompt = "";
204
+
205
+ // 检查各部分是否有内容 (使用 trim 后的固定部分)
206
+ const hasFixedSystem = fixed_system_prompt_content.length > 0;
207
+ const hasSystemHistory = system_prompt_history_content.length > 0;
208
+
209
+ if (hasFixedSystem && hasSystemHistory) {
210
+ // 两部分都有,用分隔符连接
211
+ final_system_prompt = fixed_system_prompt_content + SEPARATOR + system_prompt_history_content;
212
+ console.log("Combining fixed system prompt and history with separator.");
213
+ } else if (hasFixedSystem) {
214
+ // 只有固定部分
215
+ final_system_prompt = fixed_system_prompt_content;
216
+ console.log("Using only fixed system prompt.");
217
+ } else if (hasSystemHistory) {
218
+ // 只有历史部分 (固定部分为空)
219
+ final_system_prompt = system_prompt_history_content;
220
+ console.log("Using only history in system prompt slot.");
221
+ }
222
+ // 如果两部分都为空,final_system_prompt 保持空字符串 ""
223
+
224
+ // 6. 返回结果
225
+ const result = {
226
+ system_prompt: final_system_prompt, // 最终结果不需要再 trim
227
+ prompt: final_prompt // final_prompt 在组合前已 trim
228
+ };
229
+
230
+ console.log(`Final system_prompt length (Sys+Separator+Hist): ${result.system_prompt.length}`);
231
+ console.log(`Final prompt length (Hist): ${result.prompt.length}`);
232
+
233
+ return result;
234
+ }
235
+ // === convertMessagesToFalPrompt 函数结束 ===
236
+
237
+
238
+ // POST /v1/chat/completions endpoint (保持不变)
239
+ app.post('/v1/chat/completions', async (req, res) => {
240
+ const { model, messages, stream = false, reasoning = false, ...restOpenAIParams } = req.body;
241
+
242
+ console.log(`Received chat completion request for model: ${model}, stream: ${stream}`);
243
+
244
+ if (!FAL_SUPPORTED_MODELS.includes(model)) {
245
+ console.warn(`Warning: Requested model '${model}' is not in the explicitly supported list.`);
246
+ }
247
+ if (!model || !messages || !Array.isArray(messages) || messages.length === 0) {
248
+ console.error("Invalid request parameters:", { model, messages: Array.isArray(messages) ? messages.length : typeof messages });
249
+ return res.status(400).json({ error: 'Missing or invalid parameters: model and messages array are required.' });
250
+ }
251
+
252
+ try {
253
+ // *** 使用更新后的转换函数 ***
254
+ const { prompt, system_prompt } = convertMessagesToFalPrompt(messages);
255
+
256
+ const falInput = {
257
+ model: model,
258
+ prompt: prompt,
259
+ ...(system_prompt && { system_prompt: system_prompt }),
260
+ reasoning: !!reasoning,
261
+ };
262
+ console.log("Fal Input:", JSON.stringify(falInput, null, 2));
263
+ console.log("Forwarding request to fal-ai with system-priority + separator + recency input:");
264
+ console.log("System Prompt Length:", system_prompt?.length || 0);
265
+ console.log("Prompt Length:", prompt?.length || 0);
266
+ // 调试时取消注释可以查看具体内容
267
+ console.log("--- System Prompt Start ---");
268
+ console.log(system_prompt);
269
+ console.log("--- System Prompt End ---");
270
+ console.log("--- Prompt Start ---");
271
+ console.log(prompt);
272
+ console.log("--- Prompt End ---");
273
+
274
+
275
+ // --- 流式/非流式处理逻辑 (保持不变) ---
276
+ if (stream) {
277
+ // ... 流式代码 ...
278
+ res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
279
+ res.setHeader('Cache-Control', 'no-cache');
280
+ res.setHeader('Connection', 'keep-alive');
281
+ res.setHeader('Access-Control-Allow-Origin', '*');
282
+ res.flushHeaders();
283
+
284
+ let previousOutput = '';
285
+
286
+ const falStream = await fal.stream("fal-ai/any-llm", { input: falInput });
287
+
288
+ try {
289
+ for await (const event of falStream) {
290
+ const currentOutput = (event && typeof event.output === 'string') ? event.output : '';
291
+ const isPartial = (event && typeof event.partial === 'boolean') ? event.partial : true;
292
+ const errorInfo = (event && event.error) ? event.error : null;
293
+
294
+ if (errorInfo) {
295
+ console.error("Error received in fal stream event:", errorInfo);
296
+ const errorChunk = { id: `chatcmpl-${Date.now()}-error`, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model: model, choices: [{ index: 0, delta: {}, finish_reason: "error", message: { role: 'assistant', content: `Fal Stream Error: ${JSON.stringify(errorInfo)}` } }] };
297
+ res.write(`data: ${JSON.stringify(errorChunk)}\n\n`);
298
+ break;
299
+ }
300
+
301
+ let deltaContent = '';
302
+ if (currentOutput.startsWith(previousOutput)) {
303
+ deltaContent = currentOutput.substring(previousOutput.length);
304
+ } else if (currentOutput.length > 0) {
305
+ console.warn("Fal stream output mismatch detected. Sending full current output as delta.", { previousLength: previousOutput.length, currentLength: currentOutput.length });
306
+ deltaContent = currentOutput;
307
+ previousOutput = '';
308
+ }
309
+ previousOutput = currentOutput;
310
+
311
+ if (deltaContent || !isPartial) {
312
+ const openAIChunk = { id: `chatcmpl-${Date.now()}`, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model: model, choices: [{ index: 0, delta: { content: deltaContent }, finish_reason: isPartial === false ? "stop" : null }] };
313
+ res.write(`data: ${JSON.stringify(openAIChunk)}\n\n`);
314
+ }
315
+ }
316
+ res.write(`data: [DONE]\n\n`);
317
+ res.end();
318
+ console.log("Stream finished.");
319
+
320
+ } catch (streamError) {
321
+ console.error('Error during fal stream processing loop:', streamError);
322
+ try {
323
+ const errorDetails = (streamError instanceof Error) ? streamError.message : JSON.stringify(streamError);
324
+ res.write(`data: ${JSON.stringify({ error: { message: "Stream processing error", type: "proxy_error", details: errorDetails } })}\n\n`);
325
+ res.write(`data: [DONE]\n\n`);
326
+ res.end();
327
+ } catch (finalError) {
328
+ console.error('Error sending stream error message to client:', finalError);
329
+ if (!res.writableEnded) { res.end(); }
330
+ }
331
+ }
332
+ } else {
333
+ // --- 非流式处理 (保持不变) ---
334
+ console.log("Executing non-stream request...");
335
+ const result = await fal.subscribe("fal-ai/any-llm", { input: falInput, logs: true });
336
+ console.log("Received non-stream result from fal-ai:", JSON.stringify(result, null, 2));
337
+
338
+ if (result && result.error) {
339
+ console.error("Fal-ai returned an error in non-stream mode:", result.error);
340
+ return res.status(500).json({ object: "error", message: `Fal-ai error: ${JSON.stringify(result.error)}`, type: "fal_ai_error", param: null, code: null });
341
+ }
342
+
343
+ const openAIResponse = {
344
+ id: `chatcmpl-${result.requestId || Date.now()}`, object: "chat.completion", created: Math.floor(Date.now() / 1000), model: model,
345
+ choices: [{ index: 0, message: { role: "assistant", content: result.output || "" }, finish_reason: "stop" }],
346
+ usage: { prompt_tokens: null, completion_tokens: null, total_tokens: null }, system_fingerprint: null,
347
+ ...(result.reasoning && { fal_reasoning: result.reasoning }),
348
+ };
349
+ res.json(openAIResponse);
350
+ console.log("Returned non-stream response.");
351
+ }
352
+
353
+ } catch (error) {
354
+ console.error('Unhandled error in /v1/chat/completions:', error);
355
+ if (!res.headersSent) {
356
+ const errorMessage = (error instanceof Error) ? error.message : JSON.stringify(error);
357
+ res.status(500).json({ error: 'Internal Server Error in Proxy', details: errorMessage });
358
+ } else if (!res.writableEnded) {
359
+ console.error("Headers already sent, ending response.");
360
+ res.end();
361
+ }
362
+ }
363
+ });
364
+
365
+ // 启动服务器 (更新启动信息)
366
+ app.listen(PORT, () => {
367
+ console.log(`===================================================`);
368
+ console.log(` Fal OpenAI Proxy Server (System Top + Separator + Recency)`);
369
+ console.log(` Listening on port: ${PORT}`);
370
+ console.log(` Using Limits: System Prompt=${SYSTEM_PROMPT_LIMIT}, Prompt=${PROMPT_LIMIT}`);
371
+ console.log(` Fal AI Key Loaded: ${FAL_KEY ? 'Yes' : 'No'}`);
372
+ console.log(` API Key Auth Enabled: ${API_KEY ? 'Yes' : 'No'}`);
373
+ console.log(` Chat Completions Endpoint: POST http://localhost:${PORT}/v1/chat/completions`);
374
+ console.log(` Models Endpoint: GET http://localhost:${PORT}/v1/models`);
375
+ console.log(`===================================================`);
376
+ });
377
+
378
+ // 根路径响应 (更新信息)
379
+ app.get('/', (req, res) => {
380
+ res.send('Fal OpenAI Proxy (System Top + Separator + Recency Strategy) is running.');
381
+ });