p2test2 commited on
Commit
8ee11f6
·
verified ·
1 Parent(s): 08eff5d

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +285 -0
app.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import time
4
+ import subprocess
5
+
6
+ import requests
7
+ from huggingface_hub import hf_hub_download
8
+
9
+ # ----------------------- config (override via Space variables) -----------------------
10
+ # Serves the copied 0.8B GGUF from anon334test/qwopus.
11
+ MODEL_REPO = os.environ.get("MODEL_REPO", "anon334test/qwopus")
12
+ GGUF_FILE = os.environ.get("GGUF_FILE", "Qwen3.5-0.8B.Q4_K_M.gguf")
13
+ HF_TOKEN = os.environ.get("HF_TOKEN") # optional; model is public
14
+ PORT = int(os.environ.get("PORT", "7860"))
15
+ LLAMA_PORT = int(os.environ.get("LLAMA_PORT", "8080"))
16
+ # IMPORTANT: cpu-basic = 2 physical vCPU, but os.cpu_count() reports the HOST core
17
+ # count (e.g. 32/64) inside the cgroup -> launching -t with that number oversubscribes
18
+ # the 2 vCPU and collapses throughput (~0.1 tok/s). Default to 2; override via NUM_THREADS.
19
+ NUM_THREADS = os.environ.get("NUM_THREADS", "2")
20
+ BIN = "/opt/llamabin"
21
+ # Custom chat template that adds an enable_thinking toggle (the model's own template
22
+ # ALWAYS opens a <think> block; this lets "Fast (no thinking)" actually skip reasoning).
23
+ CHAT_TEMPLATE_FILE = os.environ.get("CHAT_TEMPLATE_FILE", "/home/user/app/chat_template.jinja")
24
+ LLAMA = f"http://127.0.0.1:{LLAMA_PORT}"
25
+ # Qwen3.5-0.8B native context = 262144. We default to a generous 32768 window (good for
26
+ # large files / long chats) while keeping startup + memory reasonable on CPU; raise N_CTX up
27
+ # to 262144 via a Space variable if you really need it (much slower prefill on CPU).
28
+ N_CTX = os.environ.get("N_CTX", "32768")
29
+
30
+
31
+ def _env():
32
+ e = os.environ.copy()
33
+ e["LD_LIBRARY_PATH"] = BIN + ":" + e.get("LD_LIBRARY_PATH", "")
34
+ return e
35
+
36
+
37
+ # ----------------------- step 1: download the GGUF (no conversion) -----------------------
38
+ def ensure_gguf():
39
+ print(f"[init] downloading {GGUF_FILE} from {MODEL_REPO} ...", flush=True)
40
+ path = hf_hub_download(MODEL_REPO, GGUF_FILE, repo_type="model", token=HF_TOKEN)
41
+ print(f"[init] model ready: {path}", flush=True)
42
+ return path
43
+
44
+
45
+ # ----------------------- step 2: launch internal llama-server -----------------------
46
+ def start_llama(model_path):
47
+ cmd = [
48
+ os.path.join(BIN, "llama-server"),
49
+ "-m", model_path, "--host", "127.0.0.1", "--port", str(LLAMA_PORT),
50
+ "-c", N_CTX, "-t", NUM_THREADS, "-b", "256", "--no-mmap",
51
+ "--parallel", os.environ.get("PARALLEL", "1"),
52
+ # Apply our chat template (adds enable_thinking toggle for true fast mode).
53
+ "--jinja",
54
+ ]
55
+ if CHAT_TEMPLATE_FILE and os.path.exists(CHAT_TEMPLATE_FILE):
56
+ cmd += ["--chat-template-file", CHAT_TEMPLATE_FILE]
57
+ # Separate the <think> chain-of-thought into reasoning_content so the answer stays clean.
58
+ cmd += ["--reasoning-format", "auto"]
59
+ print(f"[init] cpu_count={os.cpu_count()} threads={NUM_THREADS}", flush=True)
60
+ # Optional extra flags (e.g. "-fa on") via LLAMA_EXTRA_ARGS, space separated.
61
+ extra = os.environ.get("LLAMA_EXTRA_ARGS", "").split()
62
+ if extra:
63
+ cmd += extra
64
+ print("[init] starting internal llama-server: " + " ".join(cmd), flush=True)
65
+ subprocess.Popen(cmd, env=_env())
66
+ for _ in range(900):
67
+ try:
68
+ r = requests.get(LLAMA + "/health", timeout=3)
69
+ if r.status_code == 200 and r.json().get("status") == "ok":
70
+ print("[init] internal llama-server is healthy.", flush=True)
71
+ return
72
+ except Exception:
73
+ pass
74
+ time.sleep(1)
75
+ raise RuntimeError("internal llama-server did not become healthy in time")
76
+
77
+
78
+ # ============================================================================
79
+ # Serving: thin PASS-THROUGH proxy to llama-server's native OpenAI endpoints.
80
+ # llama-server applies the model's embedded chat template (--jinja) itself, so
81
+ # what the model sees is exactly the messages you send -- nothing injected.
82
+ # ============================================================================
83
+ from fastapi import FastAPI, Request
84
+ from fastapi.responses import StreamingResponse, JSONResponse, HTMLResponse, Response
85
+ from fastapi.middleware.cors import CORSMiddleware
86
+
87
+ app = FastAPI()
88
+ app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=False,
89
+ allow_methods=["*"], allow_headers=["*"])
90
+
91
+ # Sensible defaults (only applied when the caller doesn't set them). Overridable per request.
92
+ # max_tokens = -1 -> UNLIMITED output (generate until EOS or the context window is full).
93
+ DEFAULTS = {"temperature": 0.3, "top_p": 0.9, "top_k": 20, "repeat_penalty": 1.05,
94
+ "max_tokens": int(os.environ.get("MAX_TOKENS", "-1"))}
95
+
96
+
97
+ @app.get("/health")
98
+ def health():
99
+ return {"status": "ok"}
100
+
101
+
102
+ @app.get("/v1/models")
103
+ def models():
104
+ try:
105
+ return JSONResponse(requests.get(LLAMA + "/v1/models", timeout=15).json())
106
+ except Exception:
107
+ return {"object": "list", "data": [{"id": GGUF_FILE, "object": "model", "owned_by": "anon334test"}]}
108
+
109
+
110
+ # ----- Lightweight branding: short identity prompt that does NOT suppress reasoning -----
111
+ # Kept short on purpose: long/defensive prompts make small models reason worse (see report.md).
112
+ # Empty by default for a 0.8B model so nothing dilutes its limited attention; set SYSTEM_PROMPT
113
+ # as a Space variable to enable an identity line.
114
+ SYSTEM_PROMPT = os.environ.get("SYSTEM_PROMPT", "").strip()
115
+
116
+
117
+ def _prep(body):
118
+ """Apply defaults and translate convenience fields, then leave everything else untouched
119
+ so all OpenAI / llama.cpp params pass straight through to the model.
120
+
121
+ Thinking control (Qwen3.5): accept a top-level `enable_thinking` bool or a friendly
122
+ `thinking: "on"|"off"`. Both map to chat_template_kwargs.enable_thinking, honored by the
123
+ model's own chat template. If neither is given, the model's default applies.
124
+ """
125
+ for k, v in DEFAULTS.items():
126
+ body.setdefault(k, v)
127
+
128
+ think = None
129
+ if "enable_thinking" in body:
130
+ think = bool(body.pop("enable_thinking"))
131
+ if "thinking" in body:
132
+ t = str(body.pop("thinking")).lower()
133
+ think = t in ("on", "true", "1", "yes", "smart")
134
+ if think is not None:
135
+ ctk = dict(body.get("chat_template_kwargs") or {})
136
+ ctk["enable_thinking"] = think
137
+ body["chat_template_kwargs"] = ctk
138
+
139
+ # Optional identity injection (only if SYSTEM_PROMPT is set).
140
+ if SYSTEM_PROMPT:
141
+ msgs = body.get("messages")
142
+ if isinstance(msgs, list):
143
+ msgs = [m for m in msgs
144
+ if not (isinstance(m, dict) and m.get("role") == "system")]
145
+ msgs.insert(0, {"role": "system", "content": SYSTEM_PROMPT})
146
+ body["messages"] = msgs
147
+ return body
148
+
149
+
150
+ @app.post("/v1/chat/completions")
151
+ async def chat_completions(request: Request):
152
+ body = _prep(await request.json())
153
+ stream = bool(body.get("stream", False))
154
+ if stream:
155
+ def gen():
156
+ with requests.post(LLAMA + "/v1/chat/completions", json=body, stream=True, timeout=900) as r:
157
+ for chunk in r.iter_content(chunk_size=None):
158
+ if chunk:
159
+ yield chunk
160
+ return StreamingResponse(gen(), media_type="text/event-stream")
161
+ r = requests.post(LLAMA + "/v1/chat/completions", json=body, timeout=900)
162
+ return Response(content=r.content, media_type="application/json", status_code=r.status_code)
163
+
164
+
165
+ @app.post("/v1/completions")
166
+ async def completions(request: Request):
167
+ body = _prep(await request.json())
168
+ stream = bool(body.get("stream", False))
169
+ if stream:
170
+ def gen():
171
+ with requests.post(LLAMA + "/v1/completions", json=body, stream=True, timeout=900) as r:
172
+ for chunk in r.iter_content(chunk_size=None):
173
+ if chunk:
174
+ yield chunk
175
+ return StreamingResponse(gen(), media_type="text/event-stream")
176
+ r = requests.post(LLAMA + "/v1/completions", json=body, timeout=900)
177
+ return Response(content=r.content, media_type="application/json", status_code=r.status_code)
178
+
179
+
180
+ @app.get("/", response_class=HTMLResponse)
181
+ def index():
182
+ return INDEX_HTML
183
+
184
+
185
+ INDEX_HTML = """<!DOCTYPE html>
186
+ <html lang="en">
187
+ <head>
188
+ <meta charset="utf-8"/>
189
+ <meta name="viewport" content="width=device-width, initial-scale=1"/>
190
+ <title>Qwopus3.5-0.8B Chat</title>
191
+ <style>
192
+ :root { color-scheme: light dark; }
193
+ * { box-sizing: border-box; }
194
+ body { margin:0; font-family: ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif;
195
+ background:#0b0d12; color:#e7e9ee; display:flex; flex-direction:column; height:100vh; }
196
+ header { padding:12px 18px; border-bottom:1px solid #1e2430; font-weight:600; font-size:15px;
197
+ display:flex; align-items:center; gap:8px; }
198
+ header .dot { width:8px; height:8px; border-radius:50%; background:#33d17a; }
199
+ header small { font-weight:400; opacity:.55; }
200
+ #chat { flex:1; overflow-y:auto; padding:18px; display:flex; flex-direction:column; gap:14px; }
201
+ .msg { max-width:820px; width:100%; margin:0 auto; }
202
+ .who { font-size:12px; opacity:.6; margin-bottom:4px; }
203
+ .bubble { padding:10px 14px; border-radius:12px; white-space:pre-wrap; line-height:1.55;
204
+ font-size:14.5px; word-wrap:break-word; overflow-wrap:anywhere; }
205
+ .user { display:flex; justify-content:flex-end; }
206
+ .user .bubble { background:#1d4ed8; color:#fff; }
207
+ .bot .bubble { background:#161b24; border:1px solid #232a36; }
208
+ pre { background:#0f131b; border:1px solid #232a36; border-radius:8px; padding:10px;
209
+ overflow-x:auto; font-size:13px; }
210
+ footer { border-top:1px solid #1e2430; padding:12px; }
211
+ form { max-width:820px; margin:0 auto; display:flex; gap:8px; }
212
+ textarea { flex:1; resize:none; background:#11151d; color:#e7e9ee; border:1px solid #232a36;
213
+ border-radius:10px; padding:11px 12px; font-size:14.5px; max-height:160px; }
214
+ button { background:#1d4ed8; color:#fff; border:0; border-radius:10px; padding:0 18px;
215
+ font-weight:600; cursor:pointer; }
216
+ button:disabled { opacity:.5; cursor:default; }
217
+ .hint { text-align:center; opacity:.45; font-size:12px; margin-top:8px; }
218
+ .typing { opacity:.5; font-style:italic; }
219
+ .row { max-width:820px; margin:0 auto 8px; display:flex; gap:8px; }
220
+ .row button { background:#232a36; font-weight:500; font-size:12px; padding:4px 10px; }
221
+ .think { max-width:820px; width:100%; margin:0 auto 6px; font-size:13px; opacity:.75;
222
+ background:#0f131b; border:1px dashed #2a3340; border-radius:10px; padding:6px 12px; }
223
+ .think summary { cursor:pointer; user-select:none; }
224
+ .think-body { white-space:pre-wrap; margin-top:6px; line-height:1.5; }
225
+ </style>
226
+ </head>
227
+ <body>
228
+ <header><span class="dot"></span> Qwopus3.5-0.8B <small>&middot; Qwen3.5 0.8B &middot; fast chat / reasoning &middot; live GGUF</small>
229
+ <label style="margin-left:auto; font-weight:400; font-size:13px; display:flex; align-items:center; gap:6px;">Mode
230
+ <select id="mode" style="background:#11151d; color:#e7e9ee; border:1px solid #232a36; border-radius:8px; padding:4px 8px; font-size:13px;">
231
+ <option value="off" selected>&#9889; Fast (no thinking)</option>
232
+ <option value="on">&#129504; Smart (thinking)</option>
233
+ </select>
234
+ </label>
235
+ </header>
236
+ <div id="chat"></div>
237
+ <footer>
238
+ <div class="row"><button id="reset" type="button">New chat</button></div>
239
+ <form id="f">
240
+ <textarea id="t" rows="1" placeholder="Ask anything..." autofocus></textarea>
241
+ <button id="send" type="submit">Send</button>
242
+ </form>
243
+ <div class="hint">Pure model &middot; OpenAI-compatible API at <code>/v1/chat/completions</code></div>
244
+ </footer>
245
+ <script>
246
+ const chat=document.getElementById('chat'),form=document.getElementById('f'),ta=document.getElementById('t'),sendBtn=document.getElementById('send');
247
+ let history=[];
248
+ function esc(s){return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');}
249
+ function render(t){return esc(t).replace(/```([\\s\\S]*?)```/g,(m,c)=>'<pre><code>'+c.replace(/^\\w*\\n/,'')+'</code></pre>');}
250
+ function stripThink(t){return t.replace(/<think>[\\s\\S]*?<\\/think>/gi,'').replace(/^[\\s\\S]*?<\\/think>/i, m=>m.includes('<think>')?'':m).trim();}
251
+ function addUser(t){const w=document.createElement('div');w.className='msg user';w.innerHTML='<div class="bubble">'+render(t)+'</div>';chat.appendChild(w);chat.scrollTop=chat.scrollHeight;}
252
+ function addBot(){const w=document.createElement('div');w.className='msg bot';w.innerHTML='<div class="who">Assistant</div><details class="think" style="display:none"><summary>&#129504; Thinking</summary><div class="think-body"></div></details><div class="bubble"><span class="typing">&hellip;</span></div>';chat.appendChild(w);chat.scrollTop=chat.scrollHeight;return {think:w.querySelector('.think'),thinkBody:w.querySelector('.think-body'),bubble:w.querySelector('.bubble')};}
253
+ document.getElementById('reset').onclick=()=>{history=[];chat.innerHTML='';ta.focus();};
254
+ ta.addEventListener('input',()=>{ta.style.height='auto';ta.style.height=Math.min(ta.scrollHeight,160)+'px';});
255
+ ta.addEventListener('keydown',e=>{if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();form.requestSubmit();}});
256
+ form.addEventListener('submit',async e=>{
257
+ e.preventDefault();const text=ta.value.trim();if(!text)return;
258
+ ta.value='';ta.style.height='auto';addUser(text);history.push({role:'user',content:text});
259
+ sendBtn.disabled=true;const {think,thinkBody,bubble}=addBot();let acc='';let rc='';
260
+ try{
261
+ const resp=await fetch('/v1/chat/completions',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({messages:history,stream:true,thinking:document.getElementById('mode').value})});
262
+ const reader=resp.body.getReader(),dec=new TextDecoder();let buf='';
263
+ while(true){const {value,done}=await reader.read();if(done)break;buf+=dec.decode(value,{stream:true});let idx;
264
+ while((idx=buf.indexOf('\\n\\n'))>=0){const line=buf.slice(0,idx).trim();buf=buf.slice(idx+2);
265
+ if(!line.startsWith('data:'))continue;const data=line.slice(5).trim();if(data==='[DONE]')continue;
266
+ try{const o=JSON.parse(data);const dl=o.choices?.[0]?.delta||{};
267
+ const rd=dl.reasoning_content||'';if(rd){rc+=rd;think.style.display='block';thinkBody.textContent=rc;chat.scrollTop=chat.scrollHeight;}
268
+ const d=dl.content||'';if(d){acc+=d;bubble.innerHTML=render(stripThink(acc));chat.scrollTop=chat.scrollHeight;}
269
+ }catch(_){}}}
270
+ }catch(err){acc=acc||('[error] '+err);bubble.innerHTML=render(acc);}
271
+ const clean=stripThink(acc);if(!clean)bubble.innerHTML=render('(no response)');
272
+ history.push({role:'assistant',content:clean});sendBtn.disabled=false;ta.focus();
273
+ });
274
+ </script>
275
+ </body>
276
+ </html>"""
277
+
278
+
279
+ # ----------------------- main -----------------------
280
+ if __name__ == "__main__":
281
+ model_path = ensure_gguf()
282
+ start_llama(model_path)
283
+ import uvicorn
284
+ print(f"[init] starting public proxy on port {PORT} ...", flush=True)
285
+ uvicorn.run(app, host="0.0.0.0", port=PORT, log_level="info")