AxionLabsAI commited on
Commit
eb3fca1
Β·
verified Β·
1 Parent(s): 26e7453

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +424 -0
app.py ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ elem_classes = ["chatbot-wrap"],
259
+ label = "",
260
+ show_label = False,
261
+ )
262
+
263
+ with gr.Row(elem_classes=["input-row"]):
264
+ msg_box = gr.Textbox(
265
+ placeholder = "Message Lumen\u2026",
266
+ show_label = False,
267
+ scale = 5,
268
+ container = False,
269
+ autofocus = True,
270
+ lines = 1,
271
+ max_lines = 6,
272
+ )
273
+ send_btn = gr.Button("\u2191", scale=1, variant="primary", elem_classes=["send-btn"], min_width=48)
274
+
275
+ with gr.Row(elem_classes=["settings-row"]):
276
+ temperature = gr.Slider(0.1, 1.5, value=0.7, step=0.1, label="Temperature", scale=1)
277
+ max_tokens = gr.Slider(64, 1024, value=512, step=64, label="Max tokens", scale=1)
278
+
279
+ with gr.Accordion("Memory", open=False, elem_classes=["memory-panel"]):
280
+ mem_display = gr.Textbox(
281
+ value = memories_display_text,
282
+ label = "",
283
+ lines = 4,
284
+ interactive = False,
285
+ show_copy_button = False,
286
+ elem_classes = ["memory-list"],
287
+ every = 10,
288
+ )
289
+ with gr.Row():
290
+ mem_input = gr.Textbox(placeholder="Add a memory\u2026", show_label=False, scale=3, container=False)
291
+ mem_add_btn = gr.Button("Save", scale=1, size="sm")
292
+ mem_clr_btn = gr.Button("Clear all", scale=1, size="sm")
293
+
294
+ gr.HTML("""
295
+ <div id="lumen-footer">
296
+ OpenAI-compatible API: <code>POST /v1/chat/completions</code>
297
+ &nbsp;\u00b7&nbsp; use with Axion CLI via <code>/model lumen</code>
298
+ </div>
299
+ """)
300
+
301
+ msg_box.submit(
302
+ user_submit, [msg_box, chatbot], [msg_box, chatbot], queue=False
303
+ ).then(
304
+ bot_respond, [chatbot, temperature, max_tokens], chatbot
305
+ )
306
+ send_btn.click(
307
+ user_submit, [msg_box, chatbot], [msg_box, chatbot], queue=False
308
+ ).then(
309
+ bot_respond, [chatbot, temperature, max_tokens], chatbot
310
+ )
311
+
312
+ mem_add_btn.click(do_add_memory, [mem_input], [mem_input, mem_display])
313
+ mem_input.submit(do_add_memory, [mem_input], [mem_input, mem_display])
314
+ mem_clr_btn.click(do_clear_memories, [], [mem_display])
315
+
316
+ demo.load(model_status, outputs=status_html)
317
+
318
+
319
+ # ── API routes mounted on Gradio's internal FastAPI ──────────────────────────
320
+ # (These must come AFTER the `with gr.Blocks() as demo:` block so demo.app exists)
321
+
322
+ @demo.app.get("/health")
323
+ def health():
324
+ return {"status": "ready" if llm is not None else "loading"}
325
+
326
+
327
+ @demo.app.get("/v1/memories")
328
+ def api_list_memories():
329
+ return {"memories": get_memories()}
330
+
331
+
332
+ @demo.app.post("/v1/memories")
333
+ async def api_add_memory(request: Request):
334
+ body = await request.json()
335
+ text = (body.get("text") or "").strip()
336
+ if not text:
337
+ return JSONResponse({"error": "text is required"}, status_code=400)
338
+ updated = add_memory(text)
339
+ return {"memories": updated}
340
+
341
+
342
+ @demo.app.delete("/v1/memories/{index}")
343
+ def api_delete_memory(index: int):
344
+ if remove_memory_by_index(index):
345
+ return {"memories": get_memories()}
346
+ return JSONResponse({"error": "index out of range"}, status_code=404)
347
+
348
+
349
+ @demo.app.post("/v1/chat/completions")
350
+ async def chat_completions(request: Request):
351
+ if llm is None:
352
+ return JSONResponse({"error": "Model is still loading, try again in a moment."}, status_code=503)
353
+
354
+ body = await request.json()
355
+ messages = body.get("messages", [])
356
+ max_tokens = int(body.get("max_tokens", 512))
357
+ temperature = float(body.get("temperature", 0.7))
358
+ stream = body.get("stream", False)
359
+ model_id = body.get("model", "lumen")
360
+ use_memories = body.get("use_memories", False)
361
+
362
+ sys_prompt = build_system_prompt() if use_memories else SYSTEM_PROMPT
363
+ if not any(m.get("role") == "system" for m in messages):
364
+ messages = [{"role": "system", "content": sys_prompt}] + messages
365
+
366
+ if stream:
367
+ async def event_stream():
368
+ resp_id = "chatcmpl-" + uuid.uuid4().hex
369
+ created = int(time.time())
370
+ q = queue_mod.Queue(maxsize=64)
371
+ DONE = object()
372
+
373
+ @spaces.GPU
374
+ def produce():
375
+ try:
376
+ with infer_lock:
377
+ for chunk in llm.create_chat_completion(
378
+ messages = messages,
379
+ max_tokens = max_tokens,
380
+ temperature = temperature,
381
+ stream = True,
382
+ ):
383
+ q.put(chunk)
384
+ except Exception as e:
385
+ q.put(e)
386
+ finally:
387
+ q.put(DONE)
388
+
389
+ threading.Thread(target=produce, daemon=True).start()
390
+ while True:
391
+ chunk = await asyncio.to_thread(q.get)
392
+ if chunk is DONE:
393
+ break
394
+ if isinstance(chunk, Exception):
395
+ yield f"data: {json.dumps({'error': str(chunk)})}\n\n"
396
+ break
397
+ delta = chunk["choices"][0]["delta"]
398
+ finish = chunk["choices"][0].get("finish_reason")
399
+ data = {
400
+ "id": resp_id,
401
+ "object": "chat.completion.chunk",
402
+ "created": created,
403
+ "model": model_id,
404
+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
405
+ }
406
+ yield f"data: {json.dumps(data)}\n\n"
407
+ yield "data: [DONE]\n\n"
408
+
409
+ return StreamingResponse(event_stream(), media_type="text/event-stream")
410
+
411
+ @spaces.GPU
412
+ def generate():
413
+ with infer_lock:
414
+ return llm.create_chat_completion(
415
+ messages = messages,
416
+ max_tokens = max_tokens,
417
+ temperature = temperature,
418
+ stream = False,
419
+ )
420
+
421
+ result = await asyncio.to_thread(generate)
422
+ return JSONResponse(result)
423
+
424
+ demo.launch(theme=THEME, css=CSS)