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

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -423
app.py DELETED
@@ -1,423 +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(theme=THEME, css=CSS, 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
- type = "messages",
258
- height = 440,
259
- show_copy_button = True,
260
- elem_classes = ["chatbot-wrap"],
261
- label = "",
262
- show_label = False,
263
- bubble_full_width = False,
264
- )
265
-
266
- with gr.Row(elem_classes=["input-row"]):
267
- msg_box = gr.Textbox(
268
- placeholder = "Message Lumen\u2026",
269
- show_label = False,
270
- scale = 5,
271
- container = False,
272
- autofocus = True,
273
- lines = 1,
274
- max_lines = 6,
275
- )
276
- send_btn = gr.Button("\u2191", scale=1, variant="primary", elem_classes=["send-btn"], min_width=48)
277
-
278
- with gr.Row(elem_classes=["settings-row"]):
279
- temperature = gr.Slider(0.1, 1.5, value=0.7, step=0.1, label="Temperature", scale=1)
280
- max_tokens = gr.Slider(64, 1024, value=512, step=64, label="Max tokens", scale=1)
281
-
282
- with gr.Accordion("Memory", open=False, elem_classes=["memory-panel"]):
283
- mem_display = gr.Textbox(
284
- value = memories_display_text,
285
- label = "",
286
- lines = 4,
287
- interactive = False,
288
- show_copy_button = False,
289
- elem_classes = ["memory-list"],
290
- every = 10,
291
- )
292
- with gr.Row():
293
- mem_input = gr.Textbox(placeholder="Add a memory\u2026", show_label=False, scale=3, container=False)
294
- mem_add_btn = gr.Button("Save", scale=1, size="sm")
295
- mem_clr_btn = gr.Button("Clear all", scale=1, size="sm", variant="stop")
296
-
297
- gr.HTML("""
298
- <div id="lumen-footer">
299
- OpenAI-compatible API: <code>POST /v1/chat/completions</code>
300
- &nbsp;\u00b7&nbsp; use with Axion CLI via <code>/model lumen</code>
301
- </div>
302
- """)
303
-
304
- msg_box.submit(
305
- user_submit, [msg_box, chatbot], [msg_box, chatbot], queue=False
306
- ).then(
307
- bot_respond, [chatbot, temperature, max_tokens], chatbot
308
- )
309
- send_btn.click(
310
- user_submit, [msg_box, chatbot], [msg_box, chatbot], queue=False
311
- ).then(
312
- bot_respond, [chatbot, temperature, max_tokens], chatbot
313
- )
314
-
315
- mem_add_btn.click(do_add_memory, [mem_input], [mem_input, mem_display])
316
- mem_input.submit(do_add_memory, [mem_input], [mem_input, mem_display])
317
- mem_clr_btn.click(do_clear_memories, [], [mem_display])
318
-
319
- demo.load(model_status, outputs=status_html)
320
-
321
-
322
- # ── API routes mounted on Gradio's internal FastAPI ──────────────────────────
323
- # (These must come AFTER the `with gr.Blocks() as demo:` block so demo.app exists)
324
-
325
- @demo.app.get("/health")
326
- def health():
327
- return {"status": "ready" if llm is not None else "loading"}
328
-
329
-
330
- @demo.app.get("/v1/memories")
331
- def api_list_memories():
332
- return {"memories": get_memories()}
333
-
334
-
335
- @demo.app.post("/v1/memories")
336
- async def api_add_memory(request: Request):
337
- body = await request.json()
338
- text = (body.get("text") or "").strip()
339
- if not text:
340
- return JSONResponse({"error": "text is required"}, status_code=400)
341
- updated = add_memory(text)
342
- return {"memories": updated}
343
-
344
-
345
- @demo.app.delete("/v1/memories/{index}")
346
- def api_delete_memory(index: int):
347
- if remove_memory_by_index(index):
348
- return {"memories": get_memories()}
349
- return JSONResponse({"error": "index out of range"}, status_code=404)
350
-
351
-
352
- @demo.app.post("/v1/chat/completions")
353
- async def chat_completions(request: Request):
354
- if llm is None:
355
- return JSONResponse({"error": "Model is still loading, try again in a moment."}, status_code=503)
356
-
357
- body = await request.json()
358
- messages = body.get("messages", [])
359
- max_tokens = int(body.get("max_tokens", 512))
360
- temperature = float(body.get("temperature", 0.7))
361
- stream = body.get("stream", False)
362
- model_id = body.get("model", "lumen")
363
- use_memories = body.get("use_memories", False)
364
-
365
- sys_prompt = build_system_prompt() if use_memories else SYSTEM_PROMPT
366
- if not any(m.get("role") == "system" for m in messages):
367
- messages = [{"role": "system", "content": sys_prompt}] + messages
368
-
369
- if stream:
370
- async def event_stream():
371
- resp_id = "chatcmpl-" + uuid.uuid4().hex
372
- created = int(time.time())
373
- q = queue_mod.Queue(maxsize=64)
374
- DONE = object()
375
-
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
- 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)