AxionLabsAI commited on
Commit
bee0d6d
Β·
verified Β·
1 Parent(s): e2b9274

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +426 -0
app.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import time
4
+ import uuid
5
+ import asyncio
6
+ import threading
7
+ import queue as queue_mod
8
+ import gradio as gr
9
+ from fastapi import Request
10
+ from fastapi.responses import StreamingResponse, JSONResponse
11
+ from huggingface_hub import hf_hub_download
12
+ import spaces
13
+ from llama_cpp import Llama
14
+
15
+ HF_TOKEN = os.environ.get("HF_TOKEN")
16
+ MODEL_PATH = "/tmp/lumen-dpo.gguf"
17
+ MEMORY_FILE = "/tmp/memories.json"
18
+
19
+ SYSTEM_PROMPT = (
20
+ """
21
+ You are Lumen, an AI assistant made by Axion Labs. You're helpful, direct, and honest.
22
+ - Answer questions clearly and concisely. Don't over-explain.
23
+ - If you don't know something, say so β€” don't guess and present it as fact.
24
+ - Refuse requests that would harm people, violate privacy, or involve illegal activity.
25
+ """
26
+ )
27
+
28
+ llm = None
29
+ infer_lock = threading.Lock()
30
+
31
+
32
+ # ── Memory ────────────────────────────────────────────────────────────────────
33
+
34
+ def _load_memories():
35
+ try:
36
+ if not os.path.exists(MEMORY_FILE):
37
+ return []
38
+ with open(MEMORY_FILE) as f:
39
+ return json.load(f)
40
+ except Exception:
41
+ return []
42
+
43
+
44
+ def _save_memories(memories):
45
+ try:
46
+ with open(MEMORY_FILE, "w") as f:
47
+ json.dump(memories, f, indent=2)
48
+ except Exception:
49
+ pass
50
+
51
+
52
+ def get_memories():
53
+ return _load_memories()
54
+
55
+
56
+ def add_memory(text):
57
+ memories = _load_memories()
58
+ memories.append({"text": text.strip(), "addedAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())})
59
+ _save_memories(memories)
60
+ return memories
61
+
62
+
63
+ def remove_all_memories():
64
+ _save_memories([])
65
+
66
+
67
+ def remove_memory_by_index(index):
68
+ memories = _load_memories()
69
+ if 0 <= index < len(memories):
70
+ memories.pop(index)
71
+ _save_memories(memories)
72
+ return True
73
+ return False
74
+
75
+
76
+ def build_system_prompt():
77
+ memories = get_memories()
78
+ prompt = SYSTEM_PROMPT
79
+ if memories:
80
+ notes = "\n".join(f"- {m['text']}" for m in memories)
81
+ prompt += f"\n\nPersistent notes (always keep in mind):\n{notes}"
82
+ return prompt
83
+
84
+
85
+ def memories_display_text():
86
+ memories = get_memories()
87
+ if not memories:
88
+ return "No memories saved."
89
+ return "\n".join(f"{i + 1}. {m['text']}" for i, m in enumerate(memories))
90
+
91
+
92
+ # ── Model loading ─────────────────────────────────────────────────────────────
93
+
94
+ def _load_model():
95
+ global llm
96
+ if not os.path.exists(MODEL_PATH):
97
+ print("Downloading Lumen DPO model\u2026")
98
+ hf_hub_download(
99
+ repo_id = "RavikxxBGamin/Lumen",
100
+ filename = "lumen-dpo.gguf",
101
+ token = HF_TOKEN,
102
+ local_dir = "/tmp",
103
+ )
104
+
105
+ print("Loading model\u2026")
106
+ llm = Llama(
107
+ model_path = MODEL_PATH,
108
+ n_ctx = 8192,
109
+ n_threads = 2,
110
+ verbose = False,
111
+ )
112
+ print("Model ready.")
113
+
114
+ # Start loading in background before Gradio builds UI
115
+ threading.Thread(target=_load_model, daemon=True).start()
116
+
117
+
118
+ # ── Gradio chat helpers ───────────────────────────────────────────────────────
119
+
120
+ def user_submit(message, history):
121
+ if not message.strip():
122
+ return "", history
123
+ return "", history + [{"role": "user", "content": message}]
124
+
125
+
126
+ @spaces.GPU
127
+ def bot_respond(history, temperature, max_tokens):
128
+ if llm is None:
129
+ yield history + [{"role": "assistant", "content": "Model is still loading β€” please wait a moment and try again."}]
130
+ return
131
+
132
+ messages = [{"role": "system", "content": build_system_prompt()}]
133
+ for item in history:
134
+ if not isinstance(item, dict):
135
+ continue
136
+ content = item.get("content", "")
137
+ if isinstance(content, list):
138
+ content = " ".join(p.get("text", "") for p in content if isinstance(p, dict))
139
+ messages.append({"role": item["role"], "content": content})
140
+
141
+ response = ""
142
+ working_history = history + [{"role": "assistant", "content": ""}]
143
+ with infer_lock:
144
+ for chunk in llm.create_chat_completion(
145
+ messages = messages,
146
+ max_tokens = int(max_tokens),
147
+ temperature = float(temperature),
148
+ stream = True,
149
+ ):
150
+ delta = chunk["choices"][0]["delta"].get("content", "")
151
+ response += delta
152
+ working_history[-1]["content"] = response
153
+ yield working_history
154
+
155
+
156
+ def model_status():
157
+ if llm is not None:
158
+ return "<p class='status ready'>● Model ready</p>"
159
+ return "<p class='status loading'>● Loading model… (first boot takes a few minutes)</p>"
160
+
161
+
162
+ def do_add_memory(text):
163
+ if not text.strip():
164
+ return "", memories_display_text()
165
+ add_memory(text.strip())
166
+ return "", memories_display_text()
167
+
168
+
169
+ def do_clear_memories():
170
+ remove_all_memories()
171
+ return memories_display_text()
172
+
173
+
174
+ # ── Gradio UI must be defined before API routes ──────────────────────────────
175
+
176
+ THEME = gr.themes.Base(
177
+ primary_hue = gr.themes.colors.orange,
178
+ secondary_hue = gr.themes.colors.stone,
179
+ neutral_hue = gr.themes.colors.stone,
180
+ font = [gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],
181
+ font_mono = [gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace"],
182
+ ).set(
183
+ body_background_fill = "#110d08",
184
+ body_background_fill_dark = "#110d08",
185
+ block_background_fill = "#1c1510",
186
+ block_background_fill_dark = "#1c1510",
187
+ block_border_color = "#2e2218",
188
+ block_border_color_dark = "#2e2218",
189
+ block_label_background_fill = "#1c1510",
190
+ block_label_background_fill_dark = "#1c1510",
191
+ input_background_fill = "#150f0a",
192
+ input_background_fill_dark = "#150f0a",
193
+ input_border_color = "#2e2218",
194
+ input_border_color_dark = "#2e2218",
195
+ button_primary_background_fill = "#cc785c",
196
+ button_primary_background_fill_hover = "#b8664a",
197
+ button_primary_background_fill_dark = "#cc785c",
198
+ button_primary_text_color = "#fff",
199
+ button_secondary_background_fill = "#2e2218",
200
+ button_secondary_background_fill_hover = "#3a2c1e",
201
+ button_secondary_background_fill_dark = "#2e2218",
202
+ button_secondary_text_color = "#d4b896",
203
+ body_text_color = "#e8ddd0",
204
+ body_text_color_dark = "#e8ddd0",
205
+ block_label_text_color = "#a08060",
206
+ block_label_text_color_dark = "#a08060",
207
+ )
208
+
209
+ CSS = """
210
+ .gradio-container { max-width: 820px !important; margin: 0 auto !important; padding: 0 12px !important; }
211
+ footer { display: none !important; }
212
+ #lumen-header { padding: 24px 0 8px; border-bottom: 1px solid #2e2218; margin-bottom: 16px; }
213
+ #lumen-header h1 { font-size: 1.6em; font-weight: 700; margin: 0 0 2px; color: #e8ddd0; letter-spacing: -0.01em; }
214
+ #lumen-header h1 span { color: #cc785c; }
215
+ #lumen-header p { color: #7a6050; margin: 0; font-size: 0.85em; }
216
+ .status { margin: 0 0 10px; font-size: 0.8em; font-weight: 500; }
217
+ .status.ready { color: #6aa87a; }
218
+ .status.loading { color: #c9994a; }
219
+ .chatbot-wrap .message.user { background: #2a1e14 !important; border: 1px solid #3a2c1e !important; }
220
+ .chatbot-wrap .message.bot { background: #1c1510 !important; border: 1px solid #2e2218 !important; }
221
+ .chatbot-wrap .message { border-radius: 8px !important; }
222
+ .input-row textarea {
223
+ background: #150f0a !important; border: 1px solid #3a2c1e !important;
224
+ border-radius: 8px !important; color: #e8ddd0 !important; resize: none !important;
225
+ }
226
+ .input-row textarea:focus { border-color: #cc785c !important; outline: none !important; }
227
+ .send-btn {
228
+ background: #cc785c !important; border: none !important;
229
+ border-radius: 8px !important; color: #fff !important;
230
+ font-size: 1.1em !important; min-width: 48px !important;
231
+ }
232
+ .send-btn:hover { background: #b8664a !important; }
233
+ .settings-row { margin: 10px 0 4px; gap: 16px; }
234
+ .settings-row label { color: #a08060 !important; font-size: 0.8em !important; }
235
+ .memory-panel { margin-top: 8px; border-top: 1px solid #2e2218; padding-top: 10px; }
236
+ .memory-panel .gr-accordion-header { color: #a08060 !important; font-size: 0.82em !important; }
237
+ .memory-list textarea {
238
+ font-size: 0.82em !important; color: #a08060 !important;
239
+ background: #110d08 !important; border: 1px solid #2e2218 !important; border-radius: 6px !important;
240
+ }
241
+ #lumen-footer { color: #4a3828; font-size: 0.75em; text-align: center; padding: 14px 0; border-top: 1px solid #2e2218; margin-top: 12px; }
242
+ #lumen-footer code { background: #1c1510; padding: 1px 5px; border-radius: 4px; color: #7a6050; }
243
+ """
244
+
245
+ with gr.Blocks(title="Lumen \u2014 Axion Labs") as demo:
246
+
247
+ gr.HTML("""
248
+ <div id="lumen-header">
249
+ <h1>\u269b <span>Lumen</span></h1>
250
+ <p>Fine-tuned Llama 3.1 8B \u00b7 by Axion Labs \u00b7 free, no key needed</p>
251
+ </div>
252
+ """)
253
+
254
+ status_html = gr.HTML(model_status)
255
+
256
+ chatbot = gr.Chatbot(
257
+ height = 440,
258
+ show_copy_button = True,
259
+ elem_classes = ["chatbot-wrap"],
260
+ label = "",
261
+ show_label = False,
262
+ bubble_full_width = False,
263
+ )
264
+
265
+ with gr.Row(elem_classes=["input-row"]):
266
+ msg_box = gr.Textbox(
267
+ placeholder = "Message Lumen\u2026",
268
+ show_label = False,
269
+ scale = 5,
270
+ container = False,
271
+ autofocus = True,
272
+ lines = 1,
273
+ max_lines = 6,
274
+ )
275
+ send_btn = gr.Button("\u2191", scale=1, variant="primary", elem_classes=["send-btn"], min_width=48)
276
+
277
+ with gr.Row(elem_classes=["settings-row"]):
278
+ temperature = gr.Slider(0.1, 1.5, value=0.7, step=0.1, label="Temperature", scale=1)
279
+ max_tokens = gr.Slider(64, 1024, value=512, step=64, label="Max tokens", scale=1)
280
+
281
+ with gr.Accordion("Memory", open=False, elem_classes=["memory-panel"]):
282
+ mem_display = gr.Textbox(
283
+ value = memories_display_text,
284
+ label = "",
285
+ lines = 4,
286
+ interactive = False,
287
+ show_copy_button = False,
288
+ elem_classes = ["memory-list"],
289
+ every = 10,
290
+ )
291
+ with gr.Row():
292
+ mem_input = gr.Textbox(placeholder="Add a memory\u2026", show_label=False, scale=3, container=False)
293
+ mem_add_btn = gr.Button("Save", scale=1, size="sm")
294
+ mem_clr_btn = gr.Button("Clear all", scale=1, size="sm", variant="stop")
295
+
296
+ gr.HTML("""
297
+ <div id="lumen-footer">
298
+ OpenAI-compatible API: <code>POST /v1/chat/completions</code>
299
+ &nbsp;\u00b7&nbsp; use with Axion CLI via <code>/model lumen</code>
300
+ </div>
301
+ """)
302
+
303
+ msg_box.submit(
304
+ user_submit, [msg_box, chatbot], [msg_box, chatbot], queue=False
305
+ ).then(
306
+ bot_respond, [chatbot, temperature, max_tokens], chatbot
307
+ )
308
+ send_btn.click(
309
+ user_submit, [msg_box, chatbot], [msg_box, chatbot], queue=False
310
+ ).then(
311
+ bot_respond, [chatbot, temperature, max_tokens], chatbot
312
+ )
313
+
314
+ mem_add_btn.click(do_add_memory, [mem_input], [mem_input, mem_display])
315
+ mem_input.submit(do_add_memory, [mem_input], [mem_input, mem_display])
316
+ mem_clr_btn.click(do_clear_memories, [], [mem_display])
317
+
318
+ demo.load(model_status, outputs=status_html)
319
+
320
+
321
+ # ── API routes mounted on Gradio's internal FastAPI ──────────────────────────
322
+ # (These must come AFTER the `with gr.Blocks() as demo:` block so demo.app exists)
323
+
324
+ @demo.app.get("/health")
325
+ def health():
326
+ return {"status": "ready" if llm is not None else "loading"}
327
+
328
+
329
+ @demo.app.get("/v1/memories")
330
+ def api_list_memories():
331
+ return {"memories": get_memories()}
332
+
333
+
334
+ @demo.app.post("/v1/memories")
335
+ async def api_add_memory(request: Request):
336
+ body = await request.json()
337
+ text = (body.get("text") or "").strip()
338
+ if not text:
339
+ return JSONResponse({"error": "text is required"}, status_code=400)
340
+ updated = add_memory(text)
341
+ return {"memories": updated}
342
+
343
+
344
+ @demo.app.delete("/v1/memories/{index}")
345
+ def api_delete_memory(index: int):
346
+ if remove_memory_by_index(index):
347
+ return {"memories": get_memories()}
348
+ return JSONResponse({"error": "index out of range"}, status_code=404)
349
+
350
+
351
+ @demo.app.post("/v1/chat/completions")
352
+ async def chat_completions(request: Request):
353
+ if llm is None:
354
+ return JSONResponse({"error": "Model is still loading, try again in a moment."}, status_code=503)
355
+
356
+ body = await request.json()
357
+ messages = body.get("messages", [])
358
+ max_tokens = int(body.get("max_tokens", 512))
359
+ temperature = float(body.get("temperature", 0.7))
360
+ stream = body.get("stream", False)
361
+ model_id = body.get("model", "lumen")
362
+ use_memories = body.get("use_memories", False)
363
+
364
+ sys_prompt = build_system_prompt() if use_memories else SYSTEM_PROMPT
365
+ if not any(m.get("role") == "system" for m in messages):
366
+ messages = [{"role": "system", "content": sys_prompt}] + messages
367
+
368
+ if stream:
369
+ async def event_stream():
370
+ resp_id = "chatcmpl-" + uuid.uuid4().hex
371
+ created = int(time.time())
372
+ q = queue_mod.Queue(maxsize=64)
373
+ DONE = object()
374
+
375
+ @spaces.GPU
376
+ def produce():
377
+ try:
378
+ with infer_lock:
379
+ for chunk in llm.create_chat_completion(
380
+ messages = messages,
381
+ max_tokens = max_tokens,
382
+ temperature = temperature,
383
+ stream = True,
384
+ ):
385
+ q.put(chunk)
386
+ except Exception as e:
387
+ q.put(e)
388
+ finally:
389
+ q.put(DONE)
390
+
391
+ threading.Thread(target=produce, daemon=True).start()
392
+ while True:
393
+ chunk = await asyncio.to_thread(q.get)
394
+ if chunk is DONE:
395
+ break
396
+ if isinstance(chunk, Exception):
397
+ yield f"data: {json.dumps({'error': str(chunk)})}\n\n"
398
+ break
399
+ delta = chunk["choices"][0]["delta"]
400
+ finish = chunk["choices"][0].get("finish_reason")
401
+ data = {
402
+ "id": resp_id,
403
+ "object": "chat.completion.chunk",
404
+ "created": created,
405
+ "model": model_id,
406
+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
407
+ }
408
+ yield f"data: {json.dumps(data)}\n\n"
409
+ yield "data: [DONE]\n\n"
410
+
411
+ return StreamingResponse(event_stream(), media_type="text/event-stream")
412
+
413
+ @spaces.GPU
414
+ def generate():
415
+ with infer_lock:
416
+ return llm.create_chat_completion(
417
+ messages = messages,
418
+ max_tokens = max_tokens,
419
+ temperature = temperature,
420
+ stream = False,
421
+ )
422
+
423
+ result = await asyncio.to_thread(generate)
424
+ return JSONResponse(result)
425
+
426
+ demo.launch(theme=THEME, css=CSS)