-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.js
More file actions
289 lines (257 loc) · 9.21 KB
/
Copy pathproxy.js
File metadata and controls
289 lines (257 loc) · 9.21 KB
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
import express from "express";
import cors from "cors";
import rateLimit from "express-rate-limit";
import { existsSync, readFileSync } from "fs";
import sanitize from "./middleware/sanitize.js"; // ← .js obrigatório em ESM
import arcjetMiddleware from "./middleware/arcjet.js";
import notionExportHandler from "./api/notion-export.js";
import { notifyCouncilError, notifyLobeTimeout } from "./src/lib/discord.js";
import { traceLobe } from "./src/lib/monitoring.js";
const PROD_ORIGIN = "https://cortex-five-hazel.vercel.app";
const OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions";
const NIM_URL = "https://integrate.api.nvidia.com/v1/chat/completions";
const FREE_FALLBACKS = [
"google/gemma-3-4b-it:free",
"google/gemma-3n-e4b-it:free",
"liquid/lfm-2.5-1.2b-instruct:free",
"openai/gpt-oss-120b:free",
"nvidia/nemotron-3-nano-30b-a3b:free",
];
function carregarEnvLocal() {
for (const ficheiro of [".env.local", ".env"]) {
if (!existsSync(ficheiro)) continue;
const linhas = readFileSync(ficheiro, "utf8").split(/\r?\n/);
for (const linha of linhas) {
const limpo = linha.trim();
if (!limpo || limpo.startsWith("#") || !limpo.includes("=")) continue;
const idx = limpo.indexOf("=");
const chave = limpo.slice(0, idx).trim();
const valor = limpo.slice(idx + 1).trim().replace(/^["']|["']$/g, "");
if (chave && process.env[chave] === undefined) process.env[chave] = valor;
}
}
}
carregarEnvLocal();
const app = express();
app.use(express.json());
app.use(cors({ origin: "*" }));
// ── Rate limiter + sanitize nas rotas de IA ──────────────
const aiLimiter = rateLimit({
windowMs: 60 * 1000,
max: 30,
message: { error: "Demasiados pedidos. Tenta novamente em 1 minuto." },
standardHeaders: true,
legacyHeaders: false,
});
app.use(["/api/chat", "/api/nim-proxy", "/ollama", "/gemini/{*path}"], aiLimiter, arcjetMiddleware, sanitize);
async function lerJsonSeguro(resposta) {
const texto = await resposta.text().catch(() => "");
if (!texto.trim()) return {};
try {
return JSON.parse(texto);
} catch {
return { error: `Resposta não-JSON HTTP ${resposta.status}` };
}
}
function erroTexto(erro) {
if (!erro) return "";
if (typeof erro === "string") return erro;
return erro.message || JSON.stringify(erro);
}
function lerOpenRouterKey() {
return process.env.OPENROUTER_KEY || process.env.OPENROUTER_API_KEY || process.env.VITE_OPENROUTER_KEY;
}
function lerNimKey() {
return process.env.NVIDIA_NIM_KEY || process.env.VITE_NVIDIA_NIM_KEY;
}
function resumirConteudo(conteudo) {
if (typeof conteudo === "string") return conteudo.slice(0, 800);
if (Array.isArray(conteudo)) {
const texto = conteudo.find((item) => item?.type === "text")?.text;
return texto ? String(texto).slice(0, 800) : "[conteúdo multimodal]";
}
return "";
}
function perguntaDoProxy(messages) {
const ultima = Array.isArray(messages) ? messages.at(-1) : null;
return resumirConteudo(ultima?.content);
}
function textoRespostaOpenRouter(dados) {
return dados?.choices?.[0]?.message?.content || dados?.content || "";
}
function notificarTimeoutSeAplicavel(erro, contexto) {
const texto = erroTexto(erro);
if (contexto.status === 408 || contexto.status === 504 || /timeout/i.test(texto)) {
notifyLobeTimeout(contexto).catch(() => {});
}
}
// ── Proxy local compatível com /api/chat da Vercel ───────────
app.post("/api/chat", async (req, res) => {
const { model, messages, system, max_tokens } = req.body || {};
const apiKey = lerOpenRouterKey();
if (!apiKey) {
return res.status(500).json({ error: "OPENROUTER_KEY/OPENROUTER_API_KEY não configurada" });
}
if (typeof model !== "string" || !model.trim() || !Array.isArray(messages)) {
return res.status(400).json({ error: "Campos obrigatórios: model, messages" });
}
const payload = {
max_tokens: max_tokens || 420,
messages: system ? [{ role: "system", content: system }, ...messages] : messages,
};
const modelos = model.endsWith(":free")
? [model, ...FREE_FALLBACKS.filter((m) => m !== model)]
: [model];
let ultimoErro = null;
let ultimoStatus = 502;
const perguntaTrace = perguntaDoProxy(messages);
try {
for (const modeloAtual of modelos) {
const inicio = Date.now();
const upstream = await fetch(OPENROUTER_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
"HTTP-Referer": PROD_ORIGIN,
"X-Title": "Córtex Digital",
},
body: JSON.stringify({ ...payload, model: modeloAtual }),
});
const dados = await lerJsonSeguro(upstream);
ultimoStatus = upstream.status;
ultimoErro = dados;
const sucesso = upstream.ok && !dados.error && dados.choices?.[0];
const erro = dados.error?.message || dados.error || (!upstream.ok ? `HTTP ${upstream.status}` : null);
traceLobe({
lobo: "proxy:/api/chat",
modelo: modeloAtual,
pergunta: perguntaTrace,
resposta: textoRespostaOpenRouter(dados),
sucesso: Boolean(sucesso),
erro,
tempoMs: Date.now() - inicio,
tokens: dados.usage?.total_tokens,
fase: "proxy",
}).catch(() => {});
if (sucesso) {
const choice = dados.choices[0];
return res.status(200).json({
content: choice.message?.content || "",
model: dados.model || modeloAtual,
provider: "openrouter",
usage: dados.usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
});
}
notificarTimeoutSeAplicavel(erro || dados, {
lobo: "proxy:/api/chat",
modelo: modeloAtual,
tempoMs: Date.now() - inicio,
status: upstream.status,
fase: "proxy",
});
}
notifyCouncilError(new Error("OpenRouter devolveu erro"), {
fase: "proxy",
status: ultimoStatus,
modelo: model,
detalhe: erroTexto(ultimoErro?.error || ultimoErro),
}).catch(() => {});
return res.status(502).json({
error: "OpenRouter devolveu erro",
status: ultimoStatus,
detail: erroTexto(ultimoErro?.error || ultimoErro),
});
} catch (e) {
notificarTimeoutSeAplicavel(e, {
lobo: "proxy:/api/chat",
modelo: model,
fase: "proxy",
});
notifyCouncilError(e, { fase: "proxy", modelo: model }).catch(() => {});
return res.status(500).json({ error: e.message });
}
});
// ── Proxy local compatível com /api/notion-export da Vercel ─
app.post("/api/notion-export", (req, res) => notionExportHandler(req, res));
// ── Proxy local compatível com /api/nim-proxy da Vercel ──────
app.post("/api/nim-proxy", async (req, res) => {
const apiKey = lerNimKey();
if (!apiKey) {
return res.status(500).json({ error: "NVIDIA_NIM_KEY não configurada" });
}
try {
const upstream = await fetch(NIM_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify(req.body),
});
const dados = await lerJsonSeguro(upstream);
return res.status(upstream.status).json(dados);
} catch (e) {
return res.status(500).json({ error: e.message });
}
});
// ── Ollama local ──────────────────────────────────────────
app.post("/ollama", async (req, res) => {
try {
const { model = "qwen2.5-coder:1.5b", prompt } = req.body;
const r = await fetch("http://localhost:11434/api/generate", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model,
prompt,
stream: false,
options: { temperature: 0.3, num_predict: 512 },
}),
});
const d = await r.json();
res.json({ response: d.response || "", done: true });
} catch (e) {
res.status(500).json({ error: e.message });
}
});
// ── Gemini proxy ──────────────────────────────────────────
app.post("/gemini/{*path}", async (req, res) => {
const key = process.env.GEMINI_API_KEY;
if (!key)
return res
.status(503)
.json({
error: {
message:
"Gemini proxy sem key de servidor. Define GEMINI_API_KEY no .env",
},
});
const path =
req.params[0] || "v1beta/models/gemini-2.5-flash:generateContent";
try {
const r = await fetch(
`https://generativelanguage.googleapis.com/${path}?key=${key}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(req.body),
},
);
const d = await r.json();
res.status(r.status).json(d);
} catch (e) {
res.status(500).json({ error: { message: e.message } });
}
});
app.get("/", (req, res) => {
res.json({
status: "Córtex Proxy OK",
ollama: "localhost:11434",
gemini: process.env.GEMINI_API_KEY
? "✓ key configurada"
: "sem key (define GEMINI_API_KEY)",
});
});
const PORT = process.env.PORT || 3333;
app.listen(PORT, () => console.log(`Córtex Proxy em http://localhost:${PORT}`));