Spaces:
Paused
Paused
Update the CyberForge ML service
Browse filesFiles changed (2)
- app.py+133-37
- security_knowledge.py+217-5
37 unmodified lines3839404142434421 unmodified lines6667686970717273747576777812 unmodified lines919293949596979899706 unmodified lines80680780880981081161 unmodified lines87387487587687787839 unmodified lines9189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599601 unmodified line96296396496596696796896997097197297397497597697711 unmodified lines9899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018148 unmodified lines116711681169117011711172117311741175117611771178117911801181118211831184118511861187515 unmodified lines17031704170517061707170817094 unmodified lines171417151716171717181719172037 unmodified lines# FastAPI for REST endpointsfrom fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import HTMLResponse, JSONResponsefrom starlette.concurrency import run_in_threadpoollogging.basicConfig(level=logging.INFO)21 unmodified lines# It replaces Gemini and needs no API key or credit. Any GGUF chat model can be# set here; on the free cpu-basic tier (2 vCPU) stay around 2B parameters or the# answers will not fit inside the callers' timeouts.from security_knowledge import ground_prompt, finish_grounded_answer, reference_grammarfrom file_scan import file_malware, FILE_SCAN_MAX_BYTESLOCAL_LLM_REPO = os.environ.get("LOCAL_LLM_REPO", "unsloth/Qwen3.5-2B-GGUF")LOCAL_LLM_REVISION = os.environ.get("LOCAL_LLM_REVISION") or NoneLOCAL_LLM_FILE = os.environ.get("LOCAL_LLM_FILE", "Qwen3.5-2B-Q4_K_M.gguf")LOCAL_LLM_CTX = int(os.environ.get("LOCAL_LLM_CTX", "4096"))LOCAL_LLM_THREADS = int(os.environ.get("LOCAL_LLM_THREADS", "2"))# The CUDA build of llama.cpp and the CUDA libraries it links (see the Dockerfile).# Used only when the host provides an NVIDIA driver; otherwise the CPU wheel is.12 unmodified linesreturn Trueexcept OSError:return FalseLOCAL_LLM_MAX_TOKENS = int(os.environ.get("LOCAL_LLM_MAX_TOKENS", "320"))LOCAL_LLM_TEMPERATURE = float(os.environ.get("LOCAL_LLM_TEMPERATURE", "0.3"))LOCAL_LLM_MAX_INPUT_CHARS = int(os.environ.get("LOCAL_LLM_MAX_INPUT_CHARS", "2400"))LOCAL_LLM_TIME_BUDGET_S = float(os.environ.get("LOCAL_LLM_TIME_BUDGET_S", "17"))# A caller with a longer timeout of its own may ask for more time, up to this.# Reading the prompt counts: on this CPU a 2,000-character prompt alone takes706 unmodified linesself.gpu_error: Optional[str] = Noneself._chatml = Falseself._prefill = ""self._load_lock = threading.Lock()self._gen_lock = threading.Lock()self._waiting_lock = threading.Lock()61 unmodified lines# empty think block; this is what its template emits for# enable_thinking=False.self._prefill = "<think>\n\n</think>\n\n" if "<think>" in template else ""self.llm = llmlogger.info(f"✅ Local LLM loaded: {LOCAL_LLM_REPO}/{LOCAL_LLM_FILE}")except Exception as e:39 unmodified linesself._interactive_waiting -= 1return time.monotonic() - asked if got else Nonedef chat(self, system: str, user: str, max_tokens: int = 512, time_budget_s: Optional[float] = None, interactive: bool = False) -> Dict:base = {"model": "local-llm", "source": self.SOURCE, "model_id": LOCAL_LLM_REPO}budget = LOCAL_LLM_TIME_BUDGET_S if time_budget_s is None else max(5.0, min(float(time_budget_s), LOCAL_LLM_MAX_TIME_BUDGET_S))if self.llm is None:if self._load_lock.locked():return {**base, "response": None, "error": "local LLM is still loading"}self.load()if self.llm is None:return {**base, "response": None, "error": self.error or "local LLM not loaded"}waited = self._acquire(interactive, budget)if waited is None:return {**base, "response": None, "error": "local LLM is busy with another request"}# The time spent waiting comes out of the budget: the caller is waiting too.budget = max(5.0, budget - waited)started = time.monotonic()stream = Nonetry:max_tokens = max(16, min(int(max_tokens), LOCAL_LLM_MAX_TOKENS))# The chat markers are structural: drop them from untrusted textsystem = system.replace("<|im_start|>", "").replace("<|im_end|>", "")user = user.replace("<|im_start|>", "").replace("<|im_end|>", "")if len(user) > LOCAL_LLM_MAX_INPUT_CHARS:# Keep both ends: context sits at the start, the question at the endhalf = LOCAL_LLM_MAX_INPUT_CHARS // 2user = f"{user[:half]}\n[...]\n{user[-half:]}"system, references = ground_prompt(system, user)grammar_text = reference_grammar(references, analyst=not interactive)decoding = {}if grammar_text:from llama_cpp import LlamaGrammardecoding["grammar"] = LlamaGrammar.from_string(grammar_text, verbose=False)if self._chatml:prompt = (f"<|im_start|>system\n{system}<|im_end|>\n"f"<|im_start|>user\n{user}<|im_end|>\n"f"<|im_start|>assistant\n{self._prefill}")stream = self.llm.create_completion(prompt, max_tokens=max_tokens, temperature=LOCAL_LLM_TEMPERATURE, top_p=0.8, top_k=20,presence_penalty=1.5, stop=["<|im_end|>", "<|endoftext|>"], stream=True,1 unmodified line)read = lambda c: c["choices"][0].get("text") or ""else:stream = self.llm.create_chat_completion(messages=[{"role": "system", "content": system}, {"role": "user", "content": user}],max_tokens=max_tokens, temperature=LOCAL_LLM_TEMPERATURE, top_p=0.8, stream=True,**decoding,)read = lambda c: c["choices"][0].get("delta", {}).get("content") or ""pieces: List[str] = []truncated = Falsefor chunk in stream:pieces.append(read(chunk))if chunk["choices"][0].get("finish_reason") == "length":truncated = Trueif time.monotonic() - started > budget:11 unmodified linesif ends and ends[-1] > len(text) * 0.4:text = text[:ends[-1]].strip()if not text:return {**base, "response": None, "error": "local LLM returned no text"}text, grounding = finish_grounded_answer(text, references, analyst=not interactive)if grammar_text:grounding["generation_constraint"] = "reviewed_passages"return {**base,"response": text,"tokens": len(pieces),"elapsed_ms": round((time.monotonic() - started) * 1000),"truncated": truncated,"grounding": grounding,"references": grounding["references"],"model_generated": grounding["mode"] != "verified_reference",**({"model": "verified-reference", "source": "verified_reference","model_used": "cyberforge-ml-fallback"} if grounding["mode"] == "verified_reference" else {}),}except Exception as e:return {**base, "response": None, "error": f"{type(e).__name__}: {str(e)[:200]}"}finally:if stream is not None and hasattr(stream, "close"):stream.close()self._gen_lock.release()local_llm = LocalLLM()148 unmodified lines# conversation first. The analyst prompt above stays for background# explanations of scans, alerts and reports.ASSISTANT_PROMPT = ("You are the CyberForge assistant, a friendly, helpful chat assistant built into ""the CyberForge security app. Talk naturally, like a normal chat assistant: reply ""to greetings and small talk briefly and warmly, and offer to help. Answer security ""questions clearly and concisely, in plain sentences, using a short list only for ""steps. When the message includes the user's CyberForge memory, use it only if it ""helps answer. Never claim to have scanned, detected or checked anything that is ""not in the message; if something has not been checked, say so.")def security_chat(self, query: str, max_tokens: int = 512, time_budget_s: Optional[float] = None, interactive: bool = False) -> Dict:"""Cybersecurity Q&A, answered by the open-source model running insidethis Space (free, no API key). `interactive` when a person is waiting:then it is a conversation (ASSISTANT_PROMPT), not an analyst's report."""system = self.ASSISTANT_PROMPT if interactive else self.SYSTEM_PROMPTreturn local_llm.chat(system, query, max_tokens=max_tokens, time_budget_s=time_budget_s, interactive=interactive)def status(self) -> Dict:return {515 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 json_object(request)query = text_field(body, "query")if not query:4 unmodified lines# "interactive" only when a person is waiting on the answer (the assistant);# anything else is background work and gives way to it.interactive = text_field(body, "priority") == "interactive"result = await run_in_threadpool(transformer_loader.security_chat, query, max_tokens, budget, interactive)if result.get("error"):# No made-up analysis in its place: the rule-based summary keyword-matches# the whole prompt (context included) and is not an answer to a question.37 unmodified lines3839404142434421 unmodified lines6667686970717273747576777812 unmodified lines919293949596979899100101102103104105706 unmodified lines81281381481581681781861 unmodified lines88088188288388488588639 unmodified lines9269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231 unmodified line102510261027102810291030103110321033103410351036103710381039104010411042104311 unmodified lines105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087148 unmodified lines1236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266515 unmodified lines178217831784178517861787178817894 unmodified lines1794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181637 unmodified lines# FastAPI for REST endpointsfrom fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import HTMLResponse, JSONResponse, StreamingResponsefrom starlette.concurrency import run_in_threadpoollogging.basicConfig(level=logging.INFO)21 unmodified lines# It replaces Gemini and needs no API key or credit. Any GGUF chat model can be# set here; on the free cpu-basic tier (2 vCPU) stay around 2B parameters or the# answers will not fit inside the callers' timeouts.from security_knowledge import ground_prompt, finish_grounded_answer, reference_grammar, question_textfrom file_scan import file_malware, FILE_SCAN_MAX_BYTESLOCAL_LLM_REPO = os.environ.get("LOCAL_LLM_REPO", "unsloth/Qwen3.5-2B-GGUF")LOCAL_LLM_REVISION = os.environ.get("LOCAL_LLM_REVISION") or NoneLOCAL_LLM_FILE = os.environ.get("LOCAL_LLM_FILE", "Qwen3.5-2B-Q4_K_M.gguf")LOCAL_LLM_CTX = int(os.environ.get("LOCAL_LLM_CTX", "8192"))LOCAL_LLM_THREADS = int(os.environ.get("LOCAL_LLM_THREADS", "2"))# The CUDA build of llama.cpp and the CUDA libraries it links (see the Dockerfile).# Used only when the host provides an NVIDIA driver; otherwise the CPU wheel is.12 unmodified linesreturn Trueexcept OSError:return FalseLOCAL_LLM_MAX_TOKENS = int(os.environ.get("LOCAL_LLM_MAX_TOKENS", "900"))# The assistant may reason before it answers (Qwen3.5 thinking mode): at most this# many tokens of reasoning, then the answer. About 4 s on the T4.LOCAL_LLM_THINK_TOKENS = int(os.environ.get("LOCAL_LLM_THINK_TOKENS", "448"))# Earlier turns of the conversation, sent as real chat turns.LOCAL_LLM_HISTORY_TURNS = int(os.environ.get("LOCAL_LLM_HISTORY_TURNS", "6"))LOCAL_LLM_HISTORY_CHARS = int(os.environ.get("LOCAL_LLM_HISTORY_CHARS", "1200"))LOCAL_LLM_TEMPERATURE = float(os.environ.get("LOCAL_LLM_TEMPERATURE", "0.3"))LOCAL_LLM_MAX_INPUT_CHARS = int(os.environ.get("LOCAL_LLM_MAX_INPUT_CHARS", "6000"))LOCAL_LLM_TIME_BUDGET_S = float(os.environ.get("LOCAL_LLM_TIME_BUDGET_S", "17"))# A caller with a longer timeout of its own may ask for more time, up to this.# Reading the prompt counts: on this CPU a 2,000-character prompt alone takes706 unmodified linesself.gpu_error: Optional[str] = Noneself._chatml = Falseself._prefill = ""self._can_think = Falseself._load_lock = threading.Lock()self._gen_lock = threading.Lock()self._waiting_lock = threading.Lock()61 unmodified lines# empty think block; this is what its template emits for# enable_thinking=False.self._prefill = "<think>\n\n</think>\n\n" if "<think>" in template else ""self._can_think = self._chatml and "<think>" in templateself.llm = llmlogger.info(f"✅ Local LLM loaded: {LOCAL_LLM_REPO}/{LOCAL_LLM_FILE}")except Exception as e:39 unmodified linesself._interactive_waiting -= 1return time.monotonic() - asked if got else None# Greetings, thanks and "what can you do" are answered at once, without reasoning.SMALL_TALK = re.compile(r"^\W*(?:hi|hello|hey|yo|hiya|good (?:morning|afternoon|evening)|thanks?|thank you|ok(?:ay)?|cool|great|nice|bye|goodbye|who are you|what can you do)\b.{0,40}$", re.I | re.S)@classmethoddef wants_thinking(cls, question: str, think: str) -> bool:"""think: "on", "off" or "auto" (reason about real questions, not small talk)."""if think == "on":return Trueif think != "auto":return Falseq = (question or "").strip()return len(q.split()) >= 5 and not cls.SMALL_TALK.match(q)def chat(self, system: str, user: str, max_tokens: int = 512, time_budget_s: Optional[float] = None, interactive: bool = False,history: Optional[List[Dict]] = None, think: str = "off") -> Dict:result: Dict = {}for kind, value in self.generate(system, user, max_tokens, time_budget_s, interactive, history, think):if kind == "final":result = valuereturn resultdef generate(self, system: str, user: str, max_tokens: int = 512, time_budget_s: Optional[float] = None, interactive: bool = False,history: Optional[List[Dict]] = None, think: str = "off"):"""Yield ("thinking", text) and ("answer", text) as the model writes, then ("final", result)."""base = {"model": "local-llm", "source": self.SOURCE, "model_id": LOCAL_LLM_REPO}budget = LOCAL_LLM_TIME_BUDGET_S if time_budget_s is None else max(5.0, min(float(time_budget_s), LOCAL_LLM_MAX_TIME_BUDGET_S))if self.llm is None:if self._load_lock.locked():yield ("final", {**base, "response": None, "error": "local LLM is still loading"})returnself.load()if self.llm is None:yield ("final", {**base, "response": None, "error": self.error or "local LLM not loaded"})returnwaited = self._acquire(interactive, budget)if waited is None:yield ("final", {**base, "response": None, "error": "local LLM is busy with another request"})return# The time spent waiting comes out of the budget: the caller is waiting too.budget = max(5.0, budget - waited)started = time.monotonic()stream = Nonethinking = ""thinking_ms = Nonetry:max_tokens = max(16, min(int(max_tokens), LOCAL_LLM_MAX_TOKENS))# The chat markers are structural: drop them from untrusted textclean = lambda t: str(t or "").replace("<|im_start|>", "").replace("<|im_end|>", "").replace("<think>", "").replace("</think>", "")system = clean(system)user = clean(user)if len(user) > LOCAL_LLM_MAX_INPUT_CHARS:# Keep both ends: context sits at the start, the question at the endhalf = LOCAL_LLM_MAX_INPUT_CHARS // 2user = f"{user[:half]}\n[...]\n{user[-half:]}"turns = []for item in (history or [])[-LOCAL_LLM_HISTORY_TURNS:]:text_ = clean(item.get("content"))[:LOCAL_LLM_HISTORY_CHARS].strip()if text_:turns.append(("assistant" if item.get("role") == "assistant" else "user", text_))system, references = ground_prompt(system, user, interactive=interactive)# The assistant answers in its own words and is checked afterwards; analyst# explanations stay bounded to the reviewed passages.grammar_text = None if interactive else reference_grammar(references, analyst=True)decoding = {}if grammar_text:from llama_cpp import LlamaGrammardecoding["grammar"] = LlamaGrammar.from_string(grammar_text, verbose=False)reasoning = self._can_think and self.wants_thinking(question_text(user), think)if self._chatml:convo = "".join(f"<|im_start|>{role}\n{content}<|im_end|>\n" for role, content in turns)head = f"<|im_start|>system\n{system}<|im_end|>\n{convo}<|im_start|>user\n{user}<|im_end|>\n<|im_start|>assistant\n"if reasoning:# 1. reasoning, bounded in tokens and in time (at most half the budget)t0 = time.monotonic()stream = self.llm.create_completion(head + "<think>\n", max_tokens=LOCAL_LLM_THINK_TOKENS, temperature=0.6, top_p=0.95, top_k=20,stop=["</think>", "<|im_end|>", "<|endoftext|>"], stream=True)for chunk in stream:piece = chunk["choices"][0].get("text") or ""if piece:thinking += pieceyield ("thinking", piece)if time.monotonic() - started > budget * 0.5 or (not interactive and self._interactive_waiting):breakif hasattr(stream, "close"):stream.close()stream = Nonethinking_ms = round((time.monotonic() - t0) * 1000)prompt = head + "<think>\n" + thinking.strip() + "\n</think>\n\n"else:prompt = head + self._prefill# 2. the answer (the prompt prefix is cached by llama.cpp, so it is not read again)stream = self.llm.create_completion(prompt, max_tokens=max_tokens, temperature=LOCAL_LLM_TEMPERATURE, top_p=0.8, top_k=20,presence_penalty=1.5, stop=["<|im_end|>", "<|endoftext|>"], stream=True,1 unmodified line)read = lambda c: c["choices"][0].get("text") or ""else:messages = [{"role": "system", "content": system}] + [{"role": r, "content": c} for r, c in turns] + [{"role": "user", "content": user}]stream = self.llm.create_chat_completion(messages=messages, max_tokens=max_tokens, temperature=LOCAL_LLM_TEMPERATURE, top_p=0.8, stream=True,**decoding,)read = lambda c: c["choices"][0].get("delta", {}).get("content") or ""pieces: List[str] = []truncated = Falsefor chunk in stream:piece = read(chunk)pieces.append(piece)if piece:yield ("answer", piece)if chunk["choices"][0].get("finish_reason") == "length":truncated = Trueif time.monotonic() - started > budget:11 unmodified linesif ends and ends[-1] > len(text) * 0.4:text = text[:ends[-1]].strip()if not text:yield ("final", {**base, "response": None, "error": "local LLM returned no text"})returntext, grounding = finish_grounded_answer(text, references, analyst=not interactive)if grammar_text:grounding["generation_constraint"] = "reviewed_passages"yield ("final", {**base,"response": text,"tokens": len(pieces),"elapsed_ms": round((time.monotonic() - started) * 1000),"truncated": truncated,"thinking": thinking.strip()[:4000] or None,"thinking_ms": thinking_ms,"history_turns": len(turns),"grounding": grounding,"references": grounding["references"],"model_generated": grounding["mode"] != "verified_reference",**({"model": "verified-reference", "source": "verified_reference","model_used": "cyberforge-ml-fallback"} if grounding["mode"] == "verified_reference" else {}),})except Exception as e:yield ("final", {**base, "response": None, "error": f"{type(e).__name__}: {str(e)[:200]}"})finally:if stream is not None and hasattr(stream, "close"):stream.close()self._gen_lock.release()local_llm = LocalLLM()148 unmodified lines# conversation first. The analyst prompt above stays for background# explanations of scans, alerts and reports.ASSISTANT_PROMPT = ("You are the CyberForge assistant, a friendly security expert built into the CyberForge app. ""Write like a helpful expert in a chat. Start with a direct answer in one or two sentences, then give ""the details that matter: short paragraphs, bullet points for lists, numbered steps for procedures, and ""**bold** for the key terms. Keep answers focused, usually 80 to 220 words, and longer only when the user ""asks for depth. Reply to greetings, thanks and small talk in one or two warm sentences and offer help. ""Be accurate: if you are unsure, say so; never invent CVE numbers, statistics, versions, dates, product ""names, scan results or detections. When the message includes the user's CyberForge memory or scans, base ""the answer on them and quote hosts, verdicts and scores exactly; never claim to have checked anything that ""is not in the message. Use the earlier turns of the conversation to understand follow-up questions. When ""it helps, end with one clear next step.")def security_chat(self, query: str, max_tokens: int = 512, time_budget_s: Optional[float] = None, interactive: bool = False,history: Optional[List[Dict]] = None, think: str = "off") -> Dict:"""Cybersecurity Q&A, answered by the open-source model running insidethis Space (free, no API key). `interactive` when a person is waiting:then it is a conversation (ASSISTANT_PROMPT), not an analyst's report."""system = self.ASSISTANT_PROMPT if interactive else self.SYSTEM_PROMPTreturn local_llm.chat(system, query, max_tokens=max_tokens, time_budget_s=time_budget_s, interactive=interactive,history=history if interactive else None, think=think if interactive else "off")def security_chat_stream(self, query: str, max_tokens: int, time_budget_s: Optional[float], history: Optional[List[Dict]], think: str):"""The assistant's answer as it is written (interactive only)."""return local_llm.generate(self.ASSISTANT_PROMPT, query, max_tokens=max_tokens, time_budget_s=time_budget_s,interactive=True, history=history, think=think)def status(self) -> Dict:return {515 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, "priority": "interactive", "history": [{role, content}],"think": "auto"|"on"|"off", "stream": true }"""body = await json_object(request)query = text_field(body, "query")if not query:4 unmodified lines# "interactive" only when a person is waiting on the answer (the assistant);# anything else is background work and gives way to it.interactive = text_field(body, "priority") == "interactive"# The conversation so far ([{role, content}]) and whether to reason first# ("auto" reasons about real questions, not small talk). Assistant only.history = dicts_in(list_field(body, "history"))[-LOCAL_LLM_HISTORY_TURNS:]think = text_field(body, "think") if text_field(body, "think") in ("on", "off", "auto") else ("auto" if interactive else "off")if interactive and body.get("stream") is True:# Server-sent events: {"type":"thinking"|"answer","delta":...} as the model# writes, then {"type":"final","result":{...}} with the checked answer.def events():for kind, value in transformer_loader.security_chat_stream(query, max_tokens, budget, history, think):if kind == "final":answered = bool(value.get("response")) and not value.get("error")value = {**value, "answered": answered, "result_kind": "reasoning_text", **({} if answered else {"response": None})}yield "data: " + json.dumps({"type": "final", "result": value}) + "\n\n"else:yield "data: " + json.dumps({"type": kind, "delta": value}) + "\n\n"return StreamingResponse(events(), media_type="text/event-stream", headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})result = await run_in_threadpool(transformer_loader.security_chat, query, max_tokens, budget, interactive, history, think)if result.get("error"):# No made-up analysis in its place: the rule-based summary keyword-matches# the whole prompt (context included) and is not an answer to a question.
6 unmodified lines789101112131 unmodified line15161718192021222369 unmodified lines93949596979812 unmodified lines11111211311411511611711811912012155 unmodified lines1771781791801811821831841851861871886 unmodified linesimport jsonimport itertoolsREVISION = "2026-10-23.3"POLICY = ("Detector policy: the supervised phishing, malware-URL and web-attack classifiers ""flag rescaled scores >= 0.50. The anomaly model measures unusualness, not proof ""of maliciousness. Name it separately; never say all detectors are below threshold "1 unmodified line"is implied by these scores.")def doc(id, title, aliases, facts, source, required, forbidden=()):return dict(id=id, title=title, aliases=aliases, facts=facts, url=source,required=required, forbidden=forbidden, reviewed="2026-10-23")REFERENCES = [69 unmodified lines"Security analysis can observe a sample's behaviour inside such an environment. ""Isolation reduces exposure but does not prove a sample is safe; quiet behaviour in one analysis is not a guarantee.","https://csrc.nist.gov/glossary/term/sandbox", [r"(?:isolat|constrain|restrict)"]),]12 unmodified linesreturn [r for r in REFERENCES if any(re.search(a, query, re.I) for a in r["aliases"])][:2]def ground_prompt(system, user):refs = retrieve(user)if any(marker in user for marker in ("ml_scores", "ML phishing_detection", "[ML PRE-SCAN RESULTS]")):system += "\n\n" + POLICYif refs:system += ("\n\nVERIFIED REFERENCE CONTEXT (editorially reviewed; use for factual claims). ""Answer using only complete sentences copied from the facts below. ""Select the relevant sentences; you may omit others and format them as bullets. "55 unmodified linesreturn "root ::= " + " | ".join(json.dumps(c, ensure_ascii=False) for c in choices) if choices else Nonedef finish_grounded_answer(text, refs, analyst=False):"""Expose an explicit reference answer when the model misses core facts.This narrow check does not claim to verify every generated assertion.Raw model answers are evaluated separately from the served response."""fallback = reference_fallback_needed(text, refs)if fallback:if analyst:6 unmodified lines789101112131 unmodified line151617181920212223242526272869 unmodified lines989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727812 unmodified lines29129229329429529629729829930030130230330430530630730855 unmodified lines3643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994006 unmodified linesimport jsonimport itertoolsREVISION = "2026-11-17.1"POLICY = ("Detector policy: the supervised phishing, malware-URL and web-attack classifiers ""flag rescaled scores >= 0.50. The anomaly model measures unusualness, not proof ""of maliciousness. Name it separately; never say all detectors are below threshold "1 unmodified line"is implied by these scores.")def doc(id, title, aliases, facts, source, required, forbidden=(), reviewed="2026-10-23"):return dict(id=id, title=title, aliases=aliases, facts=facts, url=source,required=required, forbidden=forbidden, reviewed=reviewed)def doc2(*args, **kwargs):"""A reference added in the November 2026 review (sources checked to resolve on 2026-11-17)."""return doc(*args, reviewed="2026-11-17", **kwargs)REFERENCES = [69 unmodified lines"Security analysis can observe a sample's behaviour inside such an environment. ""Isolation reduces exposure but does not prove a sample is safe; quiet behaviour in one analysis is not a guarantee.","https://csrc.nist.gov/glossary/term/sandbox", [r"(?:isolat|constrain|restrict)"]),# ── Added 2026-11-17. More specific topics first: retrieval takes the first two matches. ──doc2("clickfix", "MITRE ATT&CK: Malicious copy and paste (T1204.004)",[r"click.?fix", r"fake captcha", r"(?:paste|copied).*(?:run (?:box|dialog)|powershell|terminal|command)", r"win(?:dows)?\s*(?:key\s*)?\+\s*r\b", r"verify (?:you are|i am) (?:a )?human.*(?:paste|command|run)"],"ClickFix pages, often disguised as a CAPTCHA or a fix for an error, trick people into copying a command and pasting it into the Windows Run dialog, PowerShell or a terminal. ""Running it usually downloads malware such as an information stealer. A real CAPTCHA or website never asks you to run commands on your computer. ""If you already ran one, disconnect from the network, run a full anti-malware scan and change your passwords from a different, clean device.","https://attack.mitre.org/techniques/T1204/004/", [r"(?:paste|copy|copied)", r"(?:command|run|powershell|terminal)"],[r"(?:it is|it's|is) (?:safe|fine|ok(?:ay)?) to (?:run|paste)"]),doc2("infostealer", "MITRE ATT&CK: Credentials from web browsers (T1555.003)",[r"info.?stealer", r"stealer (?:malware|log)", r"\b(?:redline|lumma|raccoon|vidar)\b", r"(?:saved|stored) passwords?.*(?:stolen|steal|browser)"],"Information stealers are malware that collect saved browser passwords, cookies, autofill data and cryptocurrency wallets and send them to the attacker. ""Stolen session cookies can let an attacker into an account without the password or the MFA prompt. ""After an infection, clean or reinstall the device first, then change passwords and sign out all sessions from a clean device. ""Passkeys and phishing-resistant MFA make stolen passwords far less useful.","https://attack.mitre.org/techniques/T1555/003/", [r"(?:password|cookie|credential)", r"(?:steal|stolen|collect)"]),doc2("keylogger", "MITRE ATT&CK: Keylogging (T1056.001)", [r"key.?logg", r"keystroke (?:log|record|captur)"],"A keylogger records keystrokes to capture passwords and other typed information. ""It can be malicious software or a small hardware device placed between the keyboard and the computer. ""Keep the system updated, use reputable anti-malware, and use MFA or passkeys so a captured password alone is not enough.","https://attack.mitre.org/techniques/T1056/001/", [r"(?:keystroke|typed|type|keys)"]),doc2("aitm", "MITRE ATT&CK: Adversary-in-the-middle (T1557)", [r"man.in.the.middle", r"\bmitm\b", r"adversary.in.the.middle", r"\baitm\b"],"In an adversary-in-the-middle (man-in-the-middle) attack, the attacker sits between two parties to read or alter their traffic. ""Phishing kits use it to relay a real sign-in page and capture the session cookie, which can bypass ordinary MFA codes. ""HTTPS with valid certificates protects traffic in transit, and phishing-resistant MFA such as FIDO2 security keys or passkeys resists relayed sign-ins.","https://attack.mitre.org/techniques/T1557/", [r"(?:between|intercept|relay|alter|read)"]),doc2("credential-stuffing", "OWASP: Credential stuffing prevention", [r"credential.stuffing", r"(?:leaked|breached|reused) passwords?.*(?:attack|login|sign.in)"],"Credential stuffing uses username and password pairs leaked from one site to try to sign in to other sites, relying on password reuse. ""A unique password for every account and multi-factor authentication are the main defences for users. ""Services add MFA, breached-password checks, rate limiting and bot detection.","https://cheatsheetseries.owasp.org/cheatsheets/Credential_Stuffing_Prevention_Cheat_Sheet.html", [r"(?:reuse|leak|breach)"]),doc2("brute-force", "MITRE ATT&CK: Brute force (T1110)", [r"brute.?forc", r"password spray", r"dictionary attack", r"(?:many|repeated) failed (?:log.?ins?|sign.?ins?|logins?)"],"Brute-force attacks guess passwords repeatedly; password spraying tries a few common passwords against many accounts to avoid lockouts. ""Long, unique passwords and MFA defeat most guessing. ""Rate limiting, lockout or delay policies and alerts on many failed sign-ins slow attacks down and help detect them.","https://attack.mitre.org/techniques/T1110/", [r"(?:guess|tries|trying|attempt)"]),doc2("dga", "MITRE ATT&CK: Domain generation algorithms (T1568.002)", [r"\bdga\b", r"domain generation algorithm"],"A domain generation algorithm (DGA) lets malware compute many pseudo-random domain names to find its command-and-control server, so blocking one domain does not cut it off. ""Such domains often look random, though some DGAs combine dictionary words. ""Detection looks at how random a domain is, many failed DNS lookups (NXDOMAIN) and newly registered domains.","https://attack.mitre.org/techniques/T1568/002/", [r"domain", r"(?:command|control|\bc2\b|malware)"]),doc2("privilege-escalation", "MITRE ATT&CK: Privilege escalation (TA0004)", [r"privilege escalation", r"escalat\w* privileges?", r"\bpriv.?esc\b"],"Privilege escalation is how an attacker gains higher permissions, such as administrator or SYSTEM, than they first obtained. ""Common routes are unpatched vulnerabilities, misconfigurations and stolen administrator credentials. ""Least privilege, prompt patching and monitoring administrative changes reduce the risk.","https://attack.mitre.org/tactics/TA0004/", [r"(?:permission|privilege|admin)"]),doc2("lateral-movement", "MITRE ATT&CK: Lateral movement (TA0008)", [r"lateral movement", r"move\w* laterally"],"Lateral movement is how an attacker moves from the first compromised system to others in the network, often with stolen credentials and remote-access tools. ""Network segmentation, least privilege, MFA for remote access and monitoring of unusual internal sign-ins limit it.","https://attack.mitre.org/tactics/TA0008/", [r"(?:other|network|systems|machines)"]),doc2("sextortion", "NCSC: Sextortion scams", [r"sextortion", r"(?:hacked|recorded).*webcam", r"webcam.*(?:recorded|hacked|video)", r"(?:email|message).*(?:pay|send).*bitcoin.*(?:video|recorded)"],"Sextortion scam emails claim to have hacked your webcam or recorded you and demand payment, often in cryptocurrency, sometimes quoting an old password from a data breach to seem credible. ""In most cases the claim is false. Do not reply or pay; change any password the email mentions and report the email.","https://www.ncsc.gov.uk/guidance/sextortion-scams-how-to-protect-yourself", [r"(?:do not|don't|never|not) (?:reply|pay|respond)"],[r"(?:you should|best to|just) pay"]),doc2("bec", "IC3: Business email compromise", [r"business email compromise", r"\bbec\b", r"(?:ceo|invoice|payroll|wire.transfer) (?:fraud|scam)", r"change (?:of |in |to )?(?:the )?(?:bank|payment|account) details"],"Business email compromise (BEC) is fraud in which criminals impersonate an executive, supplier or colleague by email to get money or data, for example a request to change bank details or pay an urgent invoice. ""It often uses a lookalike domain or a hacked mailbox, so the email can look genuine. ""Verify every payment or bank-detail change by calling a known phone number, not one in the email, and require two people to approve transfers.","https://www.ic3.gov/PSA/2023/PSA230609", [r"(?:impersonat|pretend|pos(?:e|ing) as|fake)", r"(?:verif|confirm|call)"]),doc2("clicked-phishing", "NCSC: What to do if you clicked a suspicious link", [r"(?:clicked|opened|tapped|followed) (?:on )?(?:a |the |an )?(?:phishing |suspicious |bad |malicious |dodgy |scam )?(?:link|attachment|email)", r"entered my (?:password|details|card|bank)", r"gave (?:them |away )?(?:my )?(?:password|details|otp|code|pin)"],"If you clicked a suspicious link but entered nothing, close the page and run an anti-malware scan; the risk is usually low. ""If you entered a password, change it straight away on the real site and anywhere else you reused it, and turn on multi-factor authentication. ""If you gave card or bank details, contact your bank immediately; if you opened an attachment or ran a file, disconnect the device and scan it.","https://www.ncsc.gov.uk/guidance/suspicious-email-actions", [r"(?:change|password|bank|scan)"]),doc2("hacked-account", "NCSC: Recovering a hacked account", [r"(?:account|email|facebook|instagram|whatsapp|gmail|outlook|tiktok).*(?:hacked|compromised|taken over|broken into)", r"hacked (?:account|email)", r"someone (?:logged|signed) (?:in|into) my", r"locked out of my (?:account|email)"],"If an account is hacked, use the service's official recovery page to regain access, then change the password to a unique one and turn on multi-factor authentication. ""Sign out of all other sessions and check the recovery email, phone number, forwarding rules and connected apps for changes the attacker made. ""Warn your contacts if messages were sent in your name, and change the same password anywhere else you reused it.","https://www.ncsc.gov.uk/guidance/recovering-a-hacked-account", [r"password", r"(?:recover|multi.factor|\bmfa\b|two.factor|2fa|sign(?:ed)? out|session)"]),doc2("infected-device", "NCSC: Mitigating malware and ransomware", [r"(?:computer|pc|laptop|phone|device|mac).*(?:infected|has (?:a )?virus|has malware)", r"remove (?:a |the )?(?:virus|malware|trojan)", r"signs of (?:malware|infection|a virus|being hacked)", r"(?:get rid of|clean) (?:a |the )?(?:virus|malware)"],"Signs of infection include sudden slowness, pop-ups, programs or browser extensions you did not install, security tools being switched off, and accounts sending messages you did not write. ""Disconnect from the network, run a full scan with up-to-date anti-malware, and remove unknown programs and extensions. ""If problems remain or the device holds sensitive data, back up your files and reinstall the operating system, then change passwords from a clean device.","https://www.ncsc.gov.uk/guidance/mitigating-malware-and-ransomware-attacks", [r"(?:scan|disconnect|reinstall)"]),doc2("ransomware", "CISA: #StopRansomware guide", [r"ransomware", r"ransom note", r"files? (?:are |got |were |have been )?encrypted.*(?:pay|ransom|bitcoin)"],"Ransomware encrypts files or systems and demands payment, and many groups also steal data and threaten to publish it. ""Keep offline, encrypted backups and test restoring them, patch internet-facing systems, and require MFA for remote access. ""If you are hit, disconnect affected devices from the network and report the incident; CISA and the FBI do not encourage paying, and payment does not guarantee recovery.","https://www.cisa.gov/stopransomware/ransomware-guide", [r"encrypt", r"(?:backup|disconnect|isolat)"],[r"(?:you should|always|best to) pay(?: the ransom)?"]),doc2("backups", "CISA: Data backup options", [r"\bbackups?\b", r"back(?:ing)? up (?:my |your |our )?(?:files|data|computer|phone)", r"3.2.1 rule"],"Keep at least three copies of important data, on two different types of storage, with one copy offsite or offline (the 3-2-1 rule). ""An offline or immutable copy protects backups from ransomware that encrypts connected drives. ""Test restoring regularly; a backup that has never been restored is unproven.","https://www.cisa.gov/sites/default/files/publications/data_backup_options.pdf", [r"(?:offline|offsite|off-site|copies|copy)"]),doc2("mfa", "CISA: Require multifactor authentication", [r"\bmfa\b", r"multi.?factor", r"two.?factor", r"\b2fa\b", r"authenticator app", r"security key", r"one.time (?:code|password)"],"Multi-factor authentication (MFA) asks for a second proof, such as an authenticator app, a security key or a passkey, in addition to a password, so a stolen password alone is not enough. ""Phishing-resistant methods (FIDO2 security keys and passkeys) are strongest; SMS codes are better than nothing but can be phished or intercepted through SIM swapping. ""Turn MFA on first for email, banking and password-manager accounts, and never share a code with someone who contacts you.","https://www.cisa.gov/secure-our-world/require-multifactor-authentication", [r"(?:second|additional|factor|another)", r"password"]),doc2("updates", "CISA: Update software", [r"\bpatch(?:es|ing)?\b", r"software updates?", r"automatic updates?", r"(?:why|should|need to).*\bupdate\b.*(?:software|windows|phone|apps?|browser|computer)"],"Software updates fix security vulnerabilities that attackers actively exploit, so install them promptly and turn on automatic updates where possible. ""Prioritise operating systems, browsers and internet-facing software. ""Get updates only from the vendor or the device's built-in updater; pop-ups saying you must install an update are a common malware trick.","https://www.cisa.gov/secure-our-world/update-software", [r"(?:vulnerab|fix|security)"]),doc2("zero-day", "NIST glossary: Zero-day attack", [r"zero.?day", r"\b0.?day\b"],"A zero-day is a vulnerability that the vendor does not yet know about or has not yet fixed when attackers first exploit it. ""Because no patch exists yet, defence in depth matters: least privilege, exploit protection, segmentation and monitoring for unusual behaviour. ""Apply the vendor's fix or mitigation as soon as it is published.","https://csrc.nist.gov/glossary/term/zero_day_attack", [r"(?:unknown|not (?:yet )?(?:know|fix|patch)|no (?:fix|patch)|before)"]),doc2("cve-cvss", "CVE program and FIRST: CVSS", [r"\bcvss\b", r"what (?:is|are) (?:a )?cves?\b", r"\bcve (?:id|number|identifier)s?", r"vulnerability (?:score|severity)"],"A CVE identifier (CVE-year-number) gives a publicly disclosed vulnerability a unique name so everyone refers to the same issue. ""CVSS rates a vulnerability's technical severity from 0.0 to 10.0, with Critical from 9.0 to 10.0. ""Severity is not the same as risk: whether it is being exploited and how exposed your systems are also matter.","https://www.cve.org/About/Overview", [r"(?:identifier|unique|name|id)", r"(?:10|severity|score)"]),doc2("owasp-top10", "OWASP Top 10", [r"owasp top.?(?:10|ten)"],"The OWASP Top 10 is a widely used awareness list of the most critical web application security risks, updated every few years from community data. ""Recent editions are led by Broken Access Control; other entries include injection, cryptographic failures and security misconfiguration. ""It is a starting point for secure development, not a complete checklist.","https://owasp.org/www-project-top-ten/", [r"(?:web|application)", r"(?:access control|risk)"]),doc2("mitre-attack", "MITRE ATT&CK", [r"mitre att&?ck", r"\batt&ck\b", r"mitre (?:framework|matrix)"],"MITRE ATT&CK is a public knowledge base of adversary tactics (the attacker's goals, such as initial access or persistence) and techniques (how they achieve them), built from real-world observations. ""Defenders use it to describe attacks consistently, map detections and find coverage gaps. Technique IDs look like T1566 (Phishing).","https://attack.mitre.org/resources/", [r"tactic", r"technique"]),doc2("ioc", "NIST glossary: Indicator", [r"\biocs?\b", r"indicators? of compromise"],"Indicators of compromise (IOCs) are observable signs of a likely intrusion, such as malicious file hashes, IP addresses, domains, URLs or unexpected system changes. ""They help hunt for and block known threats, but attackers change them easily, so behaviour-based detection is needed too. ""An IOC match is a lead to investigate, not proof on its own.","https://csrc.nist.gov/glossary/term/indicator", [r"(?:hash|\bip\b|domain|sign|observ)"]),doc2("siem-edr", "NIST glossary: SIEM", [r"\bsiem\b", r"\bedr\b", r"\bxdr\b", r"endpoint detection"],"A SIEM (security information and event management) system collects and correlates logs from many sources to detect and investigate incidents. ""EDR (endpoint detection and response) records activity on computers and servers and can isolate a device or stop malicious processes. ""XDR extends that correlation across endpoints, email, identity and network data.","https://csrc.nist.gov/glossary/term/security_information_and_event_management", [r"(?:log|event|endpoint)"]),doc2("firewall", "NIST glossary: Firewall", [r"firewall"],"A firewall controls network traffic into a device or between networks according to rules, allowing or blocking connections. ""Keep the operating system's firewall on, especially on public networks, and allow only the services you need. ""A firewall does not stop malware you run yourself or phishing that you click.","https://csrc.nist.gov/glossary/term/firewall", [r"(?:traffic|connection)", r"(?:rule|allow|block)"]),doc2("ddos", "CISA: Understanding and responding to DDoS attacks", [r"\bddos\b", r"denial.of.service"],"A distributed denial-of-service (DDoS) attack floods a service with traffic from many machines, often a botnet, to make it unavailable. ""Defences include upstream DDoS protection from an internet or cloud provider, a content delivery network, rate limiting and a tested response plan. ""DDoS mainly affects availability, not data confidentiality, but it can be used as a distraction from other attacks.","https://www.cisa.gov/resources-tools/resources/understanding-and-responding-distributed-denial-service-attacks", [r"(?:traffic|flood|overwhelm)", r"(?:unavailable|availability|offline|down)"]),doc2("botnet", "NIST glossary: Botnet", [r"botnet", r"zombie (?:computer|pc|device)"],"A botnet is a network of compromised computers or devices controlled remotely by an attacker and used for DDoS attacks, spam, password attacks or spreading malware. ""Internet-connected devices with default passwords are common recruits. ""Change default passwords, keep firmware updated and look into unexplained outbound traffic.","https://csrc.nist.gov/glossary/term/botnet", [r"(?:compromised|infected|hijacked)", r"control"]),doc2("malware", "NIST glossary: Malware", [r"\btrojans?\b", r"\bworms?\b", r"\bspyware\b", r"\badware\b", r"computer virus", r"what (?:is|are) (?:a )?(?:malware|viruses)", r"types of malware"],"Malware is software designed to harm or misuse a device or its data. ""A virus attaches to files and spreads when they run; a worm spreads by itself across networks; a trojan poses as legitimate software; spyware secretly collects information; ransomware encrypts data for payment. ""Keep software updated, install apps only from trusted sources and use reputable anti-malware.","https://csrc.nist.gov/glossary/term/malware", [r"(?:software|program)"]),doc2("insider-threat", "CISA: Insider threat mitigation", [r"insider threat", r"(?:employee|staff|insider|contractor)s? (?:who )?(?:steal|leak|sabotag)"],"An insider threat is the risk that someone with authorised access, such as an employee or contractor, harms the organisation, deliberately or by mistake. ""Least privilege, removing access promptly when roles change, monitoring access to sensitive data and a culture where concerns can be reported reduce the risk.","https://www.cisa.gov/topics/physical-security/insider-threat-mitigation", [r"(?:access|authori)"]),doc2("incident-response", "NIST SP 800-61 Rev. 3: Incident response", [r"incident response", r"respond(?:ing)? to (?:a |an )?(?:cyber )?(?:incident|breach|attack)", r"(?:after|during) (?:a |an )?(?:breach|cyber.?attack|security incident)"],"Incident response covers preparing, detecting and analysing, containing, eradicating and recovering, and learning lessons afterwards. ""NIST SP 800-61 Revision 3 (2025) presents these activities through the CSF 2.0 functions rather than a separate lifecycle. ""Early priorities are to contain the damage (isolate affected systems, disable compromised accounts), preserve evidence such as logs, and communicate through a pre-agreed channel.","https://csrc.nist.gov/pubs/sp/800/61/r3/final", [r"(?:contain|isolat)", r"(?:evidence|log|recover|eradicat)"]),doc2("email-authentication", "DMARC.org: Overview", [r"\bspf\b", r"\bdkim\b", r"\bdmarc\b", r"email (?:spoofing|authentication)", r"spoofed (?:email|sender)"],"SPF lists the servers allowed to send email for a domain, DKIM adds a cryptographic signature to messages, and DMARC tells receivers what to do when a message fails those checks and sends reports to the domain owner. ""Together they make it harder to send email that pretends to come from your domain. ""They do not stop lookalike domains or mail sent from a genuinely compromised account.","https://dmarc.org/overview/", [r"(?:sender|servers|signature|spoof)"]),doc2("https-padlock", "IC3: Secure websites used in phishing", [r"padlock", r"https.*(?:safe|secure|legit|trust)", r"(?:safe|secure|legit|trust).*https", r"\bssl\b.*(?:safe|legit|trust)"],"HTTPS and the padlock mean the connection to the site is encrypted; they do not mean the site is legitimate or safe. ""Phishing sites routinely use HTTPS with free certificates. ""Check the actual domain name, and be wary of unexpected requests for passwords or payment.","https://www.ic3.gov/PSA/2019/PSA190610", [r"encrypt", r"(?:not|n't|no guarantee|phishing)"],[r"(?:padlock|https) (?:means|shows|proves) (?:the|a|that the) (?:site|website) is (?:safe|legitimate|trustworthy)"]),doc2("social-engineering", "CISA: Avoiding social engineering and phishing", [r"social engineering", r"\bsmishing\b", r"\bvishing\b", r"pretexting", r"(?:scam|fake|suspicious) (?:text|sms|phone call|call)", r"text message.*(?:link|scam|suspicious)"],"Social engineering manipulates people into revealing information or taking unsafe actions, usually with urgency, fear or a reward. ""Smishing uses text messages and vishing uses phone calls; both may impersonate banks, delivery companies or support staff. ""Do not use the contact details or links in the message: reach the organisation through its official website or app, and never share one-time codes or passwords.","https://www.cisa.gov/news-events/news/avoiding-social-engineering-and-phishing-attacks", [r"(?:urgen|pressure|impersonat|manipulat|trick|pretend)"]),doc2("phishing", "CISA: Recognize and report phishing", [r"phishing", r"\bphish", r"suspicious (?:email|link|message)", r"fake (?:email|login|website|site)"],"Phishing messages pretend to come from a trusted organisation or person to get you to click a link, open an attachment or hand over passwords, codes or payment details. ""Warning signs include urgency or threats, unexpected requests, mismatched or misspelled sender addresses, and links whose real destination differs from their text. ""Do not use the message's links: go to the organisation's website or app yourself, and report the message as phishing.","https://www.cisa.gov/secure-our-world/recognize-and-report-phishing", [r"(?:link|attachment|password|credential|details)", r"(?:pretend|imperson|trusted|fake|appear)"]),]12 unmodified linesreturn [r for r in REFERENCES if any(re.search(a, query, re.I) for a in r["aliases"])][:2]def ground_prompt(system, user, interactive=False):refs = retrieve(user)if any(marker in user for marker in ("ml_scores", "ML phishing_detection", "[ML PRE-SCAN RESULTS]")):system += "\n\n" + POLICYif refs and interactive:# A conversation: the model explains in its own words; the answer is checked# against these facts afterwards (finish_grounded_answer).system += ("\n\nREVIEWED FACTS FOR THIS QUESTION (from cited sources). Your answer must agree with them ""and include their key points. Explain in your own words and add only widely established practice. ""Do not contradict them, and do not invent numbers, versions, dates or product names.\n")system += "\n".join(f"- {r['facts']}" for r in refs)elif refs:system += ("\n\nVERIFIED REFERENCE CONTEXT (editorially reviewed; use for factual claims). ""Answer using only complete sentences copied from the facts below. ""Select the relevant sentences; you may omit others and format them as bullets. "55 unmodified linesreturn "root ::= " + " | ".join(json.dumps(c, ensure_ascii=False) for c in choices) if choices else Nonedef reference_problem(text, refs):"""For a conversational answer: ("forbidden", refs) when it states something areference rules out, ("missing", refs) when it leaves out a reference's corefacts, otherwise (None, [])."""bad = [r for r in refs if any(re.search(p, text, re.I) for p in r["forbidden"])]if bad:return "forbidden", badmissing = [r for r in refs if not all(re.search(p, text, re.I) for p in r["required"])]return ("missing", missing) if missing else (None, [])def finish_grounded_answer(text, refs, analyst=False):"""Expose an explicit reference answer when the model misses core facts.This narrow check does not claim to verify every generated assertion.Raw model answers are evaluated separately from the served response.The assistant (analyst=False) answers in its own words. An answer that statessomething a reference rules out is replaced by the reviewed facts; one thatleaves out core facts keeps its text and gets the reviewed facts added."""cited = [{k: r[k] for k in ("id", "title", "url", "reviewed")} for r in refs]if not analyst:problem, which = reference_problem(text, refs)if problem == "forbidden":return "\n\n".join(r["facts"] for r in refs), {"mode": "verified_reference", "revision": REVISION, "references": cited}if problem == "missing":added = " ".join(" ".join(re.split(r"(?<=[.!?])\s+", r["facts"])[:2]) for r in which)return (text.rstrip() + "\n\n**From the reviewed sources:** " + added,{"mode": "retrieved_context_supplemented", "revision": REVISION, "references": cited})return text, {"mode": "retrieved_context" if refs else "model_context", "revision": REVISION, "references": cited}fallback = reference_fallback_needed(text, refs)if fallback:if analyst:
app.py+133-37
security_knowledge.py+217-5