Spaces:
Runtime error
Runtime error
Update app.py
Browse files5 unmodified lines67891011125 unmodified lines1819202122232469 unmodified lines9495969798991001 unmodified line1021031041051061071082 unmodified lines11111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428564 unmodified lines35035135235335435535635735835936036136236311 unmodified lines3753763773783793803811 unmodified line38338438538638738838910 unmodified lines40040140240340440540640740840941041141241315 unmodified lines4294304314325 unmodified linesimport threadingimport queue as queue_modimport gradio as grfrom fastapi import FastAPI, Requestfrom fastapi.responses import StreamingResponse, JSONResponsefrom huggingface_hub import hf_hub_downloadfrom llama_cpp import Llama5 unmodified linesSYSTEM_PROMPT = ("""You are Lumen, an AI assistant made by Axion Labs. You're helpful, direct, and honest.- Answer questions clearly and concisely. Don't over-explain.- If you don't know something, say so β don't guess and present it as fact.- Refuse requests that would harm people, violate privacy, or involve illegal activity.69 unmodified linesdef _load_model():global llmif not os.path.exists(MODEL_PATH):print("Downloading Lumen DPO modelβ¦")hf_hub_download(repo_id = "RavikxxBGamin/Lumen",filename = "lumen-dpo.gguf",1 unmodified linelocal_dir = "/tmp",)print("Loading modelβ¦")llm = Llama(model_path = MODEL_PATH,n_ctx = 8192,2 unmodified lines)print("Model ready.")# ββ FastAPI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββfastapi_app = FastAPI()@fastapi_app.on_event("startup")async def startup():loop = asyncio.get_event_loop()loop.run_in_executor(None, _load_model)@fastapi_app.get("/health")def health():return {"status": "ready" if llm is not None else "loading"}@fastapi_app.get("/v1/memories")def api_list_memories():return {"memories": get_memories()}@fastapi_app.post("/v1/memories")async def api_add_memory(request: Request):body = await request.json()text = (body.get("text") or "").strip()if not text:return JSONResponse({"error": "text is required"}, status_code=400)updated = add_memory(text)return {"memories": updated}@fastapi_app.delete("/v1/memories/{index}")def api_delete_memory(index: int):if remove_memory_by_index(index):return {"memories": get_memories()}return JSONResponse({"error": "index out of range"}, status_code=404)@fastapi_app.post("/v1/chat/completions")async def chat_completions(request: Request):if llm is None:return JSONResponse({"error": "Model is still loading, try again in a moment."}, status_code=503)body = await request.json()messages = body.get("messages", [])max_tokens = int(body.get("max_tokens", 512))temperature = float(body.get("temperature", 0.7))stream = body.get("stream", False)model_id = body.get("model", "lumen")use_memories = body.get("use_memories", False)sys_prompt = build_system_prompt() if use_memories else SYSTEM_PROMPTif not any(m.get("role") == "system" for m in messages):messages = [{"role": "system", "content": sys_prompt}] + messagesif stream:async def event_stream():resp_id = "chatcmpl-" + uuid.uuid4().hexcreated = int(time.time())q = queue_mod.Queue(maxsize=64)DONE = object()def produce():try:with infer_lock:for chunk in llm.create_chat_completion(messages = messages,max_tokens = max_tokens,temperature = temperature,stream = True,):q.put(chunk)except Exception as e:q.put(e)finally:q.put(DONE)threading.Thread(target=produce, daemon=True).start()while True:chunk = await asyncio.to_thread(q.get)if chunk is DONE:breakif isinstance(chunk, Exception):yield f"data: {json.dumps({'error': str(chunk)})}\n\n"breakdelta = chunk["choices"][0]["delta"]finish = chunk["choices"][0].get("finish_reason")data = {"id": resp_id,"object": "chat.completion.chunk","created": created,"model": model_id,"choices": [{"index": 0, "delta": delta, "finish_reason": finish}],}yield f"data: {json.dumps(data)}\n\n"yield "data: [DONE]\n\n"return StreamingResponse(event_stream(), media_type="text/event-stream")def generate():with infer_lock:return llm.create_chat_completion(messages = messages,max_tokens = max_tokens,temperature = temperature,stream = False,)result = await asyncio.to_thread(generate)return JSONResponse(result)# ββ Gradio chat helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββdef user_submit(message, history):if not message.strip():return "", historyreturn "", history + [{"role": "user", "content": message}]def bot_respond(history, temperature, max_tokens):if llm is None:yield history + [{"role": "assistant", "content": "Model is still loading β please wait a moment and try again."}]returnmessages = [{"role": "system", "content": build_system_prompt()}]for item in history:if not isinstance(item, dict):continuecontent = item.get("content", "")if isinstance(content, list):content = " ".join(p.get("text", "") for p in content if isinstance(p, dict))messages.append({"role": item["role"], "content": content})response = ""working_history = history + [{"role": "assistant", "content": ""}]with infer_lock:for chunk in llm.create_chat_completion(messages = messages,max_tokens = int(max_tokens),temperature = float(temperature),stream = True,):delta = chunk["choices"][0]["delta"].get("content", "")response += deltaworking_history[-1]["content"] = responseyield working_historydef model_status():if llm is not None:return "<p class='status ready'>β Model ready</p>"return "<p class='status loading'>β Loading modelβ¦ (first boot takes a few minutes)</p>"def do_add_memory(text):if not text.strip():return "", memories_display_text()add_memory(text.strip())return "", memories_display_text()def do_clear_memories():remove_all_memories()return memories_display_text()# ββ Theme & CSS βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββTHEME = gr.themes.Base(primary_hue = gr.themes.colors.orange,64 unmodified lines#lumen-footer code { background: #1c1510; padding: 1px 5px; border-radius: 4px; color: #7a6050; }"""# ββ Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββwith gr.Blocks(theme=THEME, css=CSS, title="Lumen β Axion Labs") as demo:gr.HTML("""<div id="lumen-header"><h1>β <span>Lumen</span></h1><p>Fine-tuned Llama 3.1 8B Β· by Axion Labs Β· free, no key needed</p></div>""")11 unmodified lineswith gr.Row(elem_classes=["input-row"]):msg_box = gr.Textbox(placeholder = "Message Lumenβ¦",show_label = False,scale = 5,container = False,1 unmodified linelines = 1,max_lines = 6,)send_btn = gr.Button("β", scale=1, variant="primary", elem_classes=["send-btn"], min_width=48)with gr.Row(elem_classes=["settings-row"]):temperature = gr.Slider(0.1, 1.5, value=0.7, step=0.1, label="Temperature", scale=1)10 unmodified linesevery = 10,)with gr.Row():mem_input = gr.Textbox(placeholder="Add a memoryβ¦", show_label=False, scale=3, container=False)mem_add_btn = gr.Button("Save", scale=1, size="sm")mem_clr_btn = gr.Button("Clear all", scale=1, size="sm", variant="stop")gr.HTML("""<div id="lumen-footer">OpenAI-compatible API: <code>POST /v1/chat/completions</code> Β· use with Axion CLI via <code>/model lumen</code></div>""")15 unmodified linesdemo.load(model_status, outputs=status_html)app = gr.mount_gradio_app(fastapi_app, demo, path="/")5 unmodified lines67891011125 unmodified lines18192021222369 unmodified lines939495969798991 unmodified line1011021031041051061072 unmodified lines11011111211311411511611711811912064 unmodified lines18518618718818919019119219319419519611 unmodified lines2082092102112122132141 unmodified line21621721821922022122210 unmodified lines23323423523623723823924024124224324424524615 unmodified lines2622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663675 unmodified linesimport threadingimport queue as queue_modimport gradio as grfrom fastapi import Requestfrom fastapi.responses import StreamingResponse, JSONResponsefrom huggingface_hub import hf_hub_downloadfrom llama_cpp import Llama5 unmodified linesSYSTEM_PROMPT = ("""You are Lumen, an AI assistant made by Axion Labs. You're helpful, direct, and honest.- Answer questions clearly and concisely. Don't over-explain.- If you don't know something, say so β don't guess and present it as fact.- Refuse requests that would harm people, violate privacy, or involve illegal activity.69 unmodified linesdef _load_model():global llmif not os.path.exists(MODEL_PATH):print("Downloading Lumen DPO model\u2026")hf_hub_download(repo_id = "RavikxxBGamin/Lumen",filename = "lumen-dpo.gguf",1 unmodified linelocal_dir = "/tmp",)print("Loading model\u2026")llm = Llama(model_path = MODEL_PATH,n_ctx = 8192,2 unmodified lines)print("Model ready.")# Start loading in background before Gradio builds UIthreading.Thread(target=_load_model, daemon=True).start()# ββ Gradio UI must be defined before API routes ββββββββββββββββββββββββββββββTHEME = gr.themes.Base(primary_hue = gr.themes.colors.orange,64 unmodified lines#lumen-footer code { background: #1c1510; padding: 1px 5px; border-radius: 4px; color: #7a6050; }"""with gr.Blocks(theme=THEME, css=CSS, title="Lumen \u2014 Axion Labs") as demo:gr.HTML("""<div id="lumen-header"><h1>\u269b <span>Lumen</span></h1><p>Fine-tuned Llama 3.1 8B \u00b7 by Axion Labs \u00b7 free, no key needed</p></div>""")11 unmodified lineswith gr.Row(elem_classes=["input-row"]):msg_box = gr.Textbox(placeholder = "Message Lumen\u2026",show_label = False,scale = 5,container = False,1 unmodified linelines = 1,max_lines = 6,)send_btn = gr.Button("\u2191", scale=1, variant="primary", elem_classes=["send-btn"], min_width=48)with gr.Row(elem_classes=["settings-row"]):temperature = gr.Slider(0.1, 1.5, value=0.7, step=0.1, label="Temperature", scale=1)10 unmodified linesevery = 10,)with gr.Row():mem_input = gr.Textbox(placeholder="Add a memory\u2026", show_label=False, scale=3, container=False)mem_add_btn = gr.Button("Save", scale=1, size="sm")mem_clr_btn = gr.Button("Clear all", scale=1, size="sm", variant="stop")gr.HTML("""<div id="lumen-footer">OpenAI-compatible API: <code>POST /v1/chat/completions</code>Β \u00b7Β use with Axion CLI via <code>/model lumen</code></div>""")15 unmodified linesdemo.load(model_status, outputs=status_html)# ββ API routes mounted on Gradio's internal FastAPI ββββββββββββββββββββββββββ# (These must come AFTER the `with gr.Blocks() as demo:` block so demo.app exists)@demo.app.get("/health")def health():return {"status": "ready" if llm is not None else "loading"}@demo.app.get("/v1/memories")def api_list_memories():return {"memories": get_memories()}@demo.app.post("/v1/memories")async def api_add_memory(request: Request):body = await request.json()text = (body.get("text") or "").strip()if not text:return JSONResponse({"error": "text is required"}, status_code=400)updated = add_memory(text)return {"memories": updated}@demo.app.delete("/v1/memories/{index}")def api_delete_memory(index: int):if remove_memory_by_index(index):return {"memories": get_memories()}return JSONResponse({"error": "index out of range"}, status_code=404)@demo.app.post("/v1/chat/completions")async def chat_completions(request: Request):if llm is None:return JSONResponse({"error": "Model is still loading, try again in a moment."}, status_code=503)body = await request.json()messages = body.get("messages", [])max_tokens = int(body.get("max_tokens", 512))temperature = float(body.get("temperature", 0.7))stream = body.get("stream", False)model_id = body.get("model", "lumen")use_memories = body.get("use_memories", False)sys_prompt = build_system_prompt() if use_memories else SYSTEM_PROMPTif not any(m.get("role") == "system" for m in messages):messages = [{"role": "system", "content": sys_prompt}] + messagesif stream:async def event_stream():resp_id = "chatcmpl-" + uuid.uuid4().hexcreated = int(time.time())q = queue_mod.Queue(maxsize=64)DONE = object()def produce():try:with infer_lock:for chunk in llm.create_chat_completion(messages = messages,max_tokens = max_tokens,temperature = temperature,stream = True,):q.put(chunk)except Exception as e:q.put(e)finally:q.put(DONE)threading.Thread(target=produce, daemon=True).start()while True:chunk = await asyncio.to_thread(q.get)if chunk is DONE:breakif isinstance(chunk, Exception):yield f"data: {json.dumps({'error': str(chunk)})}\n\n"breakdelta = chunk["choices"][0]["delta"]finish = chunk["choices"][0].get("finish_reason")data = {"id": resp_id,"object": "chat.completion.chunk","created": created,"model": model_id,"choices": [{"index": 0, "delta": delta, "finish_reason": finish}],}yield f"data: {json.dumps(data)}\n\n"yield "data: [DONE]\n\n"return StreamingResponse(event_stream(), media_type="text/event-stream")def generate():with infer_lock:return llm.create_chat_completion(messages = messages,max_tokens = max_tokens,temperature = temperature,stream = False,)result = await asyncio.to_thread(generate)return JSONResponse(result)
app.py+116-181