Update main.py
Browse files1234510 unmodified lines1617181920212223242526272829305 unmodified lines3637383940416 unmodified lines4849505152535455565758591 unmodified line6162636465666718 unmodified lines86878889909192939495969798991001011021 unmodified line10410510610710810911011111211311411511611711 unmodified lines12913013113213313413513620 unmodified lines15715815916016116216316416516611 unmodified lines17817918018118218318418518618718818919019119219319419519618 unmodified lines21521621721821922010 unmodified lines2312322332342352362377 unmodified lines2452462472482492502512522532542552562572581 unmodified line2602612622632642652662672682692702712722732742752762772782792802812822832842856 unmodified lines2922932942952962972982993003013023033043053061 unmodified line3083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493501 unmodified line3523533543553563573583593603613623633643653669 unmodified lines3763773783793803813823833843853863873883893903913923933943953963973983994004014029 unmodified lines4124134144154164174184194204214224234244254264274282 unmodified lines43143243343443543643743843944044144244344444544644744844945045145245345445545645745845946020 unmodified lines481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514"""NanoMind — FastAPI Backend v1.0152M GPT-2 · AVX2 + OpenMP · Persistent KV-CacheRAM Budget (HF 16GB Space):10 unmodified linesMulti-User Mode:N_ENGINES=4, OMP_NUM_THREADS=1→ 4 parallel users, ~35 tok/s each"""import asyncio, json, os, time, uuidfrom contextlib import asynccontextmanagerfrom pathlib import Pathimport psutilimport tiktokenfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponse, StreamingResponsefrom pydantic import BaseModel, Field5 unmodified linesBASE_DIR = Path(__file__).parentINFERENCE_EXE = BASE_DIR / "inference"MODEL_BIN = BASE_DIR / "model.bin"HF_REPO_ID = os.environ.get("HF_REPO_ID", "NOT-OMEGA/NanoMind")SYSTEM_TOKEN = "System:"6 unmodified linesSAFETY_MARGIN = 24MAX_SESSION_TOKENS = BLOCK_SIZE - MAX_GEN_CEILING - SAFETY_MARGIN # 500# Speed Mode: 1 engine, 2 OMP threads → all CPU cores for one request# Multi Mode: 4 engines, 1 OMP thread → 4 parallel usersN_ENGINES = int(os.environ.get("N_ENGINES", "1")) # default: speed modeOMP_PER_ENGINE = int(os.environ.get("OMP_NUM_THREADS", "2")) # default: 2 threadsSESSION_TTL_S = int(os.environ.get("SESSION_TTL", "1800")) # 30 minenc = tiktoken.get_encoding("gpt2")STOP_TOKEN_IDS = [50256]1 unmodified line# ─────────────────────────────────────────────────────────────────────────# Inference Engine (single C++ process)# ─────────────────────────────────────────────────────────────────────────class InferenceEngine:def __init__(self, eid: int):18 unmodified linescwd=str(BASE_DIR),env=env,)while True:line = (await self._proc.stdout.readline()).decode().strip()if line == "READY":self._ready = Trueprint(f"[engine-{self.eid}] READY pid={self._proc.pid} "f"OMP_NUM_THREADS={OMP_PER_ENGINE}")breakif line.startswith("ERROR"):raise RuntimeError(f"Engine-{self.eid} startup error: {line}")async def stop(self):if self._proc:try:self._proc.stdin.write(b"QUIT\n")1 unmodified lineawait asyncio.wait_for(self._proc.wait(), timeout=3.0)except Exception:self._proc.kill()async def reset_session(self, session_id: str):self._proc.stdin.write(f"RESET|{session_id}\n".encode())await self._proc.stdin.drain()while True:raw = await self._proc.stdout.readline()if not raw or raw.decode().strip() == "RESET_OK":breakasync def generate(self, session_id, new_token_ids, max_new, temperature, top_k):if not self._ready or self._proc is None:11 unmodified linestry:while True:raw = await self._proc.stdout.readline()if not raw:breakline = raw.decode("utf-8", errors="replace").strip()if not line:20 unmodified linesbreakexcept asyncio.CancelledError:while True:raw = await self._proc.stdout.readline()if not raw or raw.decode().strip().startswith(("DONE", "ERROR")):breakraise@property11 unmodified linesself._locks: list[asyncio.Lock] = []self._session_map: dict[str, int] = {}self._engine_load: list[int] = []self._map_lock = Noneasync def start(self):self._map_lock = asyncio.Lock()self._locks = [asyncio.Lock() for _ in range(self.n)]self._engine_load = [0] * self.nawait asyncio.gather(*(e.start() for e in self.engines))print(f"[pool] {self.n} engine(s) ready "f"(OMP_NUM_THREADS={OMP_PER_ENGINE} each)")async def stop(self):await asyncio.gather(*(e.stop() for e in self.engines),return_exceptions=True)async def _assign(self, session_id: str) -> int:async with self._map_lock:18 unmodified linesyield chunkasync def reset_session(self, session_id: str):async with self._map_lock:idx = self._session_map.get(session_id)if idx is not None:10 unmodified lines"engine_id": i,"pid": self.engines[i].pid,"sessions": self._engine_load[i],"busy": self._locks[i].locked(),"ready": self.engines[i]._ready,}for i in range(self.n)7 unmodified lines# Session State# ─────────────────────────────────────────────────────────────────────────class SessionData:def __init__(self, system_prompt: str):self.system_prompt = system_promptself.history: list = []self.tokens_in_engine = 0self.last_active = time.time()def touch(self):self.last_active = time.time()def append_user(self, content: str):self.history.append({"role": "user", "content": content})1 unmodified linedef append_assistant(self, content: str):self.history.append({"role": "assistant", "content": content})def new_turn_tokens(self, user_msg: str) -> list:if self.tokens_in_engine == 0:full = (f"{SYSTEM_TOKEN} {self.system_prompt}{SEP}"f"{USER_TOKEN} {user_msg}{SEP}{ASST_TOKEN} ")return enc.encode_ordinary(full)else:return enc.encode_ordinary(f"{USER_TOKEN} {user_msg}{SEP}{ASST_TOKEN} ")sessions: dict[str, SessionData] = {}metrics = {"total_requests": 0,"total_tokens": 0,"total_ms": 0.0,"errors": 0,"start_time": time.time(),"sessions_evicted": 0,}6 unmodified linestotal += psutil.Process(pid).memory_info().rssexcept psutil.NoSuchProcess:passreturn round(total / 1e6, 1)except Exception:return 0.0async def session_gc_loop():while True:await asyncio.sleep(300)now = time.time()expired = [sid for sid, s in list(sessions.items())if now - s.last_active > SESSION_TTL_S1 unmodified linefor sid in expired:sessions.pop(sid, None)await pool.reset_session(sid)metrics["sessions_evicted"] += 1if expired:print(f"[GC] Evicted {len(expired)} idle sessions")async def _startup_background():try:if not MODEL_BIN.exists():print("[HF HUB] Downloading model.bin…")hf_hub_download(repo_id=HF_REPO_ID, filename="model.bin",local_dir=str(BASE_DIR))if not (BASE_DIR / "tokenizer.bin").exists():print("[HF HUB] Downloading tokenizer.bin…")hf_hub_download(repo_id=HF_REPO_ID, filename="tokenizer.bin",local_dir=str(BASE_DIR))except Exception as e:print(f"[WARN] HF download: {e}")try:await pool.start()except Exception as e:print(f"[ERROR] Pool start: {e}")@asynccontextmanagerasync def lifespan(app: FastAPI):asyncio.create_task(_startup_background())asyncio.create_task(session_gc_loop())yieldawait pool.stop()app = FastAPI(title="NanoMind", version="1.0.0", lifespan=lifespan)app.add_middleware(CORSMiddleware,allow_origins=["*"], allow_methods=["*"], allow_headers=["*"],1 unmodified line# ─────────────────────────────────────────────────────────────────────────# Request Models# ─────────────────────────────────────────────────────────────────────────class ChatRequest(BaseModel):message: strsession_id: str = Field(default_factory=lambda: str(uuid.uuid4()))system_prompt: str = "You are a helpful, thoughtful, and articulate AI assistant."max_new_tokens: int = Field(default=200, ge=1, le=500)temperature: float = Field(default=0.7, ge=0.01, le=2.0)top_k: int = Field(default=40, ge=1, le=200)class ResetRequest(BaseModel):9 unmodified lines@app.get("/health")async def health():mem = psutil.virtual_memory()ready_count = sum(1 for e in pool.engines if e._ready)return {"status": "ok" if ready_count > 0 else "starting","engines_ready": ready_count,"engines_total": N_ENGINES,"omp_threads_per_engine": OMP_PER_ENGINE,"speed_mode": N_ENGINES == 1,"active_sessions": len(sessions),"sessions_evicted": metrics["sessions_evicted"],"process_ram_mb": get_total_ram_mb(),"system_ram_used_pct": mem.percent,"uptime_seconds": round(time.time() - metrics["start_time"], 1),}@app.get("/pool/status")async def pool_status():return {"n_engines": N_ENGINES, "omp_per_engine": OMP_PER_ENGINE,"engines": pool.status(), "sessions": len(sessions)}@app.post("/chat")9 unmodified linesnew_tokens = sess.new_turn_tokens(req.message)if sess.tokens_in_engine + len(new_tokens) + req.max_new_tokens > MAX_SESSION_TOKENS:await pool.reset_session(req.session_id)sess.tokens_in_engine = 0new_tokens = sess.new_turn_tokens(req.message)sess.append_user(req.message)metrics["total_requests"] += 1async def event_stream():parts: list[str] = []t0 = time.time()try:async for chunk in pool.generate(req.session_id, new_tokens,2 unmodified linesif chunk["type"] == "token":parts.append(chunk["text"])joined = "".join(parts)hit = any(f"\n{s}" in joined for s in STOP_STRINGS)if hit:for s in STOP_STRINGS:idx = joined.find(f"\n{s}")if idx != -1:parts = [joined[:idx]]breakyield f"data: {json.dumps(chunk)}\n\n"elif chunk["type"] == "done":reply = "".join(parts).strip()sess.append_assistant(reply)sess.tokens_in_engine += len(new_tokens) + chunk["total_tokens"]metrics["total_tokens"] += chunk["total_tokens"]metrics["total_ms"] += (time.time() - t0) * 1000yield f"data: {json.dumps({**chunk, 'session_id': req.session_id, 'full_response': reply})}\n\n"elif chunk["type"] == "error":metrics["errors"] += 1yield f"data: {json.dumps(chunk)}\n\n"except Exception as e:metrics["errors"] += 1yield f"data: {json.dumps({'type': 'error', 'message': str(e)})}\n\n"finally:yield "data: [DONE]\n\n"20 unmodified lines"session_id": session_id,"turns": sum(1 for m in sess.history if m["role"] == "user"),"tokens_in_engine": sess.tokens_in_engine,"last_active_ago_s": round(time.time() - sess.last_active, 1),"history": sess.history,}@app.get("/metrics")async def get_metrics():n, tok, ms = (metrics["total_requests"],metrics["total_tokens"],metrics["total_ms"],)mem = psutil.virtual_memory()return {"total_requests": n,"total_tokens": tok,"total_errors": metrics["errors"],"avg_tps": round(tok / (ms / 1000), 2) if ms > 0 else 0,"active_sessions": len(sessions),"sessions_evicted_total":metrics["sessions_evicted"],"n_engines": N_ENGINES,"omp_per_engine": OMP_PER_ENGINE,"engines_ready": sum(1 for e in pool.engines if e._ready),"engines_busy": sum(1 for lk in pool._locks if lk.locked()),"process_ram_mb": get_total_ram_mb(),"system_ram_used_pct": mem.percent,"system_ram_total_gb": round(mem.total / 1e9, 1),"uptime_s": round(time.time() - metrics["start_time"], 1),}1234510 unmodified lines16171819202122232425262728293031323334353637383940414243445 unmodified lines505152535455566 unmodified lines6364656667686970711 unmodified line7374757677787918 unmodified lines98991001011021031041051061071081091101111121131141151161171181191201211221231241 unmodified line12612712812913013113213313413513613713813914014114214314414514614711 unmodified lines15916016116216316416516616716816920 unmodified lines19019119219319419519619719819920020120220320420520611 unmodified lines21821922022122222322422522622722822923023123223323418 unmodified lines25325425525625725825926010 unmodified lines2712722732742752762777 unmodified lines2852862872882892902912922932942952962972982993001 unmodified line3023033043053063073083093103113123133143153163173183193203213223233243253263273286 unmodified lines3353363373383393403413423433443453463473483493503513521 unmodified line3543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204211 unmodified line4234244254264274284294304314324334344354364379 unmodified lines4474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814829 unmodified lines4924934944954964974984995005015025035045055065075085095105115125132 unmodified lines51651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557620 unmodified lines597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632"""NanoMind — FastAPI Backend v1.1152M GPT-2 · AVX2 + OpenMP · Persistent KV-CacheRAM Budget (HF 16GB Space):10 unmodified linesMulti-User Mode:N_ENGINES=4, OMP_NUM_THREADS=1→ 4 parallel users, ~35 tok/s eachFixes in v1.1:- hf_hub_download: local_dir_use_symlinks=False (fixes /tmp_xxx crash)- download runs in executor so it doesn't block the event loop- pool.start() only called after BOTH files are confirmed present- reset_session: lock held before engine call (race-condition fix)- event_stream: stop-string hit now drains C++ stdout correctly- metrics protected by asyncio.Lock (avoids torn reads under load)- engine restart on unexpected process death- /health returns 503 HTTP status while starting (not just JSON field)"""import asyncioimport jsonimport osimport timeimport uuidfrom contextlib import asynccontextmanagerfrom pathlib import Pathimport psutilimport tiktokenfrom fastapi import FastAPI, HTTPException, Responsefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponse, StreamingResponsefrom pydantic import BaseModel, Field5 unmodified linesBASE_DIR = Path(__file__).parentINFERENCE_EXE = BASE_DIR / "inference"MODEL_BIN = BASE_DIR / "model.bin"TOKENIZER_BIN = BASE_DIR / "tokenizer.bin"HF_REPO_ID = os.environ.get("HF_REPO_ID", "NOT-OMEGA/NanoMind")SYSTEM_TOKEN = "System:"6 unmodified linesSAFETY_MARGIN = 24MAX_SESSION_TOKENS = BLOCK_SIZE - MAX_GEN_CEILING - SAFETY_MARGIN # 500N_ENGINES = int(os.environ.get("N_ENGINES", "1"))OMP_PER_ENGINE = int(os.environ.get("OMP_NUM_THREADS", "2"))SESSION_TTL_S = int(os.environ.get("SESSION_TTL", "1800"))enc = tiktoken.get_encoding("gpt2")STOP_TOKEN_IDS = [50256]1 unmodified line# ─────────────────────────────────────────────────────────────────────────# Inference Engine# ─────────────────────────────────────────────────────────────────────────class InferenceEngine:def __init__(self, eid: int):18 unmodified linescwd=str(BASE_DIR),env=env,)# Wait for READY with a 60-second timeouttry:async with asyncio.timeout(60):while True:raw = await self._proc.stdout.readline()if not raw:raise RuntimeError(f"Engine-{self.eid}: process exited before READY")line = raw.decode().strip()if line == "READY":self._ready = Trueprint(f"[engine-{self.eid}] READY pid={self._proc.pid} "f"OMP_NUM_THREADS={OMP_PER_ENGINE}")breakif line.startswith("ERROR"):raise RuntimeError(f"Engine-{self.eid} startup error: {line}")except TimeoutError:self._proc.kill()raise RuntimeError(f"Engine-{self.eid} timed out waiting for READY")async def stop(self):self._ready = Falseif self._proc:try:self._proc.stdin.write(b"QUIT\n")1 unmodified lineawait asyncio.wait_for(self._proc.wait(), timeout=3.0)except Exception:self._proc.kill()self._proc = Noneasync def reset_session(self, session_id: str):"""Tell C++ engine to drop KV-cache for this session."""if not self._ready or self._proc is None:returnself._proc.stdin.write(f"RESET|{session_id}\n".encode())await self._proc.stdin.drain()# Drain until RESET_OK (ignore stray blank lines)async with asyncio.timeout(5):while True:raw = await self._proc.stdout.readline()if not raw:breakif raw.decode().strip() == "RESET_OK":breakasync def generate(self, session_id, new_token_ids, max_new, temperature, top_k):if not self._ready or self._proc is None:11 unmodified linestry:while True:raw = await self._proc.stdout.readline()if not raw:# Process died unexpectedlyself._ready = Falseyield {"type": "error", "message": "Engine process died"}breakline = raw.decode("utf-8", errors="replace").strip()if not line:20 unmodified linesbreakexcept asyncio.CancelledError:# Client disconnected — drain until C++ finishes this requesttry:async with asyncio.timeout(5):while True:raw = await self._proc.stdout.readline()if not raw:breakif raw.decode().strip().startswith(("DONE", "ERROR")):breakexcept Exception:passraise@property11 unmodified linesself._locks: list[asyncio.Lock] = []self._session_map: dict[str, int] = {}self._engine_load: list[int] = []self._map_lock: asyncio.Lock | None = Noneasync def start(self):self._map_lock = asyncio.Lock()self._locks = [asyncio.Lock() for _ in range(self.n)]self._engine_load = [0] * self.nawait asyncio.gather(*(e.start() for e in self.engines))print(f"[pool] {self.n} engine(s) ready (OMP_NUM_THREADS={OMP_PER_ENGINE} each)")async def stop(self):await asyncio.gather(*(e.stop() for e in self.engines), return_exceptions=True)async def _assign(self, session_id: str) -> int:async with self._map_lock:18 unmodified linesyield chunkasync def reset_session(self, session_id: str):# FIX: acquire map lock briefly just to read idx, then release before# acquiring engine lock — avoids deadlock with _assign.async with self._map_lock:idx = self._session_map.get(session_id)if idx is not None:10 unmodified lines"engine_id": i,"pid": self.engines[i].pid,"sessions": self._engine_load[i],"busy": self._locks[i].locked() if self._locks else False,"ready": self.engines[i]._ready,}for i in range(self.n)7 unmodified lines# Session State# ─────────────────────────────────────────────────────────────────────────class SessionData:__slots__ = ("system_prompt", "history", "tokens_in_engine", "last_active")def __init__(self, system_prompt: str):self.system_prompt = system_promptself.history: list = []self.tokens_in_engine = 0self.last_active = time.monotonic()def touch(self):self.last_active = time.monotonic()def append_user(self, content: str):self.history.append({"role": "user", "content": content})1 unmodified linedef append_assistant(self, content: str):self.history.append({"role": "assistant", "content": content})def new_turn_tokens(self, user_msg: str) -> list[int]:if self.tokens_in_engine == 0:text = (f"{SYSTEM_TOKEN} {self.system_prompt}{SEP}"f"{USER_TOKEN} {user_msg}{SEP}{ASST_TOKEN} ")else:text = f"{USER_TOKEN} {user_msg}{SEP}{ASST_TOKEN} "return enc.encode_ordinary(text)sessions: dict[str, SessionData] = {}# Use a single dict for metrics — protected by an asyncio.Lock for writes_metrics_lock = None # initialised inside lifespan (needs running loop)metrics = {"total_requests": 0,"total_tokens": 0,"total_ms": 0.0,"errors": 0,"start_time": time.time(),"sessions_evicted": 0,}6 unmodified linestotal += psutil.Process(pid).memory_info().rssexcept psutil.NoSuchProcess:passreturn round(total / 1_000_000, 1)except Exception:return 0.0# ─────────────────────────────────────────────────────────────────────────# Background tasks# ─────────────────────────────────────────────────────────────────────────async def session_gc_loop():while True:await asyncio.sleep(300)now = time.monotonic()expired = [sid for sid, s in list(sessions.items())if now - s.last_active > SESSION_TTL_S1 unmodified linefor sid in expired:sessions.pop(sid, None)await pool.reset_session(sid)async with _metrics_lock:metrics["sessions_evicted"] += 1if expired:print(f"[GC] Evicted {len(expired)} idle sessions")def _download_file(repo_id: str, filename: str, dest: Path):"""Blocking HF download — called in a thread executor."""print(f"[HF HUB] Downloading {filename}…")hf_hub_download(repo_id=repo_id,filename=filename,local_dir=str(dest),local_dir_use_symlinks=False, # ← KEY FIX: no /tmp symlink tricks)print(f"[HF HUB] {filename} ready at {dest / filename}")async def _startup_background():loop = asyncio.get_running_loop()# Download missing files in a thread so the event loop stays responsivetry:if not MODEL_BIN.exists():await loop.run_in_executor(None, _download_file, HF_REPO_ID, "model.bin", BASE_DIR)else:print(f"[HF HUB] model.bin already present ({MODEL_BIN.stat().st_size // 1_000_000}MB)")if not TOKENIZER_BIN.exists():await loop.run_in_executor(None, _download_file, HF_REPO_ID, "tokenizer.bin", BASE_DIR)else:print(f"[HF HUB] tokenizer.bin already present")except Exception as e:print(f"[ERROR] HF download failed: {e}")return # Can't start engines without model# Start engine pool only after files are confirmedtry:await pool.start()except Exception as e:print(f"[ERROR] Pool start failed: {e}")# ─────────────────────────────────────────────────────────────────────────# App lifecycle# ─────────────────────────────────────────────────────────────────────────@asynccontextmanagerasync def lifespan(app: FastAPI):global _metrics_lock_metrics_lock = asyncio.Lock()asyncio.create_task(_startup_background())asyncio.create_task(session_gc_loop())yieldawait pool.stop()app = FastAPI(title="NanoMind", version="1.1.0", lifespan=lifespan)app.add_middleware(CORSMiddleware,allow_origins=["*"], allow_methods=["*"], allow_headers=["*"],1 unmodified line# ─────────────────────────────────────────────────────────────────────────# Request models# ─────────────────────────────────────────────────────────────────────────class ChatRequest(BaseModel):message: strsession_id: str = Field(default_factory=lambda: str(uuid.uuid4()))system_prompt: str = "You are a helpful, thoughtful, and articulate AI assistant."max_new_tokens: int = Field(default=200, ge=1, le=500)temperature: float = Field(default=0.7, ge=0.01, le=2.0)top_k: int = Field(default=40, ge=1, le=200)class ResetRequest(BaseModel):9 unmodified lines@app.get("/health")async def health(response: Response):mem = psutil.virtual_memory()ready_count = sum(1 for e in pool.engines if e._ready)is_ready = ready_count > 0if not is_ready:response.status_code = 503 # callers (bench tool, k8s) get proper HTTP codereturn {"status": "ok" if is_ready else "starting","engines_ready": ready_count,"engines_total": N_ENGINES,"omp_threads_per_engine": OMP_PER_ENGINE,"speed_mode": N_ENGINES == 1,"active_sessions": len(sessions),"sessions_evicted": metrics["sessions_evicted"],"process_ram_mb": get_total_ram_mb(),"system_ram_used_pct": mem.percent,"uptime_seconds": round(time.time() - metrics["start_time"], 1),}@app.get("/pool/status")async def pool_status():return {"n_engines": N_ENGINES,"omp_per_engine": OMP_PER_ENGINE,"engines": pool.status(),"sessions": len(sessions),}@app.post("/chat")9 unmodified linesnew_tokens = sess.new_turn_tokens(req.message)# Context overflow → reset KV-cache for this sessionif sess.tokens_in_engine + len(new_tokens) + req.max_new_tokens > MAX_SESSION_TOKENS:await pool.reset_session(req.session_id)sess.tokens_in_engine = 0new_tokens = sess.new_turn_tokens(req.message)sess.append_user(req.message)async with _metrics_lock:metrics["total_requests"] += 1async def event_stream():parts: list[str] = []t0 = time.perf_counter()stopped_early = Falsetry:async for chunk in pool.generate(req.session_id, new_tokens,2 unmodified linesif chunk["type"] == "token":parts.append(chunk["text"])joined = "".join(parts)# Check stop stringsfor s in STOP_STRINGS:idx = joined.find(f"\n{s}")if idx != -1:parts = [joined[:idx]]stopped_early = Truebreakif stopped_early:breakyield f"data: {json.dumps(chunk)}\n\n"elif chunk["type"] == "done":reply = "".join(parts).strip()elapsed = (time.perf_counter() - t0) * 1000sess.append_assistant(reply)sess.tokens_in_engine += len(new_tokens) + chunk["total_tokens"]async with _metrics_lock:metrics["total_tokens"] += chunk["total_tokens"]metrics["total_ms"] += elapseddone_payload = {**chunk,"session_id": req.session_id,"full_response": reply,}yield f"data: {json.dumps(done_payload)}\n\n"elif chunk["type"] == "error":async with _metrics_lock:metrics["errors"] += 1yield f"data: {json.dumps(chunk)}\n\n"# If we broke early due to stop string, still emit a done eventif stopped_early:reply = "".join(parts).strip()elapsed = (time.perf_counter() - t0) * 1000sess.append_assistant(reply)done_payload = {"type": "done","total_tokens": len(parts),"total_ms": round(elapsed, 2),"tps": 0,"session_id": req.session_id,"full_response": reply,"stopped_early": True,}yield f"data: {json.dumps(done_payload)}\n\n"except Exception as e:async with _metrics_lock:metrics["errors"] += 1yield f"data: {json.dumps({'type': 'error', 'message': str(e)})}\n\n"finally:yield "data: [DONE]\n\n"20 unmodified lines"session_id": session_id,"turns": sum(1 for m in sess.history if m["role"] == "user"),"tokens_in_engine": sess.tokens_in_engine,"last_active_ago_s": round(time.monotonic() - sess.last_active, 1),"history": sess.history,}@app.get("/metrics")async def get_metrics():async with _metrics_lock:n = metrics["total_requests"]tok = metrics["total_tokens"]ms = metrics["total_ms"]err = metrics["errors"]evicted = metrics["sessions_evicted"]mem = psutil.virtual_memory()return {"total_requests": n,"total_tokens": tok,"total_errors": err,"avg_tps": round(tok / (ms / 1000), 2) if ms > 0 else 0,"active_sessions": len(sessions),"sessions_evicted_total": evicted,"n_engines": N_ENGINES,"omp_per_engine": OMP_PER_ENGINE,"engines_ready": sum(1 for e in pool.engines if e._ready),"engines_busy": sum(1 for lk in pool._locks if lk.locked()) if pool._locks else 0,"process_ram_mb": get_total_ram_mb(),"system_ram_used_pct": mem.percent,"system_ram_total_gb": round(mem.total / 1_000_000_000, 1),"uptime_s": round(time.time() - metrics["start_time"], 1),}
main.py+230-112