AxionLabsAI commited on
Commit
1de00bb
·
verified ·
1 Parent(s): 8e50fdd

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -367
app.py DELETED
@@ -1,367 +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
- from llama_cpp import Llama
13
-
14
- HF_TOKEN = os.environ.get("HF_TOKEN")
15
- MODEL_PATH = "/tmp/lumen-dpo.gguf"
16
- MEMORY_FILE = "/tmp/memories.json"
17
-
18
- SYSTEM_PROMPT = (
19
- """
20
- You are Lumen, an AI assistant made by Axion Labs. You're helpful, direct, and honest.
21
- - Answer questions clearly and concisely. Don't over-explain.
22
- - If you don't know something, say so — don't guess and present it as fact.
23
- - Refuse requests that would harm people, violate privacy, or involve illegal activity.
24
- """
25
- )
26
-
27
- llm = None
28
- infer_lock = threading.Lock()
29
-
30
-
31
- # ── Memory ────────────────────────────────────────────────────────────────────
32
-
33
- def _load_memories():
34
- try:
35
- if not os.path.exists(MEMORY_FILE):
36
- return []
37
- with open(MEMORY_FILE) as f:
38
- return json.load(f)
39
- except Exception:
40
- return []
41
-
42
-
43
- def _save_memories(memories):
44
- try:
45
- with open(MEMORY_FILE, "w") as f:
46
- json.dump(memories, f, indent=2)
47
- except Exception:
48
- pass
49
-
50
-
51
- def get_memories():
52
- return _load_memories()
53
-
54
-
55
- def add_memory(text):
56
- memories = _load_memories()
57
- memories.append({"text": text.strip(), "addedAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())})
58
- _save_memories(memories)
59
- return memories
60
-
61
-
62
- def remove_all_memories():
63
- _save_memories([])
64
-
65
-
66
- def remove_memory_by_index(index):
67
- memories = _load_memories()
68
- if 0 <= index < len(memories):
69
- memories.pop(index)
70
- _save_memories(memories)
71
- return True
72
- return False
73
-
74
-
75
- def build_system_prompt():
76
- memories = get_memories()
77
- prompt = SYSTEM_PROMPT
78
- if memories:
79
- notes = "\n".join(f"- {m['text']}" for m in memories)
80
- prompt += f"\n\nPersistent notes (always keep in mind):\n{notes}"
81
- return prompt
82
-
83
-
84
- def memories_display_text():
85
- memories = get_memories()
86
- if not memories:
87
- return "No memories saved."
88
- return "\n".join(f"{i + 1}. {m['text']}" for i, m in enumerate(memories))
89
-
90
-
91
- # ── Model loading ─────────────────────────────────────────────────────────────
92
-
93
- def _load_model():
94
- global llm
95
- if not os.path.exists(MODEL_PATH):
96
- print("Downloading Lumen DPO model\u2026")
97
- hf_hub_download(
98
- repo_id = "RavikxxBGamin/Lumen",
99
- filename = "lumen-dpo.gguf",
100
- token = HF_TOKEN,
101
- local_dir = "/tmp",
102
- )
103
-
104
- print("Loading model\u2026")
105
- llm = Llama(
106
- model_path = MODEL_PATH,
107
- n_ctx = 8192,
108
- n_threads = 2,
109
- verbose = False,
110
- )
111
- print("Model ready.")
112
-
113
- # Start loading in background before Gradio builds UI
114
- threading.Thread(target=_load_model, daemon=True).start()
115
-
116
-
117
- # ── Gradio UI must be defined before API routes ──────────────────────────────
118
-
119
- THEME = gr.themes.Base(
120
- primary_hue = gr.themes.colors.orange,
121
- secondary_hue = gr.themes.colors.stone,
122
- neutral_hue = gr.themes.colors.stone,
123
- font = [gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],
124
- font_mono = [gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace"],
125
- ).set(
126
- body_background_fill = "#110d08",
127
- body_background_fill_dark = "#110d08",
128
- block_background_fill = "#1c1510",
129
- block_background_fill_dark = "#1c1510",
130
- block_border_color = "#2e2218",
131
- block_border_color_dark = "#2e2218",
132
- block_label_background_fill = "#1c1510",
133
- block_label_background_fill_dark = "#1c1510",
134
- input_background_fill = "#150f0a",
135
- input_background_fill_dark = "#150f0a",
136
- input_border_color = "#2e2218",
137
- input_border_color_dark = "#2e2218",
138
- button_primary_background_fill = "#cc785c",
139
- button_primary_background_fill_hover = "#b8664a",
140
- button_primary_background_fill_dark = "#cc785c",
141
- button_primary_text_color = "#fff",
142
- button_secondary_background_fill = "#2e2218",
143
- button_secondary_background_fill_hover = "#3a2c1e",
144
- button_secondary_background_fill_dark = "#2e2218",
145
- button_secondary_text_color = "#d4b896",
146
- body_text_color = "#e8ddd0",
147
- body_text_color_dark = "#e8ddd0",
148
- block_label_text_color = "#a08060",
149
- block_label_text_color_dark = "#a08060",
150
- )
151
-
152
- CSS = """
153
- .gradio-container { max-width: 820px !important; margin: 0 auto !important; padding: 0 12px !important; }
154
- footer { display: none !important; }
155
- #lumen-header { padding: 24px 0 8px; border-bottom: 1px solid #2e2218; margin-bottom: 16px; }
156
- #lumen-header h1 { font-size: 1.6em; font-weight: 700; margin: 0 0 2px; color: #e8ddd0; letter-spacing: -0.01em; }
157
- #lumen-header h1 span { color: #cc785c; }
158
- #lumen-header p { color: #7a6050; margin: 0; font-size: 0.85em; }
159
- .status { margin: 0 0 10px; font-size: 0.8em; font-weight: 500; }
160
- .status.ready { color: #6aa87a; }
161
- .status.loading { color: #c9994a; }
162
- .chatbot-wrap .message.user { background: #2a1e14 !important; border: 1px solid #3a2c1e !important; }
163
- .chatbot-wrap .message.bot { background: #1c1510 !important; border: 1px solid #2e2218 !important; }
164
- .chatbot-wrap .message { border-radius: 8px !important; }
165
- .input-row textarea {
166
- background: #150f0a !important; border: 1px solid #3a2c1e !important;
167
- border-radius: 8px !important; color: #e8ddd0 !important; resize: none !important;
168
- }
169
- .input-row textarea:focus { border-color: #cc785c !important; outline: none !important; }
170
- .send-btn {
171
- background: #cc785c !important; border: none !important;
172
- border-radius: 8px !important; color: #fff !important;
173
- font-size: 1.1em !important; min-width: 48px !important;
174
- }
175
- .send-btn:hover { background: #b8664a !important; }
176
- .settings-row { margin: 10px 0 4px; gap: 16px; }
177
- .settings-row label { color: #a08060 !important; font-size: 0.8em !important; }
178
- .memory-panel { margin-top: 8px; border-top: 1px solid #2e2218; padding-top: 10px; }
179
- .memory-panel .gr-accordion-header { color: #a08060 !important; font-size: 0.82em !important; }
180
- .memory-list textarea {
181
- font-size: 0.82em !important; color: #a08060 !important;
182
- background: #110d08 !important; border: 1px solid #2e2218 !important; border-radius: 6px !important;
183
- }
184
- #lumen-footer { color: #4a3828; font-size: 0.75em; text-align: center; padding: 14px 0; border-top: 1px solid #2e2218; margin-top: 12px; }
185
- #lumen-footer code { background: #1c1510; padding: 1px 5px; border-radius: 4px; color: #7a6050; }
186
- """
187
-
188
- with gr.Blocks(theme=THEME, css=CSS, title="Lumen \u2014 Axion Labs") as demo:
189
-
190
- gr.HTML("""
191
- <div id="lumen-header">
192
- <h1>\u269b <span>Lumen</span></h1>
193
- <p>Fine-tuned Llama 3.1 8B \u00b7 by Axion Labs \u00b7 free, no key needed</p>
194
- </div>
195
- """)
196
-
197
- status_html = gr.HTML(model_status)
198
-
199
- chatbot = gr.Chatbot(
200
- type = "messages",
201
- height = 440,
202
- show_copy_button = True,
203
- elem_classes = ["chatbot-wrap"],
204
- label = "",
205
- show_label = False,
206
- bubble_full_width = False,
207
- )
208
-
209
- with gr.Row(elem_classes=["input-row"]):
210
- msg_box = gr.Textbox(
211
- placeholder = "Message Lumen\u2026",
212
- show_label = False,
213
- scale = 5,
214
- container = False,
215
- autofocus = True,
216
- lines = 1,
217
- max_lines = 6,
218
- )
219
- send_btn = gr.Button("\u2191", scale=1, variant="primary", elem_classes=["send-btn"], min_width=48)
220
-
221
- with gr.Row(elem_classes=["settings-row"]):
222
- temperature = gr.Slider(0.1, 1.5, value=0.7, step=0.1, label="Temperature", scale=1)
223
- max_tokens = gr.Slider(64, 1024, value=512, step=64, label="Max tokens", scale=1)
224
-
225
- with gr.Accordion("Memory", open=False, elem_classes=["memory-panel"]):
226
- mem_display = gr.Textbox(
227
- value = memories_display_text,
228
- label = "",
229
- lines = 4,
230
- interactive = False,
231
- show_copy_button = False,
232
- elem_classes = ["memory-list"],
233
- every = 10,
234
- )
235
- with gr.Row():
236
- mem_input = gr.Textbox(placeholder="Add a memory\u2026", show_label=False, scale=3, container=False)
237
- mem_add_btn = gr.Button("Save", scale=1, size="sm")
238
- mem_clr_btn = gr.Button("Clear all", scale=1, size="sm", variant="stop")
239
-
240
- gr.HTML("""
241
- <div id="lumen-footer">
242
- OpenAI-compatible API: <code>POST /v1/chat/completions</code>
243
-  \u00b7  use with Axion CLI via <code>/model lumen</code>
244
- </div>
245
- """)
246
-
247
- msg_box.submit(
248
- user_submit, [msg_box, chatbot], [msg_box, chatbot], queue=False
249
- ).then(
250
- bot_respond, [chatbot, temperature, max_tokens], chatbot
251
- )
252
- send_btn.click(
253
- user_submit, [msg_box, chatbot], [msg_box, chatbot], queue=False
254
- ).then(
255
- bot_respond, [chatbot, temperature, max_tokens], chatbot
256
- )
257
-
258
- mem_add_btn.click(do_add_memory, [mem_input], [mem_input, mem_display])
259
- mem_input.submit(do_add_memory, [mem_input], [mem_input, mem_display])
260
- mem_clr_btn.click(do_clear_memories, [], [mem_display])
261
-
262
- demo.load(model_status, outputs=status_html)
263
-
264
-
265
- # ── API routes mounted on Gradio's internal FastAPI ──────────────────────────
266
- # (These must come AFTER the `with gr.Blocks() as demo:` block so demo.app exists)
267
-
268
- @demo.app.get("/health")
269
- def health():
270
- return {"status": "ready" if llm is not None else "loading"}
271
-
272
-
273
- @demo.app.get("/v1/memories")
274
- def api_list_memories():
275
- return {"memories": get_memories()}
276
-
277
-
278
- @demo.app.post("/v1/memories")
279
- async def api_add_memory(request: Request):
280
- body = await request.json()
281
- text = (body.get("text") or "").strip()
282
- if not text:
283
- return JSONResponse({"error": "text is required"}, status_code=400)
284
- updated = add_memory(text)
285
- return {"memories": updated}
286
-
287
-
288
- @demo.app.delete("/v1/memories/{index}")
289
- def api_delete_memory(index: int):
290
- if remove_memory_by_index(index):
291
- return {"memories": get_memories()}
292
- return JSONResponse({"error": "index out of range"}, status_code=404)
293
-
294
-
295
- @demo.app.post("/v1/chat/completions")
296
- async def chat_completions(request: Request):
297
- if llm is None:
298
- return JSONResponse({"error": "Model is still loading, try again in a moment."}, status_code=503)
299
-
300
- body = await request.json()
301
- messages = body.get("messages", [])
302
- max_tokens = int(body.get("max_tokens", 512))
303
- temperature = float(body.get("temperature", 0.7))
304
- stream = body.get("stream", False)
305
- model_id = body.get("model", "lumen")
306
- use_memories = body.get("use_memories", False)
307
-
308
- sys_prompt = build_system_prompt() if use_memories else SYSTEM_PROMPT
309
- if not any(m.get("role") == "system" for m in messages):
310
- messages = [{"role": "system", "content": sys_prompt}] + messages
311
-
312
- if stream:
313
- async def event_stream():
314
- resp_id = "chatcmpl-" + uuid.uuid4().hex
315
- created = int(time.time())
316
- q = queue_mod.Queue(maxsize=64)
317
- DONE = object()
318
-
319
- def produce():
320
- try:
321
- with infer_lock:
322
- for chunk in llm.create_chat_completion(
323
- messages = messages,
324
- max_tokens = max_tokens,
325
- temperature = temperature,
326
- stream = True,
327
- ):
328
- q.put(chunk)
329
- except Exception as e:
330
- q.put(e)
331
- finally:
332
- q.put(DONE)
333
-
334
- threading.Thread(target=produce, daemon=True).start()
335
- while True:
336
- chunk = await asyncio.to_thread(q.get)
337
- if chunk is DONE:
338
- break
339
- if isinstance(chunk, Exception):
340
- yield f"data: {json.dumps({'error': str(chunk)})}\n\n"
341
- break
342
- delta = chunk["choices"][0]["delta"]
343
- finish = chunk["choices"][0].get("finish_reason")
344
- data = {
345
- "id": resp_id,
346
- "object": "chat.completion.chunk",
347
- "created": created,
348
- "model": model_id,
349
- "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
350
- }
351
- yield f"data: {json.dumps(data)}\n\n"
352
- yield "data: [DONE]\n\n"
353
-
354
- return StreamingResponse(event_stream(), media_type="text/event-stream")
355
-
356
- def generate():
357
- with infer_lock:
358
- return llm.create_chat_completion(
359
- messages = messages,
360
- max_tokens = max_tokens,
361
- temperature = temperature,
362
- stream = False,
363
- )
364
-
365
- result = await asyncio.to_thread(generate)
366
- return JSONResponse(result)
367
-