AxionLabsAI commited on
Commit
5a2a5d5
Β·
verified Β·
1 Parent(s): 348fe26

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +420 -0
app.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 FastAPI, 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
+ threading.Thread(target=_load_model, daemon=True).start()
115
+
116
+
117
+ # ── Gradio chat helpers ───────────────────────────────────────────────────────
118
+
119
+ def user_submit(message, history):
120
+ if not message.strip():
121
+ return "", history
122
+ return "", history + [{"role": "user", "content": message}]
123
+
124
+
125
+ @spaces.GPU
126
+ def bot_respond(history, temperature, max_tokens):
127
+ if llm is None:
128
+ yield history + [{"role": "assistant", "content": "Model is still loading β€” please wait a moment and try again."}]
129
+ return
130
+
131
+ messages = [{"role": "system", "content": build_system_prompt()}]
132
+ for item in history:
133
+ if not isinstance(item, dict):
134
+ continue
135
+ content = item.get("content", "")
136
+ if isinstance(content, list):
137
+ content = " ".join(p.get("text", "") for p in content if isinstance(p, dict))
138
+ messages.append({"role": item["role"], "content": content})
139
+
140
+ response = ""
141
+ working_history = history + [{"role": "assistant", "content": ""}]
142
+ with infer_lock:
143
+ for chunk in llm.create_chat_completion(
144
+ messages = messages,
145
+ max_tokens = int(max_tokens),
146
+ temperature = float(temperature),
147
+ stream = True,
148
+ ):
149
+ delta = chunk["choices"][0]["delta"].get("content", "")
150
+ response += delta
151
+ working_history[-1]["content"] = response
152
+ yield working_history
153
+
154
+
155
+ def model_status():
156
+ if llm is not None:
157
+ return "<p class='status ready'>● Model ready</p>"
158
+ return "<p class='status loading'>● Loading model… (first boot takes a few minutes)</p>"
159
+
160
+
161
+ def do_add_memory(text):
162
+ if not text.strip():
163
+ return "", memories_display_text()
164
+ add_memory(text.strip())
165
+ return "", memories_display_text()
166
+
167
+
168
+ def do_clear_memories():
169
+ remove_all_memories()
170
+ return memories_display_text()
171
+
172
+
173
+ # ── Gradio UI ──────────────────────────────────────────────────────────────────
174
+
175
+ THEME = gr.themes.Base(
176
+ primary_hue = gr.themes.colors.orange,
177
+ secondary_hue = gr.themes.colors.stone,
178
+ neutral_hue = gr.themes.colors.stone,
179
+ font = [gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],
180
+ font_mono = [gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace"],
181
+ ).set(
182
+ body_background_fill = "#110d08",
183
+ body_background_fill_dark = "#110d08",
184
+ block_background_fill = "#1c1510",
185
+ block_background_fill_dark = "#1c1510",
186
+ block_border_color = "#2e2218",
187
+ block_border_color_dark = "#2e2218",
188
+ block_label_background_fill = "#1c1510",
189
+ block_label_background_fill_dark = "#1c1510",
190
+ input_background_fill = "#150f0a",
191
+ input_background_fill_dark = "#150f0a",
192
+ input_border_color = "#2e2218",
193
+ input_border_color_dark = "#2e2218",
194
+ button_primary_background_fill = "#cc785c",
195
+ button_primary_background_fill_hover = "#b8664a",
196
+ button_primary_background_fill_dark = "#cc785c",
197
+ button_primary_text_color = "#fff",
198
+ button_secondary_background_fill = "#2e2218",
199
+ button_secondary_background_fill_hover = "#3a2c1e",
200
+ button_secondary_background_fill_dark = "#2e2218",
201
+ button_secondary_text_color = "#d4b896",
202
+ body_text_color = "#e8ddd0",
203
+ body_text_color_dark = "#e8ddd0",
204
+ block_label_text_color = "#a08060",
205
+ block_label_text_color_dark = "#a08060",
206
+ )
207
+
208
+ CSS = """
209
+ .gradio-container { max-width: 820px !important; margin: 0 auto !important; padding: 0 12px !important; }
210
+ footer { display: none !important; }
211
+ #lumen-header { padding: 24px 0 8px; border-bottom: 1px solid #2e2218; margin-bottom: 16px; }
212
+ #lumen-header h1 { font-size: 1.6em; font-weight: 700; margin: 0 0 2px; color: #e8ddd0; letter-spacing: -0.01em; }
213
+ #lumen-header h1 span { color: #cc785c; }
214
+ #lumen-header p { color: #7a6050; margin: 0; font-size: 0.85em; }
215
+ .status { margin: 0 0 10px; font-size: 0.8em; font-weight: 500; }
216
+ .status.ready { color: #6aa87a; }
217
+ .status.loading { color: #c9994a; }
218
+ .chatbot-wrap .message.user { background: #2a1e14 !important; border: 1px solid #3a2c1e !important; }
219
+ .chatbot-wrap .message.bot { background: #1c1510 !important; border: 1px solid #2e2218 !important; }
220
+ .chatbot-wrap .message { border-radius: 8px !important; }
221
+ .input-row textarea {
222
+ background: #150f0a !important; border: 1px solid #3a2c1e !important;
223
+ border-radius: 8px !important; color: #e8ddd0 !important; resize: none !important;
224
+ }
225
+ .input-row textarea:focus { border-color: #cc785c !important; outline: none !important; }
226
+ .send-btn {
227
+ background: #cc785c !important; border: none !important;
228
+ border-radius: 8px !important; color: #fff !important;
229
+ font-size: 1.1em !important; min-width: 48px !important;
230
+ }
231
+ .send-btn:hover { background: #b8664a !important; }
232
+ .settings-row { margin: 10px 0 4px; gap: 16px; }
233
+ .settings-row label { color: #a08060 !important; font-size: 0.8em !important; }
234
+ .memory-panel { margin-top: 8px; border-top: 1px solid #2e2218; padding-top: 10px; }
235
+ .memory-panel .gr-accordion-header { color: #a08060 !important; font-size: 0.82em !important; }
236
+ .memory-list textarea {
237
+ font-size: 0.82em !important; color: #a08060 !important;
238
+ background: #110d08 !important; border: 1px solid #2e2218 !important; border-radius: 6px !important;
239
+ }
240
+ #lumen-footer { color: #4a3828; font-size: 0.75em; text-align: center; padding: 14px 0; border-top: 1px solid #2e2218; margin-top: 12px; }
241
+ #lumen-footer code { background: #1c1510; padding: 1px 5px; border-radius: 4px; color: #7a6050; }
242
+ """
243
+
244
+ with gr.Blocks(title="Lumen \u2014 Axion Labs", fill_height=True) as demo:
245
+
246
+ gr.HTML("""
247
+ <div id="lumen-header">
248
+ <h1>\u269b <span>Lumen</span></h1>
249
+ <p>Fine-tuned Llama 3.1 8B \u00b7 by Axion Labs \u00b7 free, no key needed</p>
250
+ </div>
251
+ """)
252
+
253
+ status_html = gr.HTML(model_status)
254
+
255
+ chatbot = gr.Chatbot(
256
+ height = 440,
257
+ label = "",
258
+ )
259
+
260
+ with gr.Row(elem_classes=["input-row"]):
261
+ msg_box = gr.Textbox(
262
+ placeholder = "Message Lumen\u2026",
263
+ show_label = False,
264
+ scale = 5,
265
+ lines = 1,
266
+ max_lines = 6,
267
+ )
268
+ send_btn = gr.Button("\u2191", scale=1, variant="primary", min_width=48)
269
+
270
+ with gr.Row(elem_classes=["settings-row"]):
271
+ temperature = gr.Slider(0.1, 1.5, value=0.7, step=0.1, label="Temperature", scale=1)
272
+ max_tokens = gr.Slider(64, 1024, value=512, step=64, label="Max tokens", scale=1)
273
+
274
+ with gr.Accordion("Memory", open=False, elem_classes=["memory-panel"]):
275
+ mem_display = gr.Textbox(
276
+ value = memories_display_text,
277
+ label = "",
278
+ lines = 4,
279
+ interactive = False,
280
+ )
281
+ with gr.Row():
282
+ mem_input = gr.Textbox(placeholder="Add a memory\u2026", show_label=False, scale=3)
283
+ mem_add_btn = gr.Button("Save", scale=1)
284
+ mem_clr_btn = gr.Button("Clear all", scale=1)
285
+
286
+ gr.HTML("""
287
+ <div id="lumen-footer">
288
+ OpenAI-compatible API: <code>POST /v1/chat/completions</code>
289
+ &nbsp;\u00b7&nbsp; use with Axion CLI via <code>/model lumen</code>
290
+ </div>
291
+ """)
292
+
293
+ msg_box.submit(
294
+ user_submit, [msg_box, chatbot], [msg_box, chatbot]
295
+ ).then(
296
+ bot_respond, [chatbot, temperature, max_tokens], chatbot
297
+ )
298
+ send_btn.click(
299
+ user_submit, [msg_box, chatbot], [msg_box, chatbot]
300
+ ).then(
301
+ bot_respond, [chatbot, temperature, max_tokens], chatbot
302
+ )
303
+
304
+ mem_add_btn.click(do_add_memory, [mem_input], [mem_input, mem_display])
305
+ mem_input.submit(do_add_memory, [mem_input], [mem_input, mem_display])
306
+ mem_clr_btn.click(do_clear_memories, [], [mem_display])
307
+
308
+ demo.load(model_status, outputs=status_html)
309
+
310
+
311
+ # ── FastAPI + Gradio mount ───────────────────────────────────────────────────
312
+ # Mount Gradio inside a FastAPI app so custom routes coexist with the UI.
313
+ # On HF Spaces, the spaces SDK auto-detects @spaces.GPU at import time,
314
+ # then serves the FastAPI app automatically (no manual uvicorn.run needed).
315
+
316
+ fastapi_app = FastAPI()
317
+ app = gr.mount_gradio_app(fastapi_app, demo, path="/")
318
+
319
+
320
+ @fastapi_app.get("/health")
321
+ def health():
322
+ return {"status": "ready" if llm is not None else "loading"}
323
+
324
+
325
+ @fastapi_app.get("/v1/memories")
326
+ def api_list_memories():
327
+ return {"memories": get_memories()}
328
+
329
+
330
+ @fastapi_app.post("/v1/memories")
331
+ async def api_add_memory(request: Request):
332
+ body = await request.json()
333
+ text = (body.get("text") or "").strip()
334
+ if not text:
335
+ return JSONResponse({"error": "text is required"}, status_code=400)
336
+ updated = add_memory(text)
337
+ return {"memories": updated}
338
+
339
+
340
+ @fastapi_app.delete("/v1/memories/{index}")
341
+ def api_delete_memory(index: int):
342
+ if remove_memory_by_index(index):
343
+ return {"memories": get_memories()}
344
+ return JSONResponse({"error": "index out of range"}, status_code=404)
345
+
346
+
347
+ @fastapi_app.post("/v1/chat/completions")
348
+ async def chat_completions(request: Request):
349
+ if llm is None:
350
+ return JSONResponse({"error": "Model is still loading, try again in a moment."}, status_code=503)
351
+
352
+ body = await request.json()
353
+ messages = body.get("messages", [])
354
+ max_tokens = int(body.get("max_tokens", 512))
355
+ temperature = float(body.get("temperature", 0.7))
356
+ stream = body.get("stream", False)
357
+ model_id = body.get("model", "lumen")
358
+ use_memories = body.get("use_memories", False)
359
+
360
+ sys_prompt = build_system_prompt() if use_memories else SYSTEM_PROMPT
361
+ if not any(m.get("role") == "system" for m in messages):
362
+ messages = [{"role": "system", "content": sys_prompt}] + messages
363
+
364
+ if stream:
365
+ async def event_stream():
366
+ resp_id = "chatcmpl-" + uuid.uuid4().hex
367
+ created = int(time.time())
368
+ q = queue_mod.Queue(maxsize=64)
369
+ DONE = object()
370
+
371
+ @spaces.GPU
372
+ def produce():
373
+ try:
374
+ with infer_lock:
375
+ for chunk in llm.create_chat_completion(
376
+ messages = messages,
377
+ max_tokens = max_tokens,
378
+ temperature = temperature,
379
+ stream = True,
380
+ ):
381
+ q.put(chunk)
382
+ except Exception as e:
383
+ q.put(e)
384
+ finally:
385
+ q.put(DONE)
386
+
387
+ threading.Thread(target=produce, daemon=True).start()
388
+ while True:
389
+ chunk = await asyncio.to_thread(q.get)
390
+ if chunk is DONE:
391
+ break
392
+ if isinstance(chunk, Exception):
393
+ yield f"data: {json.dumps({'error': str(chunk)})}\n\n"
394
+ break
395
+ delta = chunk["choices"][0]["delta"]
396
+ finish = chunk["choices"][0].get("finish_reason")
397
+ data = {
398
+ "id": resp_id,
399
+ "object": "chat.completion.chunk",
400
+ "created": created,
401
+ "model": model_id,
402
+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
403
+ }
404
+ yield f"data: {json.dumps(data)}\n\n"
405
+ yield "data: [DONE]\n\n"
406
+
407
+ return StreamingResponse(event_stream(), media_type="text/event-stream")
408
+
409
+ @spaces.GPU
410
+ def generate():
411
+ with infer_lock:
412
+ return llm.create_chat_completion(
413
+ messages = messages,
414
+ max_tokens = max_tokens,
415
+ temperature = temperature,
416
+ stream = False,
417
+ )
418
+
419
+ result = await asyncio.to_thread(generate)
420
+ return JSONResponse(result)