Spaces:
Sleeping
Sleeping
File size: 12,444 Bytes
c5b52c6 6187dd4 c5b52c6 | 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 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | import cors from 'cors';
import dotenv from 'dotenv';
import express from 'express';
import { createClient } from '@supabase/supabase-js';
import { BedrockRuntimeClient, ConverseStreamCommand } from "@aws-sdk/client-bedrock-runtime";
import { NodeHttpHandler } from "@smithy/node-http-handler";
import path from 'path';
import { fileURLToPath } from 'url';
dotenv.config();
const app = express();
const PORT = process.env.PORT || 7860;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.static(path.join(__dirname, 'public')));
// --- LOGGER HELPER ---
const log = {
info: (msg, id = "SYS") => console.log(`[${new Date().toISOString()}] [INFO][${id}] ${msg}`),
warn: (msg, id = "SYS") => console.warn(`[${new Date().toISOString()}] ⚠️ [WARN][${id}] ${msg}`),
error: (msg, err, id = "SYS") => console.error(`[${new Date().toISOString()}] ❌ [ERROR] [${id}] ${msg}`, err?.message || err, err?.stack || "")
};
// --- SYSTEM PROMPT DEFINITIONS ---
const CLAUDE_SYSTEM_PROMPT = "You are a pro. Provide elite, high-level technical responses.";
// --- AI CLIENTS ---
const bedrockClient = new BedrockRuntimeClient({
region: "us-east-1",
requestHandler: new NodeHttpHandler({ http2Handler: undefined })
});
function getBedrockModelId(modelName) {
switch(modelName) {
case "haiku": return "arn:aws:bedrock:us-east-1:106774395747:inference-profile/global.anthropic.claude-haiku-4-5-20251001-v1:0";
case "maverick": return "arn:aws:bedrock:us-east-1:106774395747:inference-profile/us.meta.llama4-maverick-17b-instruct-v1:0";
case "claude": default: return "arn:aws:bedrock:us-east-1:106774395747:inference-profile/global.anthropic.claude-sonnet-4-6";
}
}
// --- DB & MEMORY MANAGEMENT (SUPABASE) ---
const supabase = createClient(
process.env.SUPABASE_URL || '',
process.env.SUPABASE_KEY || ''
);
let memoryChats = {};
let dirtyChats = new Set();
const activeGenerations = new Map();
async function initDB() {
try {
log.info("Connecting to Supabase...");
const { data: dbChats, error } = await supabase.from('chats').select('*');
if (error) throw error;
if (dbChats) {
dbChats.forEach(c => {
memoryChats[c.id] = {
...c,
inputTokens: c.inputTokens || 0,
outputTokens: c.outputTokens || 0,
isGenerating: false
};
});
log.info(`Hydrated ${dbChats.length} chats from DB.`);
}
setInterval(async () => {
if (dirtyChats.size === 0) return;
const toSync = Array.from(dirtyChats);
dirtyChats.clear();
const rowsToUpsert = toSync.map(id => {
const chat = memoryChats[id];
chat.updatedAt = new Date().toISOString();
return {
id: chat.id, title: chat.title, totalTokens: chat.totalTokens,
inputTokens: chat.inputTokens, outputTokens: chat.outputTokens,
messages: chat.messages, updatedAt: chat.updatedAt
};
});
if (rowsToUpsert.length > 0) {
const { error } = await supabase.from('chats').upsert(rowsToUpsert);
if (error) log.error(`Supabase Sync Error.`, error);
else log.info(`Synced ${rowsToUpsert.length} chats to Supabase.`);
}
}, 15000);
} catch (err) {
log.error('Supabase Initialization Error.', err);
}
}
initDB();
// --- API ENDPOINTS ---
app.get('/api/chats', (req, res) => {
const chatsList = Object.values(memoryChats).map(c => ({
id: c.id, title: c.title, totalTokens: c.totalTokens,
inputTokens: c.inputTokens, outputTokens: c.outputTokens, updatedAt: c.updatedAt
})).sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt));
res.json(chatsList);
});
app.get('/api/chats/:id', (req, res) => {
const chat = memoryChats[req.params.id];
if (!chat) return res.status(404).json({ error: "Chat not found" });
res.json(chat);
});
app.post('/api/chats', (req, res) => {
const newId = Date.now().toString();
memoryChats[newId] = {
id: newId, title: "New Chat", totalTokens: 0, inputTokens: 0, outputTokens: 0,
messages:[], isGenerating: false, updatedAt: new Date().toISOString()
};
dirtyChats.add(newId);
log.info("Created new chat.", newId);
res.json(memoryChats[newId]);
});
app.put('/api/chats/:id/title', (req, res) => {
const { id } = req.params;
const { title } = req.body;
if (!memoryChats[id]) return res.status(404).json({ error: "Chat not found" });
if (!title || typeof title !== 'string') return res.status(400).json({ error: "Invalid title" });
memoryChats[id].title = title.trim();
dirtyChats.add(id);
log.info(`Title updated to: "${title.trim()}"`, id);
res.json({ success: true, title: memoryChats[id].title });
});
app.delete('/api/chats/:id', async (req, res) => {
const { id } = req.params;
if (activeGenerations.has(id)) {
activeGenerations.get(id).abort();
activeGenerations.delete(id);
}
delete memoryChats[id];
dirtyChats.delete(id);
await supabase.from('chats').delete().eq('id', id);
log.info("Deleted chat permanently.", id);
res.json({ success: true });
});
app.post('/api/chats/:id/stop', (req, res) => {
const { id } = req.params;
log.info("User requested to stop generation.", id);
if (activeGenerations.has(id)) {
activeGenerations.get(id).abort();
activeGenerations.delete(id);
}
if (memoryChats[id]) {
memoryChats[id].isGenerating = false;
dirtyChats.add(id);
}
res.json({ success: true });
});
// --- STREAM ENDPOINT ---
app.post('/api/chats/:id/stream', async (req, res) => {
const { id } = req.params;
const { model, prompt, system_prompt, images } = req.body;
if (!memoryChats[id]) return res.status(404).send("Chat not found");
if (!prompt || typeof prompt !== 'string' || prompt.trim() === '') {
return res.status(400).send("Prompt cannot be empty");
}
if (memoryChats[id].isGenerating) {
log.warn("Attempted concurrent generation. Rejecting request.", id);
return res.status(409).json({ error: "Chat is currently generating." });
}
log.info(`Starting stream. Model: ${model} | Prompt length: ${prompt.length} | Images: ${images?.length || 0}`, id);
if (memoryChats[id].messages.length === 0 && memoryChats[id].title === "New Chat") {
memoryChats[id].title = prompt.substring(0, 30) + (prompt.length > 30 ? '...' : '');
}
memoryChats[id].messages.push({ role: "user", content: prompt });
const aiMessage = { role: "assistant", content: "", reasoning: "" };
memoryChats[id].messages.push(aiMessage);
memoryChats[id].isGenerating = true;
dirtyChats.add(id);
const abortController = new AbortController();
activeGenerations.set(id, abortController);
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.setHeader('Transfer-Encoding', 'chunked');
res.setHeader('X-Accel-Buffering', 'no');
res.flushHeaders();
const safeWrite = (data) => {
if (!req.socket.destroyed && !res.writableEnded) {
try { res.write(data); } catch (e) { log.warn("Socket disconnected during write.", id); }
}
};
const safeEnd = () => {
if (!req.socket.destroyed && !res.writableEnded) {
try { res.end(); } catch (e) {}
}
};
let streamInputTokens = 0;
let streamOutputTokens = 0;
let streamTotalTokens = 0;
try {
const bedrockModelId = getBedrockModelId(model);
let contentBlock = [{ text: prompt }];
if (images && images.length > 0) {
const imageBlocks = images.map(imgStr => {
const base64Data = imgStr.replace(/^data:image\/\w+;base64,/, "");
return { image: { format: 'png', source: { bytes: Buffer.from(base64Data, 'base64') } } };
});
contentBlock =[...imageBlocks, ...contentBlock];
}
// --- NEW: Limit Context to 10 Messages Max securely ---
let historySlice = memoryChats[id].messages.slice(0, -2).slice(-30);
// Bedrock/Claude Converse API will fail if the message history starts with an "assistant" role.
// We shift (remove) the first item if it's an assistant response.
if (historySlice.length > 0 && historySlice[0].role === "assistant") {
historySlice.shift();
}
const historicalMessages = historySlice.map(m => {
let safeText = m.content;
if (!safeText || safeText.trim() === "") {
safeText = "[System Note: The model failed to generate a response here previously.]";
}
return { role: m.role, content:[{ text: safeText }] };
});
historicalMessages.push({ role: "user", content: contentBlock });
// THE FIX: Uncapped Token limit for Claude 3.7 to allow massive reasoning + coding
const commandMaxTokens = model.includes("claude") ? 64000 : 8192;
const command = new ConverseStreamCommand({
modelId: bedrockModelId,
system:[{ text: system_prompt || CLAUDE_SYSTEM_PROMPT }],
messages: historicalMessages,
inferenceConfig: { maxTokens: commandMaxTokens, temperature: 1 },
/* additionalModelRequestFields: model.includes("claude") ? {
thinking: { type: "adaptive" }
} : undefined
*/
});
const response = await bedrockClient.send(command, { abortSignal: abortController.signal });
log.info(`Bedrock connected successfully (Max Tokens: ${commandMaxTokens}), streaming chunks...`, id);
for await (const chunk of response.stream) {
if (chunk.contentBlockDelta) {
const delta = chunk.contentBlockDelta.delta;
if (delta.reasoningContent && delta.reasoningContent.text) {
aiMessage.reasoning += delta.reasoningContent.text;
safeWrite(`__THINK__${delta.reasoningContent.text}`);
} else if (delta.text) {
aiMessage.content += delta.text;
safeWrite(delta.text);
}
}
// Log exactly why it stopped (e.g. max_tokens vs end_turn)
if (chunk.messageStop) {
log.info(`Stream stopped. Reason: ${chunk.messageStop.stopReason}`, id);
}
if (chunk.metadata && chunk.metadata.usage) {
streamInputTokens = chunk.metadata.usage.inputTokens || 0;
streamOutputTokens = chunk.metadata.usage.outputTokens || 0;
streamTotalTokens = streamInputTokens + streamOutputTokens;
}
}
log.info(`Stream completed normally. (In: ${streamInputTokens}, Out: ${streamOutputTokens})`, id);
} catch (err) {
if (err.name === 'AbortError' || err.name === 'TimeoutError') {
log.warn("Generation aborted by user or timeout.", id);
aiMessage.content += "\n\n*[Generation stopped by user]*";
safeWrite("\n\n*[Generation stopped by user]*");
} else {
log.error("Generation failed during stream processing.", err, id);
aiMessage.content += `\n\n**[Error]**: ${err.message}`;
safeWrite(`\n\n**ERROR**: ${err.message}`);
}
} finally {
activeGenerations.delete(id);
memoryChats[id].inputTokens += streamInputTokens;
memoryChats[id].outputTokens += streamOutputTokens;
memoryChats[id].totalTokens += streamTotalTokens;
memoryChats[id].isGenerating = false;
dirtyChats.add(id);
safeWrite(`__USAGE__${JSON.stringify({
inputTokens: streamInputTokens,
outputTokens: streamOutputTokens,
totalTokens: streamTotalTokens
})}`);
safeEnd();
}
});
app.listen(PORT, '0.0.0.0', () => log.info(`AI Server live on http://localhost:${PORT}`)); |