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