ezeinet commited on
Commit
3749715
·
verified ·
1 Parent(s): 263fe63

Update server.js

Browse files
Files changed (1) hide show
  1. server.js +212 -319
server.js CHANGED
@@ -1,48 +1,44 @@
1
  import express from 'express';
2
  import { fal } from '@fal-ai/client';
3
 
4
- // --- Express App Setup ---
5
- const app = express();
6
- app.use(express.json({ limit: '50mb' }));
7
- app.use(express.urlencoded({ extended: true, limit: '50mb' }));
8
-
9
- const PORT = process.env.PORT || 3000;
10
-
11
- // 全局变量用于存储和管理当前请求的FAL key
12
- const requestContext = new Map();
13
-
14
- // === 全局定义限制 ===
15
- const PROMPT_LIMIT = 4800;
16
- const SYSTEM_PROMPT_LIMIT = 4800;
17
- // === 限制定义结束 ===
18
-
19
- // API Key 鉴权中间件
20
- const apiKeyAuth = (req, res, next) => {
21
- const authHeader = req.headers['authorization'];
22
-
23
- if (!authHeader) {
24
- console.warn('未提供 Authorization 头');
25
- return res.status(401).json({ error: '未提供 API Key' });
26
- }
27
 
28
- const authParts = authHeader.split(' ');
29
- if (authParts.length !== 2 || authParts[0].toLowerCase() !== 'bearer') {
30
- console.warn('Authorization 头格式无效');
31
- return res.status(401).json({ error: 'Authorization 头格式无效' });
32
- }
33
 
34
- const falKey = authParts[1];
35
- if (!falKey) {
36
- console.warn('未提供有效的 FAL API Key');
37
- return res.status(401).json({ error: '未提供有效的 FAL API Key' });
38
- }
 
 
 
 
 
 
 
 
 
 
39
 
40
- // 将FAL key存储在请求上下文中
41
- requestContext.set(req, falKey);
42
- next();
43
- };
44
 
45
- app.use(['/v1/models', '/v1/chat/completions'], apiKeyAuth);
 
 
46
 
47
  // NOTE: We will configure fal client per request now, so initial global config is removed.
48
 
@@ -84,6 +80,23 @@ function getNextKey() {
84
  return null; // All keys are currently failed and within cooldown
85
  }
86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  /**
88
  * Marks a specific key as failed.
89
  * @param {object} keyInfo - The key info object to mark as failed.
@@ -97,25 +110,13 @@ function markKeyFailed(keyInfo) {
97
  }
98
  }
99
 
 
100
  /**
101
  * Determines if an error likely indicates an API key issue (auth, quota, etc.).
102
  * This needs refinement based on actual errors from fal.ai.
103
  * @param {Error} error - The error object caught from the fal client.
104
  * @returns {boolean} - True if the error suggests a key failure, false otherwise.
105
  */
106
- function isKeyRelatedError(error) {
107
- const errorMessage = error?.message?.toLowerCase() || '';
108
- const errorStatus = error?.status; // Assuming the error object might have a status property
109
-
110
- // Check for common indicators of key issues
111
- if (errorStatus === 401 || errorStatus === 403 || // Unauthorized, Forbidden
112
- errorMessage.includes('authentication failed') ||
113
- errorMessage.includes('invalid api key') ||
114
- errorMessage.includes('permission denied')) {
115
- return true;
116
- }
117
- if (errorStatus === 429 || // Too Many Requests (Rate Limit / Quota)
118
- errorMessage.includes('rate limit exceeded') ||
119
  errorMessage.includes('quota exceeded')) {
120
  return true;
121
  }
@@ -124,6 +125,38 @@ function isKeyRelatedError(error) {
124
  return false;
125
  }
126
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  // 定义 fal-ai/any-llm 支持的模型列表 (Remains the same)
128
  const FAL_SUPPORTED_MODELS = [
129
  "anthropic/claude-3.7-sonnet",
@@ -156,337 +189,197 @@ const getOwner = (modelId) => {
156
  // GET /v1/models endpoint (Remains the same)
157
  app.get('/v1/models', (req, res) => {
158
  console.log("Received request for GET /v1/models");
159
- try {
160
- const modelsData = FAL_SUPPORTED_MODELS.map(modelId => ({
161
- id: modelId, object: "model", created: 1700000000, owned_by: getOwner(modelId)
162
- }));
163
- res.json({ object: "list", data: modelsData });
164
- console.log("Successfully returned model list.");
165
- } catch (error) {
166
- console.error("Error processing GET /v1/models:", error);
167
- res.status(500).json({ error: "Failed to retrieve model list." });
168
- }
169
- });
170
-
171
- // === convertMessagesToFalPrompt 函数 (Remains the same) ===
172
- function convertMessagesToFalPrompt(messages) {
173
- let fixed_system_prompt_content = "";
174
- const conversation_message_blocks = [];
175
- // console.log(`Original messages count: ${messages.length}`); // Less verbose logging
176
-
177
- // 1. 分离 System 消息,格式化 User/Assistant 消息
178
- for (const message of messages) {
179
- let content = (message.content === null || message.content === undefined) ? "" : String(message.content);
180
- switch (message.role) {
181
- case 'system':
182
- fixed_system_prompt_content += `System: ${content}\n\n`;
183
- break;
184
- case 'user':
185
- conversation_message_blocks.push(`Human: ${content}\n\n`);
186
- break;
187
- case 'assistant':
188
- conversation_message_blocks.push(`Assistant: ${content}\n\n`);
189
- break;
190
- default:
191
- console.warn(`Unsupported role: ${message.role}`);
192
- continue;
193
- }
194
- }
195
 
196
- // 2. 截断合并后的 system 消息(如果超长)
197
- if (fixed_system_prompt_content.length > SYSTEM_PROMPT_LIMIT) {
198
- const originalLength = fixed_system_prompt_content.length;
199
- fixed_system_prompt_content = fixed_system_prompt_content.substring(0, SYSTEM_PROMPT_LIMIT);
200
- console.warn(`Combined system messages truncated from ${originalLength} to ${SYSTEM_PROMPT_LIMIT}`);
201
- }
202
- fixed_system_prompt_content = fixed_system_prompt_content.trim();
203
 
 
 
 
 
 
 
 
204
 
205
- // 3. 计算 system_prompt 中留给对话历史的剩余空间
206
- let space_occupied_by_fixed_system = 0;
207
- if (fixed_system_prompt_content.length > 0) {
208
- space_occupied_by_fixed_system = fixed_system_prompt_content.length + 4; // 预留 \n\n...\n\n 的长度
209
- }
210
- const remaining_system_limit = Math.max(0, SYSTEM_PROMPT_LIMIT - space_occupied_by_fixed_system);
211
- // console.log(`Trimmed fixed system prompt length: ${fixed_system_prompt_content.length}. Approx remaining system history limit: ${remaining_system_limit}`);
212
-
213
-
214
- // 4. 反向填充 User/Assistant 对话历史
215
- const prompt_history_blocks = [];
216
- const system_prompt_history_blocks = [];
217
- let current_prompt_length = 0;
218
- let current_system_history_length = 0;
219
- let promptFull = false;
220
- let systemHistoryFull = (remaining_system_limit <= 0);
221
-
222
- // console.log(`Processing ${conversation_message_blocks.length} user/assistant messages for recency filling.`);
223
- for (let i = conversation_message_blocks.length - 1; i >= 0; i--) {
224
- const message_block = conversation_message_blocks[i];
225
- const block_length = message_block.length;
226
-
227
- if (promptFull && systemHistoryFull) {
228
- // console.log(`Both prompt and system history slots full. Omitting older messages from index ${i}.`);
229
- break;
230
  }
231
 
232
- // 优先尝试放入 prompt
233
- if (!promptFull) {
234
- if (current_prompt_length + block_length <= PROMPT_LIMIT) {
235
- prompt_history_blocks.unshift(message_block);
236
- current_prompt_length += block_length;
237
- continue;
238
- } else {
239
- promptFull = true;
240
- // console.log(`Prompt limit (${PROMPT_LIMIT}) reached. Trying system history slot.`);
 
 
 
 
 
 
 
 
 
 
 
 
241
  }
242
- }
 
 
243
 
244
- // 如果 prompt 满了,尝试放入 system_prompt 的剩余空间
245
- if (!systemHistoryFull) {
246
- if (current_system_history_length + block_length <= remaining_system_limit) {
247
- system_prompt_history_blocks.unshift(message_block);
248
- current_system_history_length += block_length;
249
- continue;
250
  } else {
251
- systemHistoryFull = true;
252
- // console.log(`System history limit (${remaining_system_limit}) reached.`);
253
  }
254
- }
255
- }
256
 
257
- // 5. *** 组合最终的 prompt 和 system_prompt (包含分隔符逻辑) ***
258
- const system_prompt_history_content = system_prompt_history_blocks.join('').trim();
259
- const final_prompt = prompt_history_blocks.join('').trim();
260
 
261
- // 定义分隔符
262
- const SEPARATOR = "\n\n-------下面是比较早之前的对话内容-----\n\n";
263
 
264
- let final_system_prompt = "";
265
 
266
- const hasFixedSystem = fixed_system_prompt_content.length > 0;
267
- const hasSystemHistory = system_prompt_history_content.length > 0;
268
 
269
- if (hasFixedSystem && hasSystemHistory) {
270
- final_system_prompt = fixed_system_prompt_content + SEPARATOR + system_prompt_history_content;
271
- // console.log("Combining fixed system prompt and history with separator.");
272
- } else if (hasFixedSystem) {
273
- final_system_prompt = fixed_system_prompt_content;
274
- // console.log("Using only fixed system prompt.");
275
- } else if (hasSystemHistory) {
276
- final_system_prompt = system_prompt_history_content;
277
- // console.log("Using only history in system prompt slot.");
278
- }
279
 
280
- // 6. 返回结果
281
- const result = {
282
- system_prompt: final_system_prompt,
283
- prompt: final_prompt
284
- };
285
 
286
- console.log(`Final system_prompt length: ${result.system_prompt.length}, Final prompt length: ${result.prompt.length}`);
287
 
288
- return result;
289
- }
290
- // === convertMessagesToFalPrompt 函数结束 ===
291
 
292
- /**
293
- * 使用当前请求的FAL key配置fal客户端
294
- * @param {object} req - Express请求对象
295
- */
296
- function configureFalClientForRequest(req) {
297
- const falKey = requestContext.get(req);
298
- if (!falKey) {
299
- throw new Error('未找到FAL API Key');
300
  }
301
- fal.config({ credentials: falKey });
302
- }
303
 
304
- /**
305
- * Wraps the fal.ai API call with retry logic using available keys.
306
- * @param {'stream' | 'subscribe'} operation - The fal operation to perform.
307
- * @param {string} functionId - The fal function ID (e.g., "fal-ai/any-llm").
308
- * @param {object} params - The parameters for the fal function call (input, logs, etc.).
309
- * @returns {Promise<any>} - The result from the successful fal call (stream or subscription result).
310
- * @throws {Error} - Throws an error if all keys fail or a non-key-related error occurs.
311
- */
312
- async function tryFalCallWithFailover(req, operation, functionId, params) {
313
- try {
314
- configureFalClientForRequest(req);
315
-
316
- if (operation === 'stream') {
317
- const streamResult = await fal.stream(functionId, params);
318
- return streamResult;
319
- } else {
320
- const result = await fal.subscribe(functionId, params);
321
- return result;
322
- }
323
- } catch (error) {
324
- console.error('FAL API调用错误:', error.message || error);
325
- throw error;
326
- } finally {
327
- // 清理请求上下文
328
- requestContext.delete(req);
329
- }
330
  }
331
 
 
332
  // POST /v1/chat/completions endpoint (Modified to use tryFalCallWithFailover)
333
  app.post('/v1/chat/completions', async (req, res) => {
334
  const { model, messages, stream = false, reasoning = false, ...restOpenAIParams } = req.body;
335
 
336
- console.log(`收到chat completion请求,模型: ${model}, stream: ${stream}`);
 
337
 
338
  if (!FAL_SUPPORTED_MODELS.includes(model)) {
339
- console.warn(`警告: 请求的模型 '${model}' 不在明确支持的列表中。`);
340
  }
341
  if (!model || !messages || !Array.isArray(messages) || messages.length === 0) {
342
- console.error("无效的请求参数:", { model, messages: Array.isArray(messages) ? messages.length : typeof messages });
343
- return res.status(400).json({ error: '缺少或无效的参数: 需要model和messages数组。' });
344
- }
345
-
346
- try {
347
- const { prompt, system_prompt } = convertMessagesToFalPrompt(messages);
348
-
349
- const falInput = {
350
- model: model,
351
- prompt: prompt,
352
- ...(system_prompt && { system_prompt: system_prompt }),
353
- reasoning: !!reasoning,
354
- };
355
-
356
- console.log("Prepared Fal Input (lengths):", { system_prompt: system_prompt?.length, prompt: prompt?.length });
357
-
358
- if (stream) {
359
- res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
360
- res.setHeader('Cache-Control', 'no-cache');
361
- res.setHeader('Connection', 'keep-alive');
362
- res.setHeader('Access-Control-Allow-Origin', '*');
363
- res.flushHeaders();
364
-
365
- let previousOutput = '';
366
  let falStream;
367
 
368
  try {
369
- falStream = await tryFalCallWithFailover(req, 'stream', "fal-ai/any-llm", { input: falInput });
370
 
371
- for await (const event of falStream) {
372
  const currentOutput = (event && typeof event.output === 'string') ? event.output : '';
373
  const isPartial = (event && typeof event.partial === 'boolean') ? event.partial : true;
374
  const errorInfo = (event && event.error) ? event.error : null;
375
-
376
- if (errorInfo) {
377
- console.error("Error received *during* fal stream:", errorInfo);
378
- 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)}` } }] };
379
- res.write(`data: ${JSON.stringify(errorChunk)}\n\n`);
380
- break;
381
- }
382
-
383
- let deltaContent = '';
384
- if (currentOutput.startsWith(previousOutput)) {
385
- deltaContent = currentOutput.substring(previousOutput.length);
386
- } else if (currentOutput.length > 0) {
387
- console.warn("Fal stream output mismatch detected. Sending full current output as delta.", { previousLength: previousOutput.length, currentLength: currentOutput.length });
388
- deltaContent = currentOutput;
389
- previousOutput = '';
390
- }
391
- previousOutput = currentOutput;
392
-
393
- if (deltaContent || !isPartial) {
394
  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 }] };
395
  res.write(`data: ${JSON.stringify(openAIChunk)}\n\n`);
396
  }
397
- }
398
- res.write(`data: [DONE]\n\n`);
399
- res.end();
400
- console.log("Stream finished successfully.");
401
 
402
  } catch (streamError) {
403
- console.error('流处理期间出错:', streamError);
404
  if (!res.writableEnded) {
405
- try {
406
- const errorDetails = (streamError instanceof Error) ? streamError.message : JSON.stringify(streamError);
407
- const finalErrorChunk = { error: { message: "流失败", type: "proxy_error", details: errorDetails } };
408
- res.write(`data: ${JSON.stringify(finalErrorChunk)}\n\n`);
409
- res.write(`data: [DONE]\n\n`);
410
- res.end();
411
- } catch (finalError) {
412
- console.error('向客户端发送最终流错误消息时出错:', finalError);
413
- if (!res.writableEnded) { res.end(); }
414
- }
415
- }
416
  }
417
 
418
  } else { // Non-stream
419
- console.log("执行非流请求...");
420
- const result = await tryFalCallWithFailover(req, 'subscribe', "fal-ai/any-llm", { input: falInput, logs: true });
421
-
422
- console.log("Received non-stream result from fal-ai via failover wrapper.");
423
-
424
- if (result && result.error) {
425
- console.error("Fal-ai在非流模式下返回应用程序错误:", result.error);
426
- return res.status(500).json({
427
- object: "error",
428
- message: `Fal-ai应用程序错误: ${JSON.stringify(result.error)}`,
429
- type: "fal_ai_error",
430
- param: null,
431
- code: result.error.code || null
432
- });
433
- }
434
-
435
- const openAIResponse = {
436
- id: `chatcmpl-${result?.requestId || Date.now()}`,
437
- object: "chat.completion",
438
- created: Math.floor(Date.now() / 1000),
439
- model: model,
440
- choices: [{
441
- index: 0,
442
- message: {
443
- role: "assistant",
444
- content: result?.output || ""
445
- },
446
- finish_reason: "stop"
447
- }],
448
- usage: {
449
- prompt_tokens: null,
450
- completion_tokens: null,
451
- total_tokens: null
452
- },
453
- system_fingerprint: null,
454
- ...(result?.reasoning && { fal_reasoning: result.reasoning }),
455
- };
456
- res.json(openAIResponse);
457
- console.log("Returned non-stream response successfully.");
458
  }
459
 
460
  } catch (error) {
461
- console.error('在/v1/chat/completions中出现未处理的错误:', error);
462
  if (!res.headersSent) {
463
  const errorMessage = (error instanceof Error) ? error.message : JSON.stringify(error);
 
464
  res.status(500).json({
465
- error: {
466
- message: `代理内部错误: ${errorMessage}`,
467
- type: "proxy_internal_error",
468
- details: error.stack
469
- }
470
  });
471
  } else if (!res.writableEnded) {
472
- console.error("头部已发送,尝试在错误后结束响应。");
473
- res.end();
474
  }
475
  }
476
  });
477
-
478
  // --- Server Start ---
479
  app.listen(PORT, () => {
480
  console.log(`===========================================================`);
481
- console.log(` Fal OpenAI 代理服务器`);
482
- console.log(` 监听端口: ${PORT}`);
483
- console.log(` 限制: System Prompt=${SYSTEM_PROMPT_LIMIT}, Prompt=${PROMPT_LIMIT}`);
 
 
 
484
  console.log(` Chat Completions: POST http://localhost:${PORT}/v1/chat/completions`);
485
  console.log(` Models Endpoint: GET http://localhost:${PORT}/v1/models`);
486
- console.log(`===========================================================`);
487
- });
488
 
489
  // Root path response
490
  app.get('/', (req, res) => {
491
- res.send('Fal OpenAI 代理正在运行。');
492
  });
 
1
  import express from 'express';
2
  import { fal } from '@fal-ai/client';
3
 
4
+ // --- Multi-Key Configuration ---
5
+ // *** 使用 FAL_KEY 环境变量读取逗号分隔的密钥 ***
6
+ const rawFalKeys = process.env.FAL_KEY; // Expect comma-separated keys: key1,key2,key3 in FAL_KEY
7
+ const API_KEY = process.env.API_KEY; // Custom API Key for proxy auth remains the same
8
+
9
+ if (!rawFalKeys) {
10
+ // *** 更新错误信息以引用 FAL_KEY ***
11
+ console.error("Error: FAL_KEY environment variable is not set (should be comma-separated).");
12
+ process.exit(1);
13
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ if (!API_KEY) {
16
+ console.error("Error: API_KEY environment variable is not set.");
17
+ process.exit(1);
18
+ }
 
19
 
20
+ // Parse and prepare the keys
21
+ let falKeys = rawFalKeys.split(',')
22
+ .map(key => key.trim())
23
+ .filter(key => key.length > 0)
24
+ .map(key => ({
25
+ key: key,
26
+ failed: false, // Track if the key is currently considered failed
27
+ failedTimestamp: 0 // Timestamp when the key was marked as failed
28
+ }));
29
+
30
+ if (falKeys.length === 0) {
31
+ // *** 更新错误信息以引用 FAL_KEY ***
32
+ console.error("Error: No valid keys found in FAL_KEY after processing the environment variable.");
33
+ process.exit(1);
34
+ }
35
 
36
+ let currentKeyIndex = 0;
37
+ const failedKeyCooldown = 60 * 1000; // Cooldown period in milliseconds (e.g., 60 seconds) before retrying a failed key
 
 
38
 
39
+ // *** 更新日志信息以引用 FAL_KEY ***
40
+ console.log(`Loaded ${falKeys.length} FAL API Key(s) from FAL_KEY environment variable.`);
41
+ console.log(`Failed key cooldown period: ${failedKeyCooldown / 1000} seconds.`);
42
 
43
  // NOTE: We will configure fal client per request now, so initial global config is removed.
44
 
 
80
  return null; // All keys are currently failed and within cooldown
81
  }
82
 
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
  /**
101
  * Marks a specific key as failed.
102
  * @param {object} keyInfo - The key info object to mark as failed.
 
110
  }
111
  }
112
 
113
+
114
  /**
115
  * Determines if an error likely indicates an API key issue (auth, quota, etc.).
116
  * This needs refinement based on actual errors from fal.ai.
117
  * @param {Error} error - The error object caught from the fal client.
118
  * @returns {boolean} - True if the error suggests a key failure, false otherwise.
119
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  errorMessage.includes('quota exceeded')) {
121
  return true;
122
  }
 
125
  return false;
126
  }
127
 
128
+ // --- Express App Setup ---
129
+ const app = express();
130
+ app.use(express.json({ limit: '50mb' }));
131
+ app.use(express.urlencoded({ extended: true, limit: '50mb' }));
132
+
133
+ const PORT = process.env.PORT || 3000;
134
+
135
+ // API Key 鉴权中间件 (Remains the same, checks custom API_KEY)
136
+ const apiKeyAuth = (req, res, next) => {
137
+ const authHeader = req.headers['authorization'];
138
+
139
+ }
140
+
141
+ const providedKey = authParts[1];
142
+ if (providedKey !== API_KEY) {
143
+ console.warn('Unauthorized: Invalid API Key');
144
+ return res.status(401).json({ error: 'Unauthorized: Invalid API Key' });
145
+ }
146
+
147
+
148
+
149
+
150
+ next();
151
+ };
152
+
153
+ app.use(['/v1/models', '/v1/chat/completions'], apiKeyAuth);
154
+
155
+ // === 全局定义限制 === (Remains the same)
156
+ const PROMPT_LIMIT = 4800;
157
+ const SYSTEM_PROMPT_LIMIT = 4800;
158
+ // === 限制定义结束 ===
159
+
160
  // 定义 fal-ai/any-llm 支持的模型列表 (Remains the same)
161
  const FAL_SUPPORTED_MODELS = [
162
  "anthropic/claude-3.7-sonnet",
 
189
  // GET /v1/models endpoint (Remains the same)
190
  app.get('/v1/models', (req, res) => {
191
  console.log("Received request for GET /v1/models");
192
+ }
193
+ // === convertMessagesToFalPrompt 函数结束 ===
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
 
 
 
 
 
 
 
 
195
 
196
+ /**
197
+ * Wraps the fal.ai API call with retry logic using available keys.
198
+ * @param {'stream' | 'subscribe'} operation - The fal operation to perform.
199
+ * @param {string} functionId - The fal function ID (e.g., "fal-ai/any-llm").
200
+ * @param {object} params - The parameters for the fal function call (input, logs, etc.).
201
+ * @returns {Promise<any>} - The result from the successful fal call (stream or subscription result).
202
+ * @throws {Error} - Throws an error if all keys fail or a non-key-related error occurs.
203
 
204
+ */
205
+ async function tryFalCallWithFailover(operation, functionId, params) {
206
+ const maxRetries = falKeys.length; // Try each key at most once per request cycle
207
+ let lastError = null;
208
+
209
+ for (let i = 0; i < maxRetries; i++) {
210
+ const keyInfo = getNextKey();
211
+ if (!keyInfo) {
212
+ throw new Error(lastError ? `All FAL keys failed. Last error: ${lastError.message}` : "All FAL keys are currently unavailable (failed or in cooldown).");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  }
214
 
215
+ const currentFalKey = keyInfo.key;
216
+ console.log(`Attempt ${i + 1}/${maxRetries}: Using key ending in ...${currentFalKey.slice(-4)}`);
217
+
218
+ try {
219
+ // --- Configure fal client with the selected key for this attempt ---
220
+ // WARNING: This global config change might have concurrency issues in high-load scenarios
221
+ // if the fal client library doesn't isolate requests properly.
222
+ fal.config({ credentials: currentFalKey });
223
+
224
+ if (operation === 'stream') {
225
+ const streamResult = await fal.stream(functionId, params);
226
+ console.log(`Successfully initiated stream with key ending in ...${currentFalKey.slice(-4)}`);
227
+ return streamResult;
228
+ } else { // 'subscribe' (non-stream)
229
+ const result = await fal.subscribe(functionId, params);
230
+ console.log(`Successfully completed subscribe request with key ending in ...${currentFalKey.slice(-4)}`);
231
+
232
+ if (result && result.error) {
233
+ console.warn(`Fal-ai returned an application error (non-stream) with key ...${currentFalKey.slice(-4)}: ${JSON.stringify(result.error)}`);
234
+ }
235
+ return result;
236
  }
237
+ } catch (error) {
238
+ console.error(`Error using key ending in ...${currentFalKey.slice(-4)}:`, error.message || error);
239
+ lastError = error;
240
 
241
+ if (isKeyRelatedError(error)) {
242
+ markKeyFailed(keyInfo);
243
+ console.log(`Key marked as failed. Trying next key if available...`);
 
 
 
244
  } else {
245
+ console.error("Non-key related error occurred. Aborting retries.");
246
+ throw error;
247
  }
 
 
248
 
249
+ }
 
 
250
 
 
 
251
 
 
252
 
 
 
253
 
 
 
 
 
 
 
 
 
 
 
254
 
 
 
 
 
 
255
 
 
256
 
 
 
 
257
 
 
 
 
 
 
 
 
 
258
  }
 
 
259
 
260
+ console.error("All FAL keys failed after attempting each one.");
261
+ throw new Error(lastError ? `All FAL keys failed. Last error: ${lastError.message}` : "All FAL API keys failed.");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
  }
263
 
264
+
265
  // POST /v1/chat/completions endpoint (Modified to use tryFalCallWithFailover)
266
  app.post('/v1/chat/completions', async (req, res) => {
267
  const { model, messages, stream = false, reasoning = false, ...restOpenAIParams } = req.body;
268
 
269
+
270
+ console.log(`Received chat completion request for model: ${model}, stream: ${stream}`);
271
 
272
  if (!FAL_SUPPORTED_MODELS.includes(model)) {
273
+ console.warn(`Warning: Requested model '${model}' is not in the explicitly supported list.`);
274
  }
275
  if (!model || !messages || !Array.isArray(messages) || messages.length === 0) {
276
+ console.error("Invalid request parameters:", { model, messages: Array.isArray(messages) ? messages.length : typeof messages });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  let falStream;
278
 
279
  try {
280
+ falStream = await tryFalCallWithFailover('stream', "fal-ai/any-llm", { input: falInput });
281
 
282
+ for await (const event of falStream) {
283
  const currentOutput = (event && typeof event.output === 'string') ? event.output : '';
284
  const isPartial = (event && typeof event.partial === 'boolean') ? event.partial : true;
285
  const errorInfo = (event && event.error) ? event.error : null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
  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 }] };
287
  res.write(`data: ${JSON.stringify(openAIChunk)}\n\n`);
288
  }
289
+ }
290
+ res.write(`data: [DONE]\n\n`);
291
+ res.end();
292
+ console.log("Stream finished successfully.");
293
 
294
  } catch (streamError) {
295
+ console.error('Error during stream processing:', streamError);
296
  if (!res.writableEnded) {
297
+ try {
298
+ const errorDetails = (streamError instanceof Error) ? streamError.message : JSON.stringify(streamError);
299
+ const finalErrorChunk = { error: { message: "Stream failed", type: "proxy_error", details: errorDetails } };
300
+ res.write(`data: ${JSON.stringify(finalErrorChunk)}\n\n`);
301
+ res.write(`data: [DONE]\n\n`);
302
+ res.end();
303
+ } catch (finalError) {
304
+ console.error('Error sending final stream error message to client:', finalError);
305
+ if (!res.writableEnded) { res.end(); }
306
+ }
307
+ }
308
  }
309
 
310
  } else { // Non-stream
311
+ console.log("Executing non-stream request with failover...");
312
+ const result = await tryFalCallWithFailover('subscribe', "fal-ai/any-llm", { input: falInput, logs: true });
313
+
314
+ console.log("Received non-stream result from fal-ai via failover wrapper.");
315
+
316
+ if (result && result.error) {
317
+ console.error("Fal-ai returned an application error in non-stream mode (after successful API call):", result.error);
318
+ return res.status(500).json({
319
+ object: "error",
320
+ message: `Fal-ai application error: ${JSON.stringify(result.error)}`,
321
+ type: "fal_ai_error",
322
+ param: null,
323
+ code: result.error.code || null
324
+ });
325
+ }
326
+
327
+ const openAIResponse = {
328
+ id: `chatcmpl-${result?.requestId || Date.now()}`,
329
+ object: "chat.completion",
330
+ created: Math.floor(Date.now() / 1000),
331
+ model: model,
332
+ choices: [{
333
+ index: 0,
334
+ message: {
335
+ role: "assistant",
336
+ content: result?.output || ""
337
+ },
338
+ finish_reason: "stop"
339
+ }],
340
+ usage: {
341
+ prompt_tokens: null,
342
+ completion_tokens: null,
343
+ total_tokens: null
344
+ },
345
+ system_fingerprint: null,
346
+ ...(result?.reasoning && { fal_reasoning: result.reasoning }),
347
+ };
348
+ res.json(openAIResponse);
349
+ console.log("Returned non-stream response successfully.");
350
  }
351
 
352
  } catch (error) {
353
+ console.error('Unhandled error in /v1/chat/completions:', error);
354
  if (!res.headersSent) {
355
  const errorMessage = (error instanceof Error) ? error.message : JSON.stringify(error);
356
+ const errorType = error.message?.includes("All FAL keys failed") ? "api_key_error" : "proxy_internal_error";
357
  res.status(500).json({
358
+ error: {
359
+ message: `Internal Server Error in Proxy: ${errorMessage}`,
360
+ type: errorType,
361
+ details: error.stack // Optional: include stack in dev/debug mode
362
+ }
363
  });
364
  } else if (!res.writableEnded) {
365
+ console.error("Headers already sent, attempting to end response after error.");
366
+ res.end();
367
  }
368
  }
369
  });
 
370
  // --- Server Start ---
371
  app.listen(PORT, () => {
372
  console.log(`===========================================================`);
373
+ console.log(` Fal OpenAI Proxy Server (Multi-Key Failover)`);
374
+ console.log(` Listening on port: ${PORT}`);
375
+ // *** 更新日志信息以引用 FAL_KEY ***
376
+ console.log(` Loaded ${falKeys.length} FAL API Key(s) from FAL_KEY.`);
377
+ console.log(` API Key Auth Enabled: ${API_KEY ? 'Yes' : 'No'}`);
378
+ console.log(` Limits: System Prompt=${SYSTEM_PROMPT_LIMIT}, Prompt=${PROMPT_LIMIT}`);
379
  console.log(` Chat Completions: POST http://localhost:${PORT}/v1/chat/completions`);
380
  console.log(` Models Endpoint: GET http://localhost:${PORT}/v1/models`);
 
 
381
 
382
  // Root path response
383
  app.get('/', (req, res) => {
384
+ res.send('Fal OpenAI Proxy (Multi-Key Failover) is running.');
385
  });