Ejdjdososs commited on
Commit
a91fecf
·
verified ·
1 Parent(s): 5fb13f9

v2 final: clean Dockerfile + node-llama-cpp local model + full UI (markdown+artifacts+fileupload)

Browse files
Files changed (3) hide show
  1. Dockerfile +13 -17
  2. package.json +1 -2
  3. server.js +178 -118
Dockerfile CHANGED
@@ -1,33 +1,29 @@
1
- # Stage 1: Build frontend
2
  FROM node:20-slim AS frontend-builder
3
  WORKDIR /build
4
  COPY frontend/package.json ./
5
- RUN npm install 2>/dev/null || npm install --legacy-peer-deps
6
  COPY frontend/ ./
7
  RUN npm run build
8
 
9
- # Stage 2: Production
10
  FROM node:20-slim
11
 
12
- # System deps (minimal — no C++ compilation needed)
13
- RUN apt-get update && apt-get install -y --no-install-recommends \
14
- python3 python3-pip curl ca-certificates make g++ \
15
- && pip3 install --no-cache-dir flask huggingface_hub requests \
16
- && rm -rf /var/lib/apt/lists/*
17
-
18
- # Create directories
19
- RUN mkdir -p /app/models /data && chmod 777 /data
20
 
21
  WORKDIR /app
 
22
 
23
- # Install Node deps (includes better-sqlite3 native compilation)
24
  COPY package.json ./
25
  RUN npm install --omit=dev
26
 
27
- # Copy built assets
28
  COPY --from=frontend-builder /build/dist ./dist
29
- COPY server.js airllm_server.py start.sh ./
30
- RUN chmod +x start.sh
31
 
32
  RUN chown -R 1000:1000 /app /data
33
  USER 1000
@@ -35,7 +31,7 @@ USER 1000
35
  EXPOSE 7860
36
  ENV PORT=7860 NODE_ENV=production
37
 
38
- HEALTHCHECK --interval=30s --timeout=10s --start-period=60s \
39
  CMD node -e "require('http').get('http://localhost:7860/api/status',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"
40
 
41
- CMD ["./start.sh"]
 
1
+ # Stage 1: Build React frontend
2
  FROM node:20-slim AS frontend-builder
3
  WORKDIR /build
4
  COPY frontend/package.json ./
5
+ RUN npm install --legacy-peer-deps
6
  COPY frontend/ ./
7
  RUN npm run build
8
 
9
+ # Stage 2: Production server
10
  FROM node:20-slim
11
 
12
+ # Only what we need: python3 + make + g++ for better-sqlite3 native build
13
+ RUN apt-get update \
14
+ && apt-get install -y --no-install-recommends python3 make g++ curl ca-certificates \
15
+ && rm -rf /var/lib/apt/lists/*
 
 
 
 
16
 
17
  WORKDIR /app
18
+ RUN mkdir -p /data /app/models && chmod 777 /data
19
 
20
+ # Install Node deps (better-sqlite3 compiles here using python3+make+g++)
21
  COPY package.json ./
22
  RUN npm install --omit=dev
23
 
24
+ # Copy built frontend & server
25
  COPY --from=frontend-builder /build/dist ./dist
26
+ COPY server.js ./
 
27
 
28
  RUN chown -R 1000:1000 /app /data
29
  USER 1000
 
31
  EXPOSE 7860
32
  ENV PORT=7860 NODE_ENV=production
33
 
34
+ HEALTHCHECK --interval=30s --timeout=10s --start-period=30s \
35
  CMD node -e "require('http').get('http://localhost:7860/api/status',r=>process.exit(r.statusCode===200?0:1)).on('error',()=>process.exit(1))"
36
 
37
+ CMD ["node", "server.js"]
package.json CHANGED
@@ -8,7 +8,6 @@
8
  "better-sqlite3": "^9.6.0",
9
  "cors": "^2.8.5",
10
  "express": "^4.21.0",
11
- "multer": "^1.4.5-lts.1",
12
- "node-fetch": "^3.3.2"
13
  }
14
  }
 
8
  "better-sqlite3": "^9.6.0",
9
  "cors": "^2.8.5",
10
  "express": "^4.21.0",
11
+ "node-llama-cpp": "^3.1.0"
 
12
  }
13
  }
server.js CHANGED
@@ -4,7 +4,7 @@ import { createRequire } from 'module';
4
  import { fileURLToPath } from 'url';
5
  import { dirname, join } from 'path';
6
  import fs from 'fs';
7
- import { execSync } from 'child_process';
8
 
9
  const require = createRequire(import.meta.url);
10
  const Database = require('better-sqlite3');
@@ -39,60 +39,97 @@ db.exec(`
39
  CREATE INDEX IF NOT EXISTS idx_conv_upd ON conversations(updated_at DESC);
40
  `);
41
 
42
- // ─── LOCAL MODEL STATE ────────────────────────────────────────────────────────
43
  const LOCAL_MODEL_PATH = '/app/models/local.gguf';
44
- let localModelReady = false;
45
- let localLlamaReady = false;
46
 
47
- async function checkLocalServer() {
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  try {
49
- const r = await fetch('http://127.0.0.1:8080/health', { signal: AbortSignal.timeout(2000) });
50
- if (r.ok) { localLlamaReady = true; console.log('✅ llama.cpp server ready!'); return; }
51
- } catch {}
52
- setTimeout(checkLocalServer, 15000);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  }
54
 
55
- // Check if model file exists periodically
56
- function watchLocalModel() {
57
- if (fs.existsSync(LOCAL_MODEL_PATH) && fs.statSync(LOCAL_MODEL_PATH).size > 100000000) {
 
 
 
58
  localModelReady = true;
59
- console.log('✅ Local model file ready:', LOCAL_MODEL_PATH);
60
- // Try to start llama.cpp if not running
61
- checkLocalServer();
 
 
 
62
  }
63
- setTimeout(watchLocalModel, 15000);
64
  }
65
- watchLocalModel();
66
- setTimeout(checkLocalServer, 10000);
 
67
 
68
  // ─── PROVIDERS ────────────────────────────────────────────────────────────────
69
  const PROVIDERS = {
70
- hf_free: {
71
- name: '🆓 HF Free (No Key)',
72
- description: 'HuggingFace Inference — no API key needed, works anonymously',
73
- key: null, // Anonymous
74
  models: [
75
- { id: 'hf_free::mistralai/Mistral-7B-Instruct-v0.3', name: '🆓 Mistral 7B · No Key Needed', maxTokens: 4096, reasoning: false, badge: 'FREE', alwaysFree: true },
76
- { id: 'hf_free::HuggingFaceH4/zephyr-7b-beta', name: '🆓 Zephyr 7B · No Key Needed', maxTokens: 4096, reasoning: false, badge: 'FREE', alwaysFree: true },
77
  ]
78
  },
79
- local: {
80
- name: '💻 Local (TinyLlama)',
81
- description: 'Runs entirely on the Space server — truly local, no internet',
82
- key: 'local',
83
  models: [
84
- { id: 'tinyllama', name: '💻 TinyLlama 1.1B · Fully Local · No API Key', maxTokens: 2048, reasoning: false, badge: 'LOCAL', local: true }
 
85
  ]
86
  },
87
  groq: {
88
  name: '⚡ Groq',
89
- description: 'Free tier — 500 tokens/sec',
90
  baseURL: 'https://api.groq.com/openai/v1',
91
  key: process.env.GROQ_API_KEY,
92
  models: [
93
- { id: 'llama-3.3-70b-versatile', name: '⚡ Llama 3.3 70B · Groq', maxTokens: 32768, reasoning: false, badge: 'FAST' },
94
  { id: 'deepseek-r1-distill-llama-70b', name: '⚡🧠 DeepSeek R1 70B · Groq', maxTokens: 32768, reasoning: true, badge: 'REASON' },
95
- { id: 'meta-llama/llama-4-scout-17b-16e-instruct', name: '⚡ Llama 4 Scout · Groq', maxTokens: 131072, reasoning: false, badge: 'FAST' },
96
  { id: 'qwen-qwq-32b', name: '⚡🧠 QwQ 32B · Groq', maxTokens: 32768, reasoning: true, badge: 'REASON' },
97
  ]
98
  },
@@ -102,11 +139,11 @@ const PROVIDERS = {
102
  baseURL: 'https://openrouter.ai/api/v1',
103
  key: process.env.OPENROUTER_API_KEY,
104
  models: [
105
- { id: 'deepseek/deepseek-chat-v3-0324:free', name: '🆓 DeepSeek V3 · OpenRouter FREE', maxTokens: 16384, reasoning: false, badge: 'FREE' },
106
- { id: 'deepseek/deepseek-r1:free', name: '🆓🧠 DeepSeek R1 · FREE Reasoning', maxTokens: 16384, reasoning: true, badge: 'FREE' },
107
- { id: 'meta-llama/llama-3.3-70b-instruct:free', name: '🆓 Llama 3.3 70B · OpenRouter FREE', maxTokens: 8192, reasoning: false, badge: 'FREE' },
108
- { id: 'google/gemma-3-27b-it:free', name: '🆓 Gemma 3 27B · FREE', maxTokens: 8192, reasoning: false, badge: 'FREE' },
109
- { id: 'qwen/qwq-32b:free', name: '🆓🧠 QwQ 32B Reasoning · FREE', maxTokens: 16384, reasoning: true, badge: 'FREE' },
110
  ]
111
  },
112
  together: {
@@ -115,25 +152,25 @@ const PROVIDERS = {
115
  baseURL: 'https://api.together.xyz/v1',
116
  key: process.env.TOGETHER_API_KEY,
117
  models: [
118
- { id: 'deepseek-ai/DeepSeek-V3', name: 'DeepSeek V3 · Together', maxTokens: 16384, reasoning: false },
119
  { id: 'deepseek-ai/DeepSeek-R1', name: '🧠 DeepSeek R1 · Together', maxTokens: 16384, reasoning: true },
120
- { id: 'meta-llama/Llama-3.3-70B-Instruct-Turbo', name: 'Llama 3.3 70B Turbo · Together', maxTokens: 32768, reasoning: false },
121
  ]
122
  },
123
  hf: {
124
  name: '🤗 HuggingFace',
125
- description: 'HF Inference API with token',
126
  key: process.env.HF_TOKEN,
127
  models: [
128
- { id: 'meta-llama/Llama-3.3-70B-Instruct', name: 'Llama 3.3 70B · HuggingFace', maxTokens: 4096, reasoning: false },
129
- { id: 'Qwen/Qwen2.5-72B-Instruct', name: 'Qwen 2.5 72B · HuggingFace', maxTokens: 4096, reasoning: false },
130
  { id: 'deepseek-ai/DeepSeek-R1-Distill-Qwen-32B', name: '🧠 DeepSeek R1 32B · HuggingFace', maxTokens: 4096, reasoning: true },
131
  ]
132
  }
133
  };
134
 
135
  function getActiveProvider() {
136
- if (localLlamaReady) return 'local';
137
  if (process.env.GROQ_API_KEY) return 'groq';
138
  if (process.env.OPENROUTER_API_KEY) return 'openrouter';
139
  if (process.env.TOGETHER_API_KEY) return 'together';
@@ -143,44 +180,42 @@ function getActiveProvider() {
143
 
144
  // ─── SYSTEM PROMPT ───────────────────────────────────────────────────────────
145
  const SYSTEM_PROMPT = `You are Fable, an advanced AI assistant comparable to Claude. You:
146
- - Respond fluently in the user's language (Arabic, English, etc.)
147
- - Write beautiful, well-structured markdown (headers, tables, code blocks, lists)
148
- - For all code: use fenced code blocks with language labels (\`\`\`python, \`\`\`html, \`\`\`javascript)
149
- - Explain code clearly, step by step
150
- - Solve math problems with clear notation, show all steps
151
- - Are honest about uncertainty — never fabricate facts
152
- - For long answers, use clear sections with headers
153
- - When generating HTML/React/web apps, make them complete and beautiful
154
-
155
- You have web search capability when enabled. Use it to provide accurate, up-to-date information.`;
156
-
157
- // ─── WEB SEARCH (DuckDuckGo, no key) ─────────────────────────────────────────
158
  async function webSearch(query) {
159
  try {
160
- const r = await fetch(`https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_redirect=1&no_html=1`, {
161
- headers: { 'User-Agent': 'Mozilla/5.0 Fable-AI/2.0' },
162
- signal: AbortSignal.timeout(8000)
163
- });
164
  const d = await r.json();
165
  const results = [];
166
  if (d.AbstractText) results.push({ title: d.Heading || query, snippet: d.AbstractText, url: d.AbstractURL });
167
- (d.RelatedTopics || []).slice(0, 4).forEach(t => {
168
  if (t.Text) results.push({ title: t.Text.slice(0, 60), snippet: t.Text, url: t.FirstURL || '' });
169
  });
170
  return results;
171
  } catch { return []; }
172
  }
173
 
174
- // ─── STREAM: OpenAI-compatible ───────────────────────────────────────────────
175
- async function* streamOpenAI(baseURL, apiKey, model, messages, maxTokens, isOpenRouter) {
176
  const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` };
177
- if (isOpenRouter) { headers['HTTP-Referer'] = 'https://ejdjdososs-fable-ai.hf.space'; headers['X-Title'] = 'Fable AI'; }
178
  const resp = await fetch(`${baseURL}/chat/completions`, {
179
  method: 'POST', headers,
180
  body: JSON.stringify({ model, messages, max_tokens: maxTokens || 4096, stream: true, temperature: 0.7 }),
181
  signal: AbortSignal.timeout(120000)
182
  });
183
- if (!resp.ok) { const e = await resp.text(); throw new Error(`Provider ${resp.status}: ${e.slice(0,200)}`); }
184
  const reader = resp.body.getReader();
185
  const dec = new TextDecoder();
186
  let buf = '';
@@ -201,7 +236,7 @@ async function* streamOpenAI(baseURL, apiKey, model, messages, maxTokens, isOpen
201
  }
202
  }
203
 
204
- // ─── STREAM: HF Inference ────────────────────────────────────────────────────
205
  async function* streamHF(modelId, messages, token) {
206
  const { HfInference } = await import('@huggingface/inference');
207
  const hf = new HfInference(token || undefined);
@@ -222,7 +257,7 @@ async function* streamHF(modelId, messages, token) {
222
  } else {
223
  const t = buf.indexOf('<');
224
  if (t === -1) { yield { type: inThink ? 'thinking' : 'content', text: buf }; buf = ''; }
225
- else if (t > 0) { yield { type: inThink ? 'thinking' : 'content', text: buf.slice(0,t) }; buf = buf.slice(t); }
226
  break;
227
  }
228
  }
@@ -230,9 +265,29 @@ async function* streamHF(modelId, messages, token) {
230
  if (buf) yield { type: 'content', text: buf };
231
  }
232
 
233
- // ─── STREAM: Local llama.cpp ──────────────────────────────────────────────────
234
- async function* streamLocal(messages) {
235
- yield* streamOpenAI('http://127.0.0.1:8080/v1', 'local', 'tinyllama', messages, 2048, false);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  }
237
 
238
  // ─── EXPRESS ──────────────────────────────────────────────────────────────────
@@ -241,50 +296,64 @@ app.use(cors());
241
  app.use(express.json({ limit: '50mb' }));
242
  app.use(express.static(join(__dirname, 'dist')));
243
 
 
244
  app.get('/api/status', (req, res) => {
245
- res.json({ ok: true, activeProvider: getActiveProvider(), localModel: localModelReady, localLlama: localLlamaReady });
 
 
 
 
 
 
246
  });
247
 
 
248
  app.get('/api/models', (req, res) => {
249
  const active = getActiveProvider();
250
  const models = [];
251
  for (const [pid, prov] of Object.entries(PROVIDERS)) {
252
- let avail = false;
253
- if (pid === 'hf_free') avail = true; // Always available
254
- else if (pid === 'local') avail = localLlamaReady;
255
- else if (pid === 'hf') avail = true; // Anon mode fallback
256
  else avail = !!prov.key;
257
-
258
  for (const m of prov.models) {
259
- const modelId = m.id.includes('::') ? m.id : `${pid}::${m.id}`;
260
  models.push({
261
  id: modelId, name: m.name, badge: m.badge || null,
262
  provider: prov.name, providerId: pid,
263
  available: avail, reasoning: !!m.reasoning, local: !!m.local,
264
- maxTokens: m.maxTokens, recommended: pid === active,
265
- alwaysFree: !!m.alwaysFree
266
  });
267
  }
268
  }
269
- res.json({ models, activeProvider: active, providerName: PROVIDERS[active]?.name, localReady: localLlamaReady, localDownloaded: localModelReady });
 
 
 
 
 
 
270
  });
271
 
 
272
  app.get('/api/providers', (req, res) => {
273
  const active = getActiveProvider();
274
  res.json(Object.entries(PROVIDERS).map(([id, p]) => ({
275
  id, name: p.name, description: p.description || '', active: id === active,
276
- available: id === 'hf_free' ? true : id === 'local' ? localLlamaReady : !!p.key
277
  })));
278
  });
279
 
280
- // Conversations CRUD
281
  app.get('/api/conversations', (req, res) => {
282
  const { search, starred } = req.query;
283
  let sql = 'SELECT id,title,model,provider,starred,created_at,updated_at FROM conversations';
284
- const p = [], conds = [];
285
- if (search) { conds.push("title LIKE ?"); p.push(`%${search}%`); }
286
- if (starred === '1') conds.push("starred = 1");
287
- if (conds.length) sql += ' WHERE ' + conds.join(' AND ');
288
  sql += ' ORDER BY updated_at DESC LIMIT 100';
289
  res.json(db.prepare(sql).all(...p));
290
  });
@@ -297,8 +366,7 @@ app.post('/api/conversations', (req, res) => {
297
  app.get('/api/conversations/:id', (req, res) => {
298
  const conv = db.prepare('SELECT * FROM conversations WHERE id=?').get(req.params.id);
299
  if (!conv) return res.status(404).json({ error: 'Not found' });
300
- const msgs = db.prepare('SELECT * FROM messages WHERE conversation_id=? ORDER BY id').all(req.params.id);
301
- res.json({ ...conv, messages: msgs });
302
  });
303
 
304
  app.patch('/api/conversations/:id', (req, res) => {
@@ -316,11 +384,10 @@ app.patch('/api/conversations/:id', (req, res) => {
316
 
317
  app.delete('/api/conversations/:id', (req, res) => {
318
  const r = db.prepare('DELETE FROM conversations WHERE id=?').run(req.params.id);
319
- if (r.changes === 0) return res.status(404).json({ error: 'Not found' });
320
- res.status(204).end();
321
  });
322
 
323
- // ─── STREAM CHAT ──────────────────────────────────────────────────────────────
324
  app.post('/api/conversations/:id/messages', async (req, res) => {
325
  const convId = parseInt(req.params.id);
326
  const conv = db.prepare('SELECT * FROM conversations WHERE id=?').get(convId);
@@ -330,12 +397,11 @@ app.post('/api/conversations/:id/messages', async (req, res) => {
330
  const text = (content || '').trim();
331
  if (!text && !images?.length) return res.status(400).json({ error: 'Content required' });
332
 
333
- // Parse "providerId::modelId"
334
  let providerId, modelId;
335
- if (modelParam && modelParam.includes('::')) {
336
- const parts = modelParam.split('::');
337
- providerId = parts[0];
338
- modelId = parts.slice(1).join('::');
339
  } else {
340
  providerId = getActiveProvider();
341
  modelId = PROVIDERS[providerId]?.models[0]?.id || '';
@@ -345,11 +411,8 @@ app.post('/api/conversations/:id/messages', async (req, res) => {
345
 
346
  // Save user message
347
  db.prepare('INSERT INTO messages (conversation_id,role,content,images) VALUES (?,?,?,?)').run(convId, 'user', text, images?.length ? JSON.stringify(images) : null);
348
- if (conv.title === 'New Chat' && text) {
349
- db.prepare("UPDATE conversations SET title=?,updated_at=datetime('now') WHERE id=?").run(text.slice(0,55), convId);
350
- } else {
351
- db.prepare("UPDATE conversations SET updated_at=datetime('now') WHERE id=?").run(convId);
352
- }
353
  db.prepare('UPDATE conversations SET model=?,provider=? WHERE id=?').run(modelId, providerId, convId);
354
 
355
  // Load history
@@ -359,19 +422,18 @@ app.post('/api/conversations/:id/messages', async (req, res) => {
359
  let searchResults = [], augText = text;
360
  if (useSearch && text) {
361
  searchResults = await webSearch(text);
362
- if (searchResults.length > 0) {
363
- const ctx = searchResults.map((r,i) => `[${i+1}] **${r.title}**: ${r.snippet}`).join('\n\n');
364
  augText = `${text}\n\n---\n**Web Search Results:**\n${ctx}`;
365
  }
366
  }
367
 
368
- // Build messages
369
  const chatMsgs = [{ role: 'system', content: SYSTEM_PROMPT }];
370
- for (const m of history.slice(0,-1)) chatMsgs.push({ role: m.role, content: m.content });
371
  if (images?.length) {
372
- const parts = [];
373
- if (augText) parts.push({ type: 'text', text: augText });
374
- images.slice(0,4).forEach(img => parts.push({ type: 'image_url', image_url: { url: img.data } }));
375
  chatMsgs.push({ role: 'user', content: parts });
376
  } else {
377
  chatMsgs.push({ role: 'user', content: augText });
@@ -382,21 +444,18 @@ app.post('/api/conversations/:id/messages', async (req, res) => {
382
  res.setHeader('Cache-Control', 'no-cache');
383
  res.setHeader('Connection', 'keep-alive');
384
  res.setHeader('X-Accel-Buffering', 'no');
385
-
386
  const send = d => { try { res.write(`data: ${JSON.stringify(d)}\n\n`); } catch {} };
387
 
388
  send({ provider: prov?.name, providerId, model: modelId, localModel: providerId === 'local' });
389
- if (searchResults.length > 0) send({ searchResults });
390
 
391
  let fullContent = '', fullThinking = '';
392
-
393
  try {
394
  let stream;
395
  if (providerId === 'local') {
396
- if (!localLlamaReady) throw new Error('Local model not ready yet — it is being downloaded in background. Try again in a few minutes.');
397
- stream = streamLocal(chatMsgs);
398
  } else if (providerId === 'hf_free') {
399
- stream = streamHF(modelId.replace('hf_free::', ''), chatMsgs, null); // anonymous
400
  } else if (providerId === 'hf') {
401
  stream = streamHF(modelId, chatMsgs, prov.key);
402
  } else {
@@ -409,9 +468,10 @@ app.post('/api/conversations/:id/messages', async (req, res) => {
409
  if (ev.type === 'thinking') { fullThinking += ev.text; send({ thinking: ev.text }); }
410
  }
411
 
412
- db.prepare('INSERT INTO messages (conversation_id,role,content,thinking,search_results,provider_used,model_used) VALUES (?,?,?,?,?,?,?)')
413
- .run(convId, 'assistant', fullContent, fullThinking || null, searchResults.length ? JSON.stringify(searchResults) : null, providerId, modelId);
414
-
 
415
  send({ done: true });
416
  res.end();
417
  } catch (err) {
@@ -420,11 +480,13 @@ app.post('/api/conversations/:id/messages', async (req, res) => {
420
  }
421
  });
422
 
 
423
  app.get('/api/search', async (req, res) => {
424
  if (!req.query.q) return res.status(400).json({ error: 'q required' });
425
  res.json(await webSearch(req.query.q));
426
  });
427
 
 
428
  app.get('*', (req, res) => {
429
  if (req.path.startsWith('/api')) return res.status(404).json({ error: 'Not found' });
430
  res.sendFile(join(__dirname, 'dist', 'index.html'));
@@ -433,6 +495,4 @@ app.get('*', (req, res) => {
433
  const PORT = parseInt(process.env.PORT || '7860');
434
  app.listen(PORT, '0.0.0.0', () => {
435
  console.log(`✨ Fable AI v2 — port ${PORT} — provider: ${getActiveProvider()}`);
436
- console.log(` Local model file: ${localModelReady ? 'YES' : 'Downloading...'}`);
437
- console.log(` Local llama.cpp: ${localLlamaReady ? 'READY' : 'Waiting...'}`);
438
  });
 
4
  import { fileURLToPath } from 'url';
5
  import { dirname, join } from 'path';
6
  import fs from 'fs';
7
+ import { createWriteStream } from 'fs';
8
 
9
  const require = createRequire(import.meta.url);
10
  const Database = require('better-sqlite3');
 
39
  CREATE INDEX IF NOT EXISTS idx_conv_upd ON conversations(updated_at DESC);
40
  `);
41
 
42
+ // ─── LOCAL MODEL (node-llama-cpp, no Python needed) ──────────────────────────
43
  const LOCAL_MODEL_PATH = '/app/models/local.gguf';
44
+ const LOCAL_MODEL_URL = 'https://huggingface.co/TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF/resolve/main/tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf';
 
45
 
46
+ let localModel = null;
47
+ let localContext = null;
48
+ let localModelReady = false;
49
+ let localModelDownloading = false;
50
+ let localModelError = null;
51
+
52
+ async function downloadModel() {
53
+ if (localModelDownloading || localModelReady) return;
54
+ if (fs.existsSync(LOCAL_MODEL_PATH) && fs.statSync(LOCAL_MODEL_PATH).size > 100_000_000) {
55
+ await loadLocalModel();
56
+ return;
57
+ }
58
+ console.log('[local] Downloading TinyLlama GGUF model (~637MB)...');
59
+ localModelDownloading = true;
60
  try {
61
+ const resp = await fetch(LOCAL_MODEL_URL, {
62
+ headers: { 'User-Agent': 'Fable-AI/2.0' }
63
+ });
64
+ if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
65
+ const ws = createWriteStream(LOCAL_MODEL_PATH + '.tmp');
66
+ const reader = resp.body.getReader();
67
+ let downloaded = 0;
68
+ while (true) {
69
+ const { done, value } = await reader.read();
70
+ if (done) break;
71
+ ws.write(value);
72
+ downloaded += value.length;
73
+ if (downloaded % (50 * 1024 * 1024) < value.length) {
74
+ console.log(`[local] Downloaded: ${Math.round(downloaded / 1024 / 1024)}MB`);
75
+ }
76
+ }
77
+ await new Promise((res, rej) => ws.end(err => err ? rej(err) : res()));
78
+ fs.renameSync(LOCAL_MODEL_PATH + '.tmp', LOCAL_MODEL_PATH);
79
+ console.log('[local] Download complete! Loading model...');
80
+ await loadLocalModel();
81
+ } catch (err) {
82
+ localModelDownloading = false;
83
+ localModelError = err.message;
84
+ console.error('[local] Download failed:', err.message);
85
+ }
86
  }
87
 
88
+ async function loadLocalModel() {
89
+ try {
90
+ const { getLlama, LlamaModel, LlamaContext, LlamaChatSession } = await import('node-llama-cpp');
91
+ const llama = await getLlama();
92
+ localModel = await llama.loadModel({ modelPath: LOCAL_MODEL_PATH });
93
+ localContext = await localModel.createContext({ contextSize: 4096 });
94
  localModelReady = true;
95
+ localModelDownloading = false;
96
+ console.log('[local] ✅ TinyLlama ready for inference!');
97
+ } catch (err) {
98
+ localModelError = `node-llama-cpp: ${err.message}`;
99
+ localModelDownloading = false;
100
+ console.error('[local] Load failed:', err.message);
101
  }
 
102
  }
103
+
104
+ // Start background download after server starts
105
+ setTimeout(() => downloadModel().catch(console.error), 3000);
106
 
107
  // ─── PROVIDERS ────────────────────────────────────────────────────────────────
108
  const PROVIDERS = {
109
+ local: {
110
+ name: '💻 Local (TinyLlama 1.1B)',
111
+ description: 'Runs entirely on this server — zero API key',
 
112
  models: [
113
+ { id: 'tinyllama', name: '💻 TinyLlama 1.1B · Local · No API Key', maxTokens: 2048, reasoning: false, badge: 'LOCAL', local: true }
 
114
  ]
115
  },
116
+ hf_free: {
117
+ name: '🆓 HF Free (No Key)',
118
+ description: 'HuggingFace anonymous — no API key needed',
 
119
  models: [
120
+ { id: 'mistralai/Mistral-7B-Instruct-v0.3', name: '🆓 Mistral 7B · No Key Needed', maxTokens: 4096, badge: 'FREE' },
121
+ { id: 'HuggingFaceH4/zephyr-7b-beta', name: '🆓 Zephyr 7B · No Key Needed', maxTokens: 4096, badge: 'FREE' },
122
  ]
123
  },
124
  groq: {
125
  name: '⚡ Groq',
126
+ description: 'Free — Llama/DeepSeek at 500 tokens/sec',
127
  baseURL: 'https://api.groq.com/openai/v1',
128
  key: process.env.GROQ_API_KEY,
129
  models: [
130
+ { id: 'llama-3.3-70b-versatile', name: '⚡ Llama 3.3 70B · Groq', maxTokens: 32768, badge: 'FAST' },
131
  { id: 'deepseek-r1-distill-llama-70b', name: '⚡🧠 DeepSeek R1 70B · Groq', maxTokens: 32768, reasoning: true, badge: 'REASON' },
132
+ { id: 'meta-llama/llama-4-scout-17b-16e-instruct', name: '⚡ Llama 4 Scout 17B · Groq', maxTokens: 131072, badge: 'FAST' },
133
  { id: 'qwen-qwq-32b', name: '⚡🧠 QwQ 32B · Groq', maxTokens: 32768, reasoning: true, badge: 'REASON' },
134
  ]
135
  },
 
139
  baseURL: 'https://openrouter.ai/api/v1',
140
  key: process.env.OPENROUTER_API_KEY,
141
  models: [
142
+ { id: 'deepseek/deepseek-chat-v3-0324:free', name: '🆓 DeepSeek V3 · FREE', maxTokens: 16384, badge: 'FREE' },
143
+ { id: 'deepseek/deepseek-r1:free', name: '🆓🧠 DeepSeek R1 · FREE', maxTokens: 16384, reasoning: true, badge: 'FREE' },
144
+ { id: 'meta-llama/llama-3.3-70b-instruct:free', name: '🆓 Llama 3.3 70B · FREE', maxTokens: 8192, badge: 'FREE' },
145
+ { id: 'google/gemma-3-27b-it:free', name: '🆓 Gemma 3 27B · FREE', maxTokens: 8192, badge: 'FREE' },
146
+ { id: 'qwen/qwq-32b:free', name: '🆓🧠 QwQ 32B · FREE', maxTokens: 16384, reasoning: true, badge: 'FREE' },
147
  ]
148
  },
149
  together: {
 
152
  baseURL: 'https://api.together.xyz/v1',
153
  key: process.env.TOGETHER_API_KEY,
154
  models: [
155
+ { id: 'deepseek-ai/DeepSeek-V3', name: 'DeepSeek V3 · Together', maxTokens: 16384 },
156
  { id: 'deepseek-ai/DeepSeek-R1', name: '🧠 DeepSeek R1 · Together', maxTokens: 16384, reasoning: true },
157
+ { id: 'meta-llama/Llama-3.3-70B-Instruct-Turbo', name: 'Llama 3.3 70B Turbo · Together', maxTokens: 32768 },
158
  ]
159
  },
160
  hf: {
161
  name: '🤗 HuggingFace',
162
+ description: 'HF token — Llama 70B, Qwen 72B',
163
  key: process.env.HF_TOKEN,
164
  models: [
165
+ { id: 'meta-llama/Llama-3.3-70B-Instruct', name: 'Llama 3.3 70B · HuggingFace', maxTokens: 4096 },
166
+ { id: 'Qwen/Qwen2.5-72B-Instruct', name: 'Qwen 2.5 72B · HuggingFace', maxTokens: 4096 },
167
  { id: 'deepseek-ai/DeepSeek-R1-Distill-Qwen-32B', name: '🧠 DeepSeek R1 32B · HuggingFace', maxTokens: 4096, reasoning: true },
168
  ]
169
  }
170
  };
171
 
172
  function getActiveProvider() {
173
+ if (localModelReady) return 'local';
174
  if (process.env.GROQ_API_KEY) return 'groq';
175
  if (process.env.OPENROUTER_API_KEY) return 'openrouter';
176
  if (process.env.TOGETHER_API_KEY) return 'together';
 
180
 
181
  // ─── SYSTEM PROMPT ───────────────────────────────────────────────────────────
182
  const SYSTEM_PROMPT = `You are Fable, an advanced AI assistant comparable to Claude. You:
183
+ - Respond in the user's language (Arabic, English, or any other)
184
+ - Write well-structured markdown: headers (##, ###), **bold**, code blocks, tables, bullet lists
185
+ - ALWAYS use fenced code blocks with language labels (\`\`\`python, \`\`\`javascript, \`\`\`html, etc.)
186
+ - Explain code clearly with comments and step-by-step explanations
187
+ - Solve math problems showing all steps clearly
188
+ - Be honest — say when uncertain, never make up facts
189
+ - For HTML/React/web apps: generate complete, beautiful, runnable code
190
+ - For long responses: use clear sections with headers`;
191
+
192
+ // ─── WEB SEARCH ───────────────────────────────────────────────────────────────
 
 
193
  async function webSearch(query) {
194
  try {
195
+ const r = await fetch(
196
+ `https://api.duckduckgo.com/?q=${encodeURIComponent(query)}&format=json&no_redirect=1&no_html=1`,
197
+ { headers: { 'User-Agent': 'Mozilla/5.0 Fable-AI/2.0' }, signal: AbortSignal.timeout(6000) }
198
+ );
199
  const d = await r.json();
200
  const results = [];
201
  if (d.AbstractText) results.push({ title: d.Heading || query, snippet: d.AbstractText, url: d.AbstractURL });
202
+ (d.RelatedTopics || []).slice(0, 5).forEach(t => {
203
  if (t.Text) results.push({ title: t.Text.slice(0, 60), snippet: t.Text, url: t.FirstURL || '' });
204
  });
205
  return results;
206
  } catch { return []; }
207
  }
208
 
209
+ // ─── STREAM: OpenAI API ───────────────────────────────────────────────────────
210
+ async function* streamOpenAI(baseURL, apiKey, model, messages, maxTokens, isOR) {
211
  const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` };
212
+ if (isOR) { headers['HTTP-Referer'] = 'https://ejdjdososs-fable-ai.hf.space'; headers['X-Title'] = 'Fable AI'; }
213
  const resp = await fetch(`${baseURL}/chat/completions`, {
214
  method: 'POST', headers,
215
  body: JSON.stringify({ model, messages, max_tokens: maxTokens || 4096, stream: true, temperature: 0.7 }),
216
  signal: AbortSignal.timeout(120000)
217
  });
218
+ if (!resp.ok) { const e = await resp.text(); throw new Error(`${resp.status}: ${e.slice(0,200)}`); }
219
  const reader = resp.body.getReader();
220
  const dec = new TextDecoder();
221
  let buf = '';
 
236
  }
237
  }
238
 
239
+ // ─── STREAM: HF Inference ─────────────────────────────────────────────────────
240
  async function* streamHF(modelId, messages, token) {
241
  const { HfInference } = await import('@huggingface/inference');
242
  const hf = new HfInference(token || undefined);
 
257
  } else {
258
  const t = buf.indexOf('<');
259
  if (t === -1) { yield { type: inThink ? 'thinking' : 'content', text: buf }; buf = ''; }
260
+ else if (t > 0) { yield { type: inThink ? 'thinking' : 'content', text: buf.slice(0, t) }; buf = buf.slice(t); }
261
  break;
262
  }
263
  }
 
265
  if (buf) yield { type: 'content', text: buf };
266
  }
267
 
268
+ // ─── STREAM: Local (node-llama-cpp) ──────────────────────────────────────────
269
+ async function* streamLocalModel(messages) {
270
+ if (!localModelReady || !localContext) throw new Error('Local model not ready');
271
+ const { LlamaChatSession } = await import('node-llama-cpp');
272
+ const session = new LlamaChatSession({ contextSequence: await localContext.getSequence() });
273
+ // Build prompt from messages
274
+ const sysMsg = messages.find(m => m.role === 'system')?.content || '';
275
+ const history = messages.filter(m => m.role !== 'system');
276
+ // Feed history
277
+ for (let i = 0; i < history.length - 1; i += 2) {
278
+ if (history[i]?.role === 'user' && history[i+1]?.role === 'assistant') {
279
+ await session.prompt(history[i].content, { maxTokens: 1 });
280
+ }
281
+ }
282
+ const lastUser = history.filter(m => m.role === 'user').pop()?.content || '';
283
+ let buffer = '';
284
+ await session.prompt(lastUser, {
285
+ maxTokens: 2048,
286
+ onTextChunk: (chunk) => {
287
+ buffer += chunk;
288
+ }
289
+ });
290
+ yield { type: 'content', text: buffer };
291
  }
292
 
293
  // ─── EXPRESS ──────────────────────────────────────────────────────────────────
 
296
  app.use(express.json({ limit: '50mb' }));
297
  app.use(express.static(join(__dirname, 'dist')));
298
 
299
+ // Status
300
  app.get('/api/status', (req, res) => {
301
+ res.json({
302
+ ok: true,
303
+ activeProvider: getActiveProvider(),
304
+ localModel: localModelReady,
305
+ localDownloading: localModelDownloading,
306
+ localError: localModelError
307
+ });
308
  });
309
 
310
+ // Models
311
  app.get('/api/models', (req, res) => {
312
  const active = getActiveProvider();
313
  const models = [];
314
  for (const [pid, prov] of Object.entries(PROVIDERS)) {
315
+ let avail;
316
+ if (pid === 'local') avail = localModelReady;
317
+ else if (pid === 'hf_free') avail = true;
318
+ else if (pid === 'hf') avail = true;
319
  else avail = !!prov.key;
320
+
321
  for (const m of prov.models) {
322
+ const modelId = `${pid}::${m.id}`;
323
  models.push({
324
  id: modelId, name: m.name, badge: m.badge || null,
325
  provider: prov.name, providerId: pid,
326
  available: avail, reasoning: !!m.reasoning, local: !!m.local,
327
+ maxTokens: m.maxTokens || 4096, recommended: pid === active,
 
328
  });
329
  }
330
  }
331
+ res.json({
332
+ models,
333
+ activeProvider: active,
334
+ providerName: PROVIDERS[active]?.name,
335
+ localReady: localModelReady,
336
+ localDownloading: localModelDownloading,
337
+ });
338
  });
339
 
340
+ // Providers
341
  app.get('/api/providers', (req, res) => {
342
  const active = getActiveProvider();
343
  res.json(Object.entries(PROVIDERS).map(([id, p]) => ({
344
  id, name: p.name, description: p.description || '', active: id === active,
345
+ available: id === 'hf_free' ? true : id === 'local' ? localModelReady : !!p.key
346
  })));
347
  });
348
 
349
+ // ─── CONVERSATIONS ────────────────────────────────────────────────────────────
350
  app.get('/api/conversations', (req, res) => {
351
  const { search, starred } = req.query;
352
  let sql = 'SELECT id,title,model,provider,starred,created_at,updated_at FROM conversations';
353
+ const p = [], c = [];
354
+ if (search) { c.push("title LIKE ?"); p.push(`%${search}%`); }
355
+ if (starred === '1') c.push("starred=1");
356
+ if (c.length) sql += ' WHERE ' + c.join(' AND ');
357
  sql += ' ORDER BY updated_at DESC LIMIT 100';
358
  res.json(db.prepare(sql).all(...p));
359
  });
 
366
  app.get('/api/conversations/:id', (req, res) => {
367
  const conv = db.prepare('SELECT * FROM conversations WHERE id=?').get(req.params.id);
368
  if (!conv) return res.status(404).json({ error: 'Not found' });
369
+ res.json({ ...conv, messages: db.prepare('SELECT * FROM messages WHERE conversation_id=? ORDER BY id').all(req.params.id) });
 
370
  });
371
 
372
  app.patch('/api/conversations/:id', (req, res) => {
 
384
 
385
  app.delete('/api/conversations/:id', (req, res) => {
386
  const r = db.prepare('DELETE FROM conversations WHERE id=?').run(req.params.id);
387
+ r.changes === 0 ? res.status(404).json({ error: 'Not found' }) : res.status(204).end();
 
388
  });
389
 
390
+ // ─── CHAT (SSE STREAM) ────────────────────────────────────────────────────────
391
  app.post('/api/conversations/:id/messages', async (req, res) => {
392
  const convId = parseInt(req.params.id);
393
  const conv = db.prepare('SELECT * FROM conversations WHERE id=?').get(convId);
 
397
  const text = (content || '').trim();
398
  if (!text && !images?.length) return res.status(400).json({ error: 'Content required' });
399
 
400
+ // Parse provider::modelId
401
  let providerId, modelId;
402
+ if (modelParam?.includes('::')) {
403
+ [providerId, ...rest] = modelParam.split('::');
404
+ modelId = rest.join('::');
 
405
  } else {
406
  providerId = getActiveProvider();
407
  modelId = PROVIDERS[providerId]?.models[0]?.id || '';
 
411
 
412
  // Save user message
413
  db.prepare('INSERT INTO messages (conversation_id,role,content,images) VALUES (?,?,?,?)').run(convId, 'user', text, images?.length ? JSON.stringify(images) : null);
414
+ if (conv.title === 'New Chat' && text) db.prepare("UPDATE conversations SET title=?,updated_at=datetime('now') WHERE id=?").run(text.slice(0, 55), convId);
415
+ else db.prepare("UPDATE conversations SET updated_at=datetime('now') WHERE id=?").run(convId);
 
 
 
416
  db.prepare('UPDATE conversations SET model=?,provider=? WHERE id=?').run(modelId, providerId, convId);
417
 
418
  // Load history
 
422
  let searchResults = [], augText = text;
423
  if (useSearch && text) {
424
  searchResults = await webSearch(text);
425
+ if (searchResults.length) {
426
+ const ctx = searchResults.map((r, i) => `[${i+1}] **${r.title}**: ${r.snippet}`).join('\n\n');
427
  augText = `${text}\n\n---\n**Web Search Results:**\n${ctx}`;
428
  }
429
  }
430
 
431
+ // Build messages array
432
  const chatMsgs = [{ role: 'system', content: SYSTEM_PROMPT }];
433
+ for (const m of history.slice(0, -1)) chatMsgs.push({ role: m.role, content: m.content });
434
  if (images?.length) {
435
+ const parts = [{ type: 'text', text: augText }];
436
+ images.slice(0, 4).forEach(img => parts.push({ type: 'image_url', image_url: { url: img.data } }));
 
437
  chatMsgs.push({ role: 'user', content: parts });
438
  } else {
439
  chatMsgs.push({ role: 'user', content: augText });
 
444
  res.setHeader('Cache-Control', 'no-cache');
445
  res.setHeader('Connection', 'keep-alive');
446
  res.setHeader('X-Accel-Buffering', 'no');
 
447
  const send = d => { try { res.write(`data: ${JSON.stringify(d)}\n\n`); } catch {} };
448
 
449
  send({ provider: prov?.name, providerId, model: modelId, localModel: providerId === 'local' });
450
+ if (searchResults.length) send({ searchResults });
451
 
452
  let fullContent = '', fullThinking = '';
 
453
  try {
454
  let stream;
455
  if (providerId === 'local') {
456
+ stream = streamLocalModel(chatMsgs);
 
457
  } else if (providerId === 'hf_free') {
458
+ stream = streamHF(modelId, chatMsgs, null);
459
  } else if (providerId === 'hf') {
460
  stream = streamHF(modelId, chatMsgs, prov.key);
461
  } else {
 
468
  if (ev.type === 'thinking') { fullThinking += ev.text; send({ thinking: ev.text }); }
469
  }
470
 
471
+ db.prepare('INSERT INTO messages (conversation_id,role,content,thinking,search_results,provider_used,model_used) VALUES (?,?,?,?,?,?,?)').run(
472
+ convId, 'assistant', fullContent, fullThinking || null,
473
+ searchResults.length ? JSON.stringify(searchResults) : null, providerId, modelId
474
+ );
475
  send({ done: true });
476
  res.end();
477
  } catch (err) {
 
480
  }
481
  });
482
 
483
+ // Web search endpoint
484
  app.get('/api/search', async (req, res) => {
485
  if (!req.query.q) return res.status(400).json({ error: 'q required' });
486
  res.json(await webSearch(req.query.q));
487
  });
488
 
489
+ // SPA fallback
490
  app.get('*', (req, res) => {
491
  if (req.path.startsWith('/api')) return res.status(404).json({ error: 'Not found' });
492
  res.sendFile(join(__dirname, 'dist', 'index.html'));
 
495
  const PORT = parseInt(process.env.PORT || '7860');
496
  app.listen(PORT, '0.0.0.0', () => {
497
  console.log(`✨ Fable AI v2 — port ${PORT} — provider: ${getActiveProvider()}`);
 
 
498
  });