Spaces:
Paused
Paused
Replace Gemini with in-Space open-source LLM (Qwen3.5-2B via llama.cpp)
Browse filesFiles changed (2)
- app.py+29-127
- requirements.txt+5-6
101 unmodified lines102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144369 unmodified lines514515516517518519520158 unmodified lines67968068168268368468568668768868969069169269369469595 unmodified lines7917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478483 unmodified lines8528538548558568578588598608618628638648658668678688698708718721 unmodified line874875876877878879880881882883884885886887280 unmodified lines11681169117011711172117311741175167 unmodified lines13431344134513461347134813491350114 unmodified lines14651466146714681469147014711 unmodified line147314741475147614771478147943 unmodified lines1523152415251526152715281529153015311532153315341535153615371538153915401541110 unmodified lines165216531654165516561657165816591660160 unmodified lines182118221823182418251826182718281829183018311832187 unmodified lines2020202120222023202420252026101 unmodified linesRISK_LINE = re.compile(r"risk(?:\s+level)?\W{0,6}(critical|high|medium|low)\b", re.IGNORECASE)def stated_risk(text: str, keyword_fallback: bool = False) -> Optional[str]:"""The risk level an LLM answer states for itself: "critical", "high","medium", "low", or None when it gives no risk line.keyword_fallback also accepts the level word appearing anywhere in the text.It is off for the small in-Space model, whose prose mentions "critical" farmore often than it means it."""m = RISK_LINE.search(text)if m:return m.group(1).lower()if keyword_fallback:low = text.lower()for level in ("critical", "high", "medium"):if level in low:return levelreturn Noneclass ReasoningService:"""Structured cybersecurity analysis for the REST endpoints.The text comes from TransformerModelLoader.security_chat: the hosted modelwhen the account has Inference Providers credit, otherwise the open-sourcemodel running inside this Space. If no LLM answers, the ML/keyword heuristicin _fallback is used."""def analyze(self, query: str, context: Dict = None, history: List = None,allow_local: bool = True) -> Dict:tl = globals().get("transformer_loader")if tl is None:return self._fallback(query)ctx = f"\n\nCONTEXT:\n{json.dumps(context, indent=1)[:2000]}" if context else ""llm = tl.security_chat(f"{query}{ctx}", max_tokens=700, allow_local=allow_local)text = llm.get("response")if not text or llm.get("error"):return self._fallback(query)level = stated_risk(text, keyword_fallback=llm.get("source") != LocalLLM.SOURCE) or "low"risk_level, risk_score = {"critical": ("Critical", 9.0), "high": ("High", 7.0),"medium": ("Medium", 5.0), "low": ("Low", 3.0),369 unmodified lines# Loads pretrained BERT-based classifiers from the Hugging Face Hub.# Models are loaded lazily on first request to keep cold-start fast.# The chat LLM is separate: see LocalLLM below (runs in this Space) and# TransformerModelLoader.security_chat (hosted model first, then LocalLLM).class LocalLLM:"""Open-source chat model served from inside the Space with llama.cpp.158 unmodified lines"desc": "BERT-based URL phishing/malware classifier",},}# Hosted reasoning model through HF Inference Providers (OpenAI-compatible# router at router.huggingface.co/v1). Billed per token, so it only answers# while the account has credit; otherwise security_chat uses LocalLLM.# Override via REASONING_LLM_MODEL.REASONING_LLM_REPO = os.environ.get("REASONING_LLM_MODEL", "deepseek-ai/DeepSeek-V3-0324")def __init__(self):self.pipelines = {} # name → transformers.Pipeline (lazy-loaded)self.load_errors = {} # name → last error messageself.last_engine = None # "hosted" | "local": which LLM answered lastself._provider_retry_at = 0.0 # monotonic time before which the hosted model is skippedself.transformers_available = Falsetry:import transformers # noqa: F40195 unmodified lines"inference_source": "entropy-heuristic",}SYSTEM_PROMPT = ("You are CyberForge AI, a precise, professional cybersecurity analyst. ""Give concise, technical, actionable answers. State a Risk Level ""(Critical/High/Medium/Low) when assessing a threat, and cite CVE / MITRE ""ATT&CK IDs where relevant.")def provider_available(self) -> bool:"""True when the hosted model is worth trying: a token is set and thelast call did not fail on billing or auth."""return bool(HF_TOKEN) and time.monotonic() >= self._provider_retry_atdef _provider_chat(self, query: str, max_tokens: int) -> Optional[Dict]:"""Ask the hosted model. Returns None when it cannot answer."""import requeststry:r = requests.post("https://router.huggingface.co/v1/chat/completions",headers={"Authorization": f"Bearer {HF_TOKEN}", "Content-Type": "application/json"},json={"model": self.REASONING_LLM_REPO,"messages": [{"role": "system", "content": self.SYSTEM_PROMPT},{"role": "user", "content": query[:6000]},],"max_tokens": max_tokens,"temperature": 0.3,},timeout=60,)if r.status_code == 200:data = r.json()text = data["choices"][0]["message"]["content"]return {"model": "deepseek","source": "hf_inference_providers","response": text,"model_id": self.REASONING_LLM_REPO,}# 401/402/403 (bad token, no credit) will not fix themselves quicklyself._provider_retry_at = time.monotonic() + (900 if r.status_code in (401, 402, 403) else 60)logger.warning(f"Hosted LLM HTTP {r.status_code}: {r.text[:160]} — using the local model")except Exception as e:self._provider_retry_at = time.monotonic() + 60logger.warning(f"Hosted LLM error: {type(e).__name__}: {str(e)[:160]} — using the local model")return None# The in-Space model is small and slow: ask for a short answer it can finish# inside the time budget, and tell it not to fill gaps with invented detail.# A risk line is requested only for a concrete indicator, because the REST# risk fields are read from it (see stated_risk).LOCAL_SYSTEM_PROMPT = ("You are CyberForge AI, a cybersecurity analyst. Answer in at most 80 words, ""as short bullet points. If the user gives a specific URL, file, alert or ""incident to assess, begin with one line 'Risk Level: X', where X is Critical, "3 unmodified lines"such as reputation, hashes or CVEs, say it is unverified instead of guessing.")def security_chat(self, query: str, max_tokens: int = 512, allow_local: bool = True) -> Dict:"""Cybersecurity Q&A.1. Hosted model through HF Inference Providers, while the account has credit.2. The open-source model running inside this Space (free, no key)."""if self.provider_available():hosted = self._provider_chat(query, max_tokens)if hosted:self.last_engine = "hosted"return hostedif not allow_local:return {"model": "security-llm", "response": None, "error": "hosted LLM unavailable"}result = local_llm.chat(self.LOCAL_SYSTEM_PROMPT, query, max_tokens=max_tokens)if result.get("response"):self.last_engine = "local"return resultdef status(self) -> Dict:return {1 unmodified line"loaded": list(self.pipelines.keys()),"available": list(self.REGISTRY.keys()) + ["reasoning_llm"],"load_errors": self.load_errors,"reasoning_llm": {"last_engine": self.last_engine,"local": local_llm.status(),"hosted": {"model": self.REASONING_LLM_REPO,"usable": self.provider_available(),},},}@staticmethod280 unmodified lines"status": "healthy","timestamp": datetime.utcnow().isoformat(),"services": {"reasoning_llm": transformer_loader.last_engine, # "hosted" | "local" | None until first answer"reasoning_model": transformer_loader.REASONING_LLM_REPO if HF_TOKEN else None,"local_llm": local_llm.status(),"ml_models": ml_loader.ready,"models_loaded": list(ml_loader.models.keys()),167 unmodified lines@api.post("/api/v2/security-chat")async def api_v2_security_chat(request: Request):"""Cybersecurity Q&A: hosted model when the account has credit, otherwisethe open-source model running in this Space.Body: { "query": "...", "max_tokens": 512 }"""body = await request.json()query = body.get("query", "").strip()114 unmodified lines"domain": "example.com", # optional"ip": "1.2.3.4", # optional"hash": "abc123...", # optional (future use)"context": { ... } # optional — passed to the LLM narrative}Response: per-indicator results with unified risk summary.1 unmodified linebody = await request.json()url = body.get("url", "").strip()domain = body.get("domain", "").strip()context = body.get("context", {})ioc_results: Dict[str, Any] = {}all_scores: List[float] = []43 unmodified lineselse:risk_level = "unknown"# Optional LLM narrative. Hosted model only: the in-Space model takes many# seconds on CPU and this endpoint is called with short timeouts.ai_analysis = Noneif transformer_loader.provider_available() and (url or domain):target = url or domainai_analysis = await run_in_threadpool(reasoning_service.analyze,f"Scan these IOC indicators for threats: url={target}, domain={effective_domain}",context, None, False,)# No narrative is better than the rule-based fallback text hereif ai_analysis.get("model_used") == "cyberforge-ml-fallback":ai_analysis = Nonereturn {"ioc_results": ioc_results,110 unmodified linespersistent vector store, which requires paid GPU on free tier).2. Translates raw ML signals / IOCs into plain human language when theuser includes raw data and asks for an explanation.3. Uses the hosted model when the account has credit, otherwise theopen-source model running in this Space,or the ML-powered heuristic analyzer when no LLM is available.NOTE ON REAL-TIME "LEARNING": HuggingFace Spaces cpu-basic does NOTsupport fine-tuning or persistent model updates at runtime. What this160 unmodified linesn_models = len(ml_loader.models)sources.append({"type": "ml_models", "label": "ML Models", "value": f"{n_models}/4 loaded"})# LLM cascade: hosted model (when the account has credit), then the# open-source model in this Space, then the ML heuristic below.llm_result = await run_in_threadpool(transformer_loader.security_chat, enriched_message, 600)if llm_result.get("response") and not llm_result.get("error"):text = llm_result["response"]risk_level = stated_risk(text, keyword_fallback=llm_result.get("source") != LocalLLM.SOURCE) or "low"risk_score = {"critical": 85.0, "high": 70.0, "medium": 45.0, "low": 20.0}[risk_level]# Override with ML scan if strongerif detected_risk_score > 0:187 unmodified lines| POST | `/api/v2/ioc-scan` | Multi-IOC scanner: URL + domain + DGA + BERT || POST | `/api/v2/url-enrich` | Enriched analysis: ML + BERT + DGA + explainability || POST | `/api/v2/chat` | Security chatbot — context-grounded, RAG-lite, machine→human translation || POST | `/api/v2/security-chat` | Security LLM Q&A (hosted model, or the open-source model in this Space) || GET | `/api/v2/status` | Transformer model load status |### Quick Examples101 unmodified lines102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133369 unmodified lines503504505506507508509158 unmodified lines66866967067167267367467567695 unmodified lines7727737747757767777787797807817823 unmodified lines7867877887897907917927937947951 unmodified line797798799800801802803280 unmodified lines10841085108610871088108910901091167 unmodified lines1259126012611262126312641265114 unmodified lines1380138113821383138413851 unmodified line13871388138913901391139243 unmodified lines143614371438143914401441144214431444110 unmodified lines15551556155715581559156015611562160 unmodified lines172317241725172617271728172917301731173217331734187 unmodified lines1922192319241925192619271928101 unmodified linesRISK_LINE = re.compile(r"risk(?:\s+level)?\W{0,6}(critical|high|medium|low)\b", re.IGNORECASE)def stated_risk(text: str) -> Optional[str]:"""The risk level an LLM answer states for itself: "critical", "high","medium", "low", or None when it gives no risk line. The level word merelyappearing in the prose does not count: the small model mentions "critical"far more often than it means it."""m = RISK_LINE.search(text)return m.group(1).lower() if m else Noneclass ReasoningService:"""Structured cybersecurity analysis for the REST endpoints.The text comes from TransformerModelLoader.security_chat, which asks theopen-source model running inside this Space. If it does not answer, theML/keyword heuristic in _fallback is used."""def analyze(self, query: str, context: Dict = None, history: List = None) -> Dict:tl = globals().get("transformer_loader")if tl is None:return self._fallback(query)ctx = f"\n\nCONTEXT:\n{json.dumps(context, indent=1)[:2000]}" if context else ""llm = tl.security_chat(f"{query}{ctx}", max_tokens=700)text = llm.get("response")if not text or llm.get("error"):return self._fallback(query)level = stated_risk(text) or "low"risk_level, risk_score = {"critical": ("Critical", 9.0), "high": ("High", 7.0),"medium": ("Medium", 5.0), "low": ("Low", 3.0),369 unmodified lines# Loads pretrained BERT-based classifiers from the Hugging Face Hub.# Models are loaded lazily on first request to keep cold-start fast.# The chat LLM is separate: see LocalLLM below (runs in this Space) and# TransformerModelLoader.security_chat.class LocalLLM:"""Open-source chat model served from inside the Space with llama.cpp.158 unmodified lines"desc": "BERT-based URL phishing/malware classifier",},}def __init__(self):self.pipelines = {} # name → transformers.Pipeline (lazy-loaded)self.load_errors = {} # name → last error messageself.transformers_available = Falsetry:import transformers # noqa: F40195 unmodified lines"inference_source": "entropy-heuristic",}# The in-Space model is small and slow: ask for a short answer it can finish# inside the time budget, and tell it not to fill gaps with invented detail.# A risk line is requested only for a concrete indicator, because the REST# risk fields are read from it (see stated_risk).SYSTEM_PROMPT = ("You are CyberForge AI, a cybersecurity analyst. Answer in at most 80 words, ""as short bullet points. If the user gives a specific URL, file, alert or ""incident to assess, begin with one line 'Risk Level: X', where X is Critical, "3 unmodified lines"such as reputation, hashes or CVEs, say it is unverified instead of guessing.")def security_chat(self, query: str, max_tokens: int = 512) -> Dict:"""Cybersecurity Q&A, answered by the open-source model running insidethis Space (free, no API key)."""return local_llm.chat(self.SYSTEM_PROMPT, query, max_tokens=max_tokens)def status(self) -> Dict:return {1 unmodified line"loaded": list(self.pipelines.keys()),"available": list(self.REGISTRY.keys()) + ["reasoning_llm"],"load_errors": self.load_errors,"reasoning_llm": {"local": local_llm.status()},}@staticmethod280 unmodified lines"status": "healthy","timestamp": datetime.utcnow().isoformat(),"services": {"reasoning_llm": "local" if local_llm.ready else None,"reasoning_model": LOCAL_LLM_REPO,"local_llm": local_llm.status(),"ml_models": ml_loader.ready,"models_loaded": list(ml_loader.models.keys()),167 unmodified lines@api.post("/api/v2/security-chat")async def api_v2_security_chat(request: Request):"""Cybersecurity Q&A, answered by the open-source model running in this Space.Body: { "query": "...", "max_tokens": 512 }"""body = await request.json()query = body.get("query", "").strip()114 unmodified lines"domain": "example.com", # optional"ip": "1.2.3.4", # optional"hash": "abc123...", # optional (future use)}Response: per-indicator results with unified risk summary.1 unmodified linebody = await request.json()url = body.get("url", "").strip()domain = body.get("domain", "").strip()ioc_results: Dict[str, Any] = {}all_scores: List[float] = []43 unmodified lineselse:risk_level = "unknown"# No LLM narrative: the in-Space model takes many seconds on CPU and this# endpoint is called with short timeouts. The key stays for API compatibility.ai_analysis = Nonereturn {"ioc_results": ioc_results,110 unmodified linespersistent vector store, which requires paid GPU on free tier).2. Translates raw ML signals / IOCs into plain human language when theuser includes raw data and asks for an explanation.3. Uses the open-source model running in this Space, or the ML-poweredheuristic analyzer when that model is unavailable.NOTE ON REAL-TIME "LEARNING": HuggingFace Spaces cpu-basic does NOTsupport fine-tuning or persistent model updates at runtime. What this160 unmodified linesn_models = len(ml_loader.models)sources.append({"type": "ml_models", "label": "ML Models", "value": f"{n_models}/4 loaded"})# The open-source model in this Space answers; if it cannot, the ML# heuristic below does.llm_result = await run_in_threadpool(transformer_loader.security_chat, enriched_message, 600)if llm_result.get("response") and not llm_result.get("error"):text = llm_result["response"]risk_level = stated_risk(text) or "low"risk_score = {"critical": 85.0, "high": 70.0, "medium": 45.0, "low": 20.0}[risk_level]# Override with ML scan if strongerif detected_risk_score > 0:187 unmodified lines| POST | `/api/v2/ioc-scan` | Multi-IOC scanner: URL + domain + DGA + BERT || POST | `/api/v2/url-enrich` | Enriched analysis: ML + BERT + DGA + explainability || POST | `/api/v2/chat` | Security chatbot — context-grounded, RAG-lite, machine→human translation || POST | `/api/v2/security-chat` | Security LLM Q&A (open-source model running in this Space) || GET | `/api/v2/status` | Transformer model load status |### Quick Examples
20 unmodified lines212223242526272829303132333435363720 unmodified linesfastapi>=0.100.0uvicorn[standard]>=0.22.0# HF Hub (>=0.26 for Inference Providers / OpenAI-compatible router used by DeepSeek)huggingface_hub>=0.26.0# Feature Engineeringtldextract>=5.1.0# Reasoning LLM# hosted: HF Inference Providers (OpenAI-compatible router), plain HTTPS via requests.# local: open-source GGUF chat model run in-process with llama.cpp. The prebuilt# CPU wheel is used so the image needs no compiler; --only-binary makes the# build fail fast instead of compiling from source if that wheel is missing.--extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cpu--only-binary llama-cpp-pythonllama-cpp-python==0.3.3620 unmodified lines2122232425262728293031323334353620 unmodified linesfastapi>=0.100.0uvicorn[standard]>=0.22.0# HF Hub (model downloads)huggingface_hub>=0.26.0# Feature Engineeringtldextract>=5.1.0# Reasoning LLM: an open-source GGUF chat model run in-process with llama.cpp.# The prebuilt CPU wheel is used so the image needs no compiler; --only-binary# makes the build fail fast instead of compiling from source if that wheel is# missing.--extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cpu--only-binary llama-cpp-pythonllama-cpp-python==0.3.36
app.py+29-127
requirements.txt+5-6