AxionLabsAI commited on
Commit
76cc259
Β·
verified Β·
1 Parent(s): 45ab589

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -181
app.py CHANGED
@@ -6,7 +6,7 @@ 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
  from llama_cpp import Llama
@@ -18,7 +18,6 @@ MEMORY_FILE = "/tmp/memories.json"
18
  SYSTEM_PROMPT = (
19
  """
20
  You are Lumen, an AI assistant made by Axion Labs. You're helpful, direct, and honest.
21
-
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.
@@ -94,7 +93,7 @@ def memories_display_text():
94
  def _load_model():
95
  global llm
96
  if not os.path.exists(MODEL_PATH):
97
- print("Downloading Lumen DPO model…")
98
  hf_hub_download(
99
  repo_id = "RavikxxBGamin/Lumen",
100
  filename = "lumen-dpo.gguf",
@@ -102,7 +101,7 @@ def _load_model():
102
  local_dir = "/tmp",
103
  )
104
 
105
- print("Loading model…")
106
  llm = Llama(
107
  model_path = MODEL_PATH,
108
  n_ctx = 8192,
@@ -111,175 +110,11 @@ def _load_model():
111
  )
112
  print("Model ready.")
113
 
114
-
115
- # ── FastAPI ───────────────────────────────────────────────────────────────────
116
-
117
- fastapi_app = FastAPI()
118
-
119
-
120
- @fastapi_app.on_event("startup")
121
- async def startup():
122
- loop = asyncio.get_event_loop()
123
- loop.run_in_executor(None, _load_model)
124
-
125
-
126
- @fastapi_app.get("/health")
127
- def health():
128
- return {"status": "ready" if llm is not None else "loading"}
129
-
130
-
131
- @fastapi_app.get("/v1/memories")
132
- def api_list_memories():
133
- return {"memories": get_memories()}
134
-
135
-
136
- @fastapi_app.post("/v1/memories")
137
- async def api_add_memory(request: Request):
138
- body = await request.json()
139
- text = (body.get("text") or "").strip()
140
- if not text:
141
- return JSONResponse({"error": "text is required"}, status_code=400)
142
- updated = add_memory(text)
143
- return {"memories": updated}
144
-
145
-
146
- @fastapi_app.delete("/v1/memories/{index}")
147
- def api_delete_memory(index: int):
148
- if remove_memory_by_index(index):
149
- return {"memories": get_memories()}
150
- return JSONResponse({"error": "index out of range"}, status_code=404)
151
-
152
-
153
- @fastapi_app.post("/v1/chat/completions")
154
- async def chat_completions(request: Request):
155
- if llm is None:
156
- return JSONResponse({"error": "Model is still loading, try again in a moment."}, status_code=503)
157
-
158
- body = await request.json()
159
- messages = body.get("messages", [])
160
- max_tokens = int(body.get("max_tokens", 512))
161
- temperature = float(body.get("temperature", 0.7))
162
- stream = body.get("stream", False)
163
- model_id = body.get("model", "lumen")
164
- use_memories = body.get("use_memories", False)
165
-
166
- sys_prompt = build_system_prompt() if use_memories else SYSTEM_PROMPT
167
- if not any(m.get("role") == "system" for m in messages):
168
- messages = [{"role": "system", "content": sys_prompt}] + messages
169
-
170
- if stream:
171
- async def event_stream():
172
- resp_id = "chatcmpl-" + uuid.uuid4().hex
173
- created = int(time.time())
174
- q = queue_mod.Queue(maxsize=64)
175
- DONE = object()
176
-
177
- def produce():
178
- try:
179
- with infer_lock:
180
- for chunk in llm.create_chat_completion(
181
- messages = messages,
182
- max_tokens = max_tokens,
183
- temperature = temperature,
184
- stream = True,
185
- ):
186
- q.put(chunk)
187
- except Exception as e:
188
- q.put(e)
189
- finally:
190
- q.put(DONE)
191
-
192
- threading.Thread(target=produce, daemon=True).start()
193
- while True:
194
- chunk = await asyncio.to_thread(q.get)
195
- if chunk is DONE:
196
- break
197
- if isinstance(chunk, Exception):
198
- yield f"data: {json.dumps({'error': str(chunk)})}\n\n"
199
- break
200
- delta = chunk["choices"][0]["delta"]
201
- finish = chunk["choices"][0].get("finish_reason")
202
- data = {
203
- "id": resp_id,
204
- "object": "chat.completion.chunk",
205
- "created": created,
206
- "model": model_id,
207
- "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
208
- }
209
- yield f"data: {json.dumps(data)}\n\n"
210
- yield "data: [DONE]\n\n"
211
-
212
- return StreamingResponse(event_stream(), media_type="text/event-stream")
213
-
214
- def generate():
215
- with infer_lock:
216
- return llm.create_chat_completion(
217
- messages = messages,
218
- max_tokens = max_tokens,
219
- temperature = temperature,
220
- stream = False,
221
- )
222
-
223
- result = await asyncio.to_thread(generate)
224
- return JSONResponse(result)
225
-
226
-
227
- # ── Gradio chat helpers ───────────────────────────────────────────────────────
228
-
229
- def user_submit(message, history):
230
- if not message.strip():
231
- return "", history
232
- return "", history + [{"role": "user", "content": message}]
233
-
234
-
235
- def bot_respond(history, temperature, max_tokens):
236
- if llm is None:
237
- yield history + [{"role": "assistant", "content": "Model is still loading β€” please wait a moment and try again."}]
238
- return
239
-
240
- messages = [{"role": "system", "content": build_system_prompt()}]
241
- for item in history:
242
- if not isinstance(item, dict):
243
- continue
244
- content = item.get("content", "")
245
- if isinstance(content, list):
246
- content = " ".join(p.get("text", "") for p in content if isinstance(p, dict))
247
- messages.append({"role": item["role"], "content": content})
248
-
249
- response = ""
250
- working_history = history + [{"role": "assistant", "content": ""}]
251
- with infer_lock:
252
- for chunk in llm.create_chat_completion(
253
- messages = messages,
254
- max_tokens = int(max_tokens),
255
- temperature = float(temperature),
256
- stream = True,
257
- ):
258
- delta = chunk["choices"][0]["delta"].get("content", "")
259
- response += delta
260
- working_history[-1]["content"] = response
261
- yield working_history
262
-
263
-
264
- def model_status():
265
- if llm is not None:
266
- return "<p class='status ready'>● Model ready</p>"
267
- return "<p class='status loading'>● Loading model… (first boot takes a few minutes)</p>"
268
-
269
-
270
- def do_add_memory(text):
271
- if not text.strip():
272
- return "", memories_display_text()
273
- add_memory(text.strip())
274
- return "", memories_display_text()
275
 
276
 
277
- def do_clear_memories():
278
- remove_all_memories()
279
- return memories_display_text()
280
-
281
-
282
- # ── Theme & CSS ───────────────────────────────────────────────────────────────
283
 
284
  THEME = gr.themes.Base(
285
  primary_hue = gr.themes.colors.orange,
@@ -350,14 +185,12 @@ footer { display: none !important; }
350
  #lumen-footer code { background: #1c1510; padding: 1px 5px; border-radius: 4px; color: #7a6050; }
351
  """
352
 
353
- # ── Gradio UI ─────────────────────────────────────────────────────────────────
354
-
355
- with gr.Blocks(theme=THEME, css=CSS, title="Lumen β€” Axion Labs") as demo:
356
 
357
  gr.HTML("""
358
  <div id="lumen-header">
359
- <h1>βš› <span>Lumen</span></h1>
360
- <p>Fine-tuned Llama 3.1 8B Β· by Axion Labs Β· free, no key needed</p>
361
  </div>
362
  """)
363
 
@@ -375,7 +208,7 @@ with gr.Blocks(theme=THEME, css=CSS, title="Lumen β€” Axion Labs") as demo:
375
 
376
  with gr.Row(elem_classes=["input-row"]):
377
  msg_box = gr.Textbox(
378
- placeholder = "Message Lumen…",
379
  show_label = False,
380
  scale = 5,
381
  container = False,
@@ -383,7 +216,7 @@ with gr.Blocks(theme=THEME, css=CSS, title="Lumen β€” Axion Labs") as demo:
383
  lines = 1,
384
  max_lines = 6,
385
  )
386
- send_btn = gr.Button("↑", scale=1, variant="primary", elem_classes=["send-btn"], min_width=48)
387
 
388
  with gr.Row(elem_classes=["settings-row"]):
389
  temperature = gr.Slider(0.1, 1.5, value=0.7, step=0.1, label="Temperature", scale=1)
@@ -400,14 +233,14 @@ with gr.Blocks(theme=THEME, css=CSS, title="Lumen β€” Axion Labs") as demo:
400
  every = 10,
401
  )
402
  with gr.Row():
403
- mem_input = gr.Textbox(placeholder="Add a memory…", show_label=False, scale=3, container=False)
404
  mem_add_btn = gr.Button("Save", scale=1, size="sm")
405
  mem_clr_btn = gr.Button("Clear all", scale=1, size="sm", variant="stop")
406
 
407
  gr.HTML("""
408
  <div id="lumen-footer">
409
  OpenAI-compatible API: <code>POST /v1/chat/completions</code>
410
- &nbsp;Β·&nbsp; use with Axion CLI via <code>/model lumen</code>
411
  </div>
412
  """)
413
 
@@ -429,4 +262,106 @@ with gr.Blocks(theme=THEME, css=CSS, title="Lumen β€” Axion Labs") as demo:
429
  demo.load(model_status, outputs=status_html)
430
 
431
 
432
- app = gr.mount_gradio_app(fastapi_app, demo, path="/")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
 
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.
 
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",
 
101
  local_dir = "/tmp",
102
  )
103
 
104
+ print("Loading model\u2026")
105
  llm = Llama(
106
  model_path = MODEL_PATH,
107
  n_ctx = 8192,
 
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,
 
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
 
 
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,
 
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)
 
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
 
 
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
+