Spaces:
Running
fix: correct LLM model path default, fix chat 'error: format only' leak, surface load errors
Browse filesRoot causes of LLM: OFFLINE + chat 'error: format only' on the Space:
1. agents.py defaulted MODEL_PATH to the old filename
'models/retro-alpha-nemotron-q4_k_m.gguf'. The actual GGUF file
is 'NVIDIA-Nemotron-3-Nano-4B.Q4_K_M.gguf'. When the model
download failed on the Space (slow network, token scope, or
timeout), MODEL_PATH stayed as the wrong default and get_llm()
raised FileNotFoundError -> _llm_status='error' -> UI OFFLINE.
2. mock_generate() returned the literal 'error: format only' for
any prompt that didn't match its keyword checks. The chat prompt
matched none, so the sentinel leaked to the UI (chat_reply's
'if not text' fallback never fired because the string was truthy).
Fixes:
- agents.py: correct MODEL_PATH default to the actual filename;
capture _llm_error with the exception type+message; print the
resolved model path and size on load
- mock_generate(): return '' for unknown prompts so per-feature
deterministic fallbacks (chat_reply, generate_insight) take over
instead of leaking a sentinel
- download_model.py: robust download that tries with token, then
anonymously, and ALWAYS returns the expected local path (never
raises) so get_llm() can report a precise 'model not found' error
- app.py /api/health: now returns llm_error, model_exists,
model_size_gb so the UI (and the user) can see exactly why the
LLM failed to load
- static/app.js: topbar shows the resolved model path on hover;
status line reports the error reason ('LLM offline (FileNotFoundError...).
Game still works, features use deterministic fallbacks')
- tests: regression checks that chat/insight never return
'error: format only'
110 tests pass: 12 unit + 42 FastAPI E2E + 56 Playwright.
Files changed (5)
- agents.py+34-11
- app.py+6-1
- download_model.py+47-16
- static/app.js+16-1
- tests/e2e_test.py+14
14 unmodified lines151617181920212223242526272829303132333435363738394041424344454647484950515243 unmodified lines969798991001011021032 unmodified lines10610710810911011111211311411511614 unmodified linesASSETS = ["cash", "fd", "gov_bonds", "nifty_50", "nifty_it", "real_estate", "crypto", "gold"]PERSONAS = ["whale", "retail", "permabull"]# Default model path; override via MODEL_PATH env varMODEL_PATH = os.getenv("MODEL_PATH", "models/retro-alpha-nemotron-q4_k_m.gguf")_llm = None_llm_status = "uninitialized" # "loaded" | "mock" | "error"# Allow forcing mock mode for fast local testing / CIif os.getenv("MOCK_LLM") == "1":_llm = "mock"_llm_status = "mock"def llm_status() -> str:return _llm_statusdef get_llm():global _llm, _llm_statusif _llm is None:try:from llama_cpp import Llamaif not Path(MODEL_PATH).exists():raise FileNotFoundError(f"Model not found: {MODEL_PATH}")_llm = Llama(model_path=MODEL_PATH,n_ctx=2048,n_threads=int(os.getenv("LLAMA_THREADS", "4")),verbose=False,)_llm_status = "loaded"except Exception as e:print(f"Warning: could not load LLM: {e}. Using mock mode.")_llm = "mock"_llm_status = "error"return _llm43 unmodified linesdef mock_generate(prompt: str, system: str = "") -> str:"""Deterministic fallback when no model is loaded."""p = prompt.lower()if "agent" in p and "whale" in p:return "agent: whale\naction: buy gov_bonds 0.10\nreason: safety first\nsentiment: cautious"if "agent" in p and "retail" in p:2 unmodified linesreturn "agent: permabull\naction: buy crypto 0.10\nreason: buy the dip\nsentiment: bullish"if "roast" in p or "sharpe_ratio" in p:return "roast: diversify more\nsharpe_ratio: 0.5\nlesson: Sharpe ratio measures risk-adjusted return\nsuggestion: add bonds"if "insight" in p or "commentary" in p:return "insight: Markets are reacting to the headline. Watch for follow-through."if "headline" in p:return "headline: RBI holds rates steady\nimpact: cash:0 fd:0 gov_bonds:0 nifty_50:0 nifty_it:0 real_estate:0 crypto:0 gold:0\nduration: 1"return "error: format only"def parse_agent_response(response: str, persona: str) -> Dict:14 unmodified lines1516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686943 unmodified lines1131141151161171181191201211221231242 unmodified lines12712812913013113213313413513613713813914 unmodified linesASSETS = ["cash", "fd", "gov_bonds", "nifty_50", "nifty_it", "real_estate", "crypto", "gold"]PERSONAS = ["whale", "retail", "permabull"]# Default model path. MUST match the GGUF file in the repo.# Override via MODEL_PATH env var if you use a different filename._DEFAULT_MODEL_DIR = Path(__file__).resolve().parent / "models"_DEFAULT_MODEL_FILE = "NVIDIA-Nemotron-3-Nano-4B.Q4_K_M.gguf"MODEL_PATH = os.getenv("MODEL_PATH") or str(_DEFAULT_MODEL_DIR / _DEFAULT_MODEL_FILE)_llm = None_llm_status = "uninitialized" # "loaded" | "mock" | "error"_llm_error = "" # last load/import error message, surfaced to UI# Allow forcing mock mode for fast local testing / CIif os.getenv("MOCK_LLM") == "1":_llm = "mock"_llm_status = "mock"_llm_error = "MOCK_LLM=1 (test mode)"def llm_status() -> str:return _llm_statusdef llm_error() -> str:return _llm_errordef get_llm():global _llm, _llm_status, _llm_errorif _llm is None:try:from llama_cpp import Llamamp = Path(MODEL_PATH)if not mp.exists():raise FileNotFoundError(f"Model file not found at '{mp}'. "f"Set MODEL_PATH or check the download.")print(f"Loading LLM from {mp} ({mp.stat().st_size / 1e9:.2f} GB)...")_llm = Llama(model_path=str(mp),n_ctx=int(os.getenv("LLAMA_CTX", "2048")),n_threads=int(os.getenv("LLAMA_THREADS", "4")),verbose=False,)_llm_status = "loaded"_llm_error = ""print("LLM loaded successfully.")except Exception as e:_llm_error = f"{type(e).__name__}: {e}"print(f"Warning: could not load LLM: {_llm_error}. Using mock mode.")_llm = "mock"_llm_status = "error"return _llm43 unmodified linesdef mock_generate(prompt: str, system: str = "") -> str:"""Deterministic fallback when no model is loaded. Returns cannedtext for known formats; returns "" for unknown so the per-featuredeterministic fallbacks in chat_reply / generate_insight /parse_mentor_response take over (never leak a sentinel)."""p = prompt.lower()s = system.lower()if "agent" in p and "whale" in p:return "agent: whale\naction: buy gov_bonds 0.10\nreason: safety first\nsentiment: cautious"if "agent" in p and "retail" in p:2 unmodified linesreturn "agent: permabull\naction: buy crypto 0.10\nreason: buy the dip\nsentiment: bullish"if "roast" in p or "sharpe_ratio" in p:return "roast: diversify more\nsharpe_ratio: 0.5\nlesson: Sharpe ratio measures risk-adjusted return\nsuggestion: add bonds"if "insight" in p or "commentary" in p or "commentator" in s:return "insight: Markets are reacting to the headline. Watch for follow-through."if "headline" in p:return "headline: RBI holds rates steady\nimpact: cash:0 fd:0 gov_bonds:0 nifty_50:0 nifty_it:0 real_estate:0 crypto:0 gold:0\nduration: 1"# Chat and other unknown prompts: return empty so the caller's# deterministic fallback runs.return ""def parse_agent_response(response: str, persona: str) -> Dict:
24 unmodified lines252627282930317 unmodified lines3940414243444546474824 unmodified linesagents.MODEL_PATH = download_model.download()print(f"Model path set to: {agents.MODEL_PATH}")except Exception as e:print(f"Model download failed: {e}. Endpoints will use deterministic fallbacks.")app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")7 unmodified lines@app.get("/api/health")def health() -> JSONResponse:return JSONResponse({"status": "ok","llm": agents.llm_status(),"model_path": str(agents.MODEL_PATH),})24 unmodified lines252627282930317 unmodified lines39404142434445464748495051525324 unmodified linesagents.MODEL_PATH = download_model.download()print(f"Model path set to: {agents.MODEL_PATH}")except Exception as e:print(f"Model download wrapper failed: {e}. Endpoints will use deterministic fallbacks.")app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")7 unmodified lines@app.get("/api/health")def health() -> JSONResponse:from pathlib import Path as _Pathmp = _Path(str(agents.MODEL_PATH))return JSONResponse({"status": "ok","llm": agents.llm_status(),"llm_error": agents.llm_error(),"model_path": str(agents.MODEL_PATH),"model_exists": mp.exists(),"model_size_gb": round(mp.stat().st_size / 1e9, 2) if mp.exists() else 0,})
123456789102 unmodified lines131415161718192021222324252627282930313233"""Download the fine-tuned GGUF model from Hugging Face."""import osfrom pathlib import Pathfrom dotenv import load_dotenvfrom huggingface_hub import hf_hub_downloadload_dotenv()2 unmodified linesMODEL_DIR = Path(__file__).resolve().parent / "models"def download() -> str:MODEL_DIR.mkdir(exist_ok=True)local_path = MODEL_DIR / MODEL_FILEif local_path.exists():return str(local_path)print(f"Downloading {MODEL_FILE} from {MODEL_REPO}...")path = hf_hub_download(repo_id=MODEL_REPO,filename=MODEL_FILE,local_dir=str(MODEL_DIR),local_dir_use_symlinks=False,token=os.getenv("HF_TOKEN"),)return pathif __name__ == "__main__":12345678910111213142 unmodified lines171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""Download the fine-tuned GGUF model from Hugging Face.Robust download: returns the expected local path even on failure so therest of the app can report a clear "model not found" error instead ofcrashing at startup. Tries with the token first, then anonymously(works for public repos)."""import osfrom pathlib import Pathfrom dotenv import load_dotenvload_dotenv()2 unmodified linesMODEL_DIR = Path(__file__).resolve().parent / "models"def _local_path() -> Path:return MODEL_DIR / MODEL_FILEdef download() -> str:"""Ensure the GGUF model is available locally. Returns the local pathas a string. Never raises — returns the expected path even onfailure so callers can surface a precise error to the user."""MODEL_DIR.mkdir(parents=True, exist_ok=True)local = _local_path()if local.exists() and local.stat().st_size > 100_000_000:size_gb = local.stat().st_size / 1e9print(f"Model already present: {local} ({size_gb:.2f} GB)")return str(local)token = os.getenv("HF_TOKEN")# Try with token first (for private repos), then anonymously (public).for attempt_token, label in [(token, "with token"), (None, "anonymously")]:if attempt_token == "":attempt_token = Nonetry:print(f"Downloading {MODEL_FILE} from {MODEL_REPO} ({label})...")from huggingface_hub import hf_hub_downloadpath = hf_hub_download(repo_id=MODEL_REPO,filename=MODEL_FILE,local_dir=str(MODEL_DIR),local_dir_use_symlinks=False,token=attempt_token,)print(f"Download complete: {path}")return str(path)except Exception as e:print(f"Download attempt failed ({label}): {type(e).__name__}: {e}")if attempt_token is None:break # don't retry anonymous again# Download failed; return the expected path so the app can report# a clear "model not found" error rather than crashing.print(f"Model download failed. Expected at: {local}")return str(local)if __name__ == "__main__":
536 unmodified lines537538539540541542543544545546547548549550551552553554555556557558559560536 unmodified linesif (h.llm === "loaded") {els.llmStatus.textContent = "LLM: LOCAL";els.llmStatus.className = "llm-tag loaded";els.llmBadge.className = "badge live";els.llmBadge.textContent = "LLM";els.chatLlmBadge.className = "badge live";els.chatLlmBadge.textContent = "LLM";} else if (h.llm === "mock") {els.llmStatus.textContent = "LLM: MOCK";els.llmStatus.className = "llm-tag mock";els.llmBadge.className = "badge fallback";els.llmBadge.textContent = "FALLBACK";els.chatLlmBadge.className = "badge fallback";els.chatLlmBadge.textContent = "FALLBACK";} else {els.llmStatus.textContent = "LLM: OFFLINE";els.llmStatus.className = "llm-tag error";els.llmBadge.className = "badge fallback";els.chatLlmBadge.className = "badge fallback";}setStatus("Ready");render();})();})();536 unmodified lines537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575536 unmodified linesif (h.llm === "loaded") {els.llmStatus.textContent = "LLM: LOCAL";els.llmStatus.className = "llm-tag loaded";els.llmStatus.title = `Model: ${h.model_path}`;els.llmBadge.className = "badge live";els.llmBadge.textContent = "LLM";els.chatLlmBadge.className = "badge live";els.chatLlmBadge.textContent = "LLM";setStatus("Ready (local LLM online)");} else if (h.llm === "mock") {els.llmStatus.textContent = "LLM: MOCK";els.llmStatus.className = "llm-tag mock";els.llmStatus.title = h.llm_error || "Mock mode";els.llmBadge.className = "badge fallback";els.llmBadge.textContent = "FALLBACK";els.chatLlmBadge.className = "badge fallback";els.chatLlmBadge.textContent = "FALLBACK";setStatus("Ready (LLM in mock mode — features use deterministic fallbacks)");} else {// error / uninitialized — LLM failed to loadconst reason = (h.llm_error || "model not loaded").slice(0, 80);const modelInfo = h.model_exists? `model found (${h.model_size_gb} GB) but failed to initialize`: `model file missing at ${h.model_path}`;els.llmStatus.textContent = "LLM: OFFLINE";els.llmStatus.className = "llm-tag error";els.llmStatus.title = `${reason} — ${modelInfo}`;els.llmBadge.className = "badge fallback";els.llmBadge.textContent = "FALLBACK";els.chatLlmBadge.className = "badge fallback";els.chatLlmBadge.textContent = "FALLBACK";setStatus(`LLM offline (${reason}). Chat/mentor use deterministic fallbacks. Game still works.`,true);}render();})();})();
2 unmodified lines34567875 unmodified lines8485868788896 unmodified lines969798991001012 unmodified linesimport osimport syssys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))# Force mock LLM for tests75 unmodified linescheck("chat 200", r.status_code == 200)data = r.json()check("chat has reply", "reply" in data and len(data["reply"]) > 0)r = client.post("/api/chat", json={"message": "", "snapshot": {}})check("empty message rejected", r.status_code == 400)6 unmodified linescheck("insight 200", r.status_code == 200)data = r.json()check("insight has text", "insight" in data and len(data["insight"]) > 0)print("\n=== /api/mentor ===")r = client.post("/api/mentor", json={"summary": {2 unmodified lines3456789101112131475 unmodified lines909192939495969798991001016 unmodified lines1081091101111121131141152 unmodified linesimport osimport sys# Force UTF-8 stdout for ₹ symbol on Windowstry:sys.stdout.reconfigure(encoding="utf-8")except Exception:passsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))# Force mock LLM for tests75 unmodified linescheck("chat 200", r.status_code == 200)data = r.json()check("chat has reply", "reply" in data and len(data["reply"]) > 0)# Regression: no raw "error: format only" leaks from the mockcheck("chat never returns 'error: format only'","error: format only" not in data["reply"], f"reply='{data['reply']}'")check("chat reply looks like real commentary (has ₹ or words)",("₹" in data["reply"] or len(data["reply"].split()) >= 4),f"reply='{data['reply']}'")r = client.post("/api/chat", json={"message": "", "snapshot": {}})check("empty message rejected", r.status_code == 400)6 unmodified linescheck("insight 200", r.status_code == 200)data = r.json()check("insight has text", "insight" in data and len(data["insight"]) > 0)check("insight never returns 'error: format only'","error: format only" not in data["insight"], f"insight='{data['insight']}'")print("\n=== /api/mentor ===")r = client.post("/api/mentor", json={"summary": {