dfa32412 commited on
Commit
f031603
·
verified ·
1 Parent(s): 5c100bb

Upload 2 files

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