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

Delete app.py

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