AxionLabsAI commited on
Commit
f428402
·
verified ·
1 Parent(s): 1e779c5

Delete app.py

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