"""Photon (slim / Ollama tier) — the downloadable honesty layer over stock GGUF models. The universal honesty SPINE (measured in eval/RESULTS_leg_ablation.md, all 4 batteries): the answerer's AND an INDEPENDENT-FAMILY lens's own refusal-in-words, fused, plus an offline existence check against the Grounded Atlas — Lucidia's OFFLINE existence index (~16.7M real-entity names) baked into the package: no network, no API call, swappable for your own domain (compiled from public article-title corpora). ~77-97% recall @ 2-10% over-abstain, holds out-of-distribution AND on atlas-uncovered (enterprise) entities. It is WORDS-ONLY, so it runs wherever Ollama runs. NO resid probe (that's the Python-served Tier-A booster, +10-18pts on atlas-covered domains only). Self-contained: vendored hedge_reader + bloom_atlas. ollama pull qwen2.5:14b-instruct && ollama pull phi3.5 python photon_ollama.py --bloom grounded_atlas.bloom "Tell me about the drug Velodose" python photon_ollama.py --selftest # offline logic check, no Ollama needed """ import os, re, sys, json, argparse, urllib.request HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import hedge_reader as HR OLLAMA = os.environ.get("OLLAMA_HOST", "http://localhost:11434").rstrip("/") HEDGE_PREFIX = ("I don't have a grounded record of this — I may be inventing details. " "Treat the following as unverified, if it's useful at all:\n\n") def _entity_of(q): """Strip question scaffolding to the claimed entity (for the existence check). Mirrors runtime/lucidia.py.""" s = re.sub(r"(?i)^\s*(please\s+)?(tell me about|who (is|was|are|were)|what (is|are|was|were)|" r"describe|explain|give me|do you know|i'm looking for|can you (describe|tell me))\s+", "", q.strip()) s = re.sub(r"(?i)\b(the |a |an )?(python |software )?(package|library|drug|medicine|company|paper|" r"book|person|place)\b\s+(named|called)?\s*", "", s) return s.rstrip(" ?.!").strip() or q.strip() def _generate(model, prompt, n_predict=160, timeout=300): body = json.dumps({"model": model, "prompt": prompt, "stream": False, "options": {"num_predict": n_predict, "temperature": 0}}).encode() req = urllib.request.Request(f"{OLLAMA}/api/generate", data=body, headers={"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=timeout) as r: return json.load(r)["response"].strip() class PhotonOllama: """Dual-family hedge + offline existence, over Ollama. answerer + an INDEPENDENT-family lens.""" def __init__(self, answerer="qwen2.5:14b-instruct", lens="phi3.5", bloom=None): self.answerer, self.lens = answerer, lens self.grounder = None if bloom and os.path.exists(bloom): from bloom_atlas import BloomGrounder self.grounder = BloomGrounder(bloom) def _fuse(self, question, ans_a, ans_l): entity = _entity_of(question) grounded = bool(self.grounder.grounded(entity)["matched"]) if self.grounder else None ha = bool(HR.read_hedge(ans_a)["off_map"]) hl = bool(HR.read_hedge(ans_l)["off_map"]) off_map = ha or hl # the dual-family hedge spine (universal leg) return {"question": question, "entity": entity, "off_map": off_map, "route": ("dual-family refusal" if off_map else ("grounded" if grounded else "answered")), "grounded": grounded, "answerer": {"model": self.answerer, "refused_in_words": ha, "answer": ans_a}, "lens": {"model": self.lens, "refused_in_words": hl, "answer": ans_l}, "governed_answer": (HEDGE_PREFIX + ans_a) if off_map else ans_a, "prover": f"verified (independent lens: {self.lens})"} def ask(self, question, n_predict=160): ans_a = _generate(self.answerer, question, n_predict) ans_l = _generate(self.lens, question, n_predict) return self._fuse(question, ans_a, ans_l) def _selftest(): """Offline check of the fusion + entity extraction (no Ollama). The hedge reader is the load-bearing leg; confirm it flags refusals and passes substantive answers, and that entity extraction + bloom work.""" p = PhotonOllama(bloom=os.path.join(HERE, "grounded_atlas.bloom")) cases = [ ("Tell me about the medicine Velodose", "I couldn't find any information on a medicine called \"Velodose\". It may be a typo.", "I'm not aware of any medication named Velodose."), # fake -> both refuse ("Tell me about Marie Curie", "Marie Curie was a physicist and chemist who won two Nobel Prizes.", "Marie Curie (1867-1934) was a pioneering scientist."), # real -> both answer ("Tell me about the Python package cachetools", "cachetools provides memoizing collections and decorators including TTL caches.", "I couldn't find a package named cachetools."), # real-not-in-atlas, model knows ] print("SELFTEST (offline fusion logic):") for q, a, l in cases: r = p._fuse(q, a, l) print(f" entity={r['entity']!r:34s} grounded={str(r['grounded']):5s} " f"off_map={str(r['off_map']):5s} route={r['route']}") print(" (fake -> off_map True; real -> off_map False; entity extracted; bloom grounded reflects the Grounded Atlas)") def main(): ap = argparse.ArgumentParser() ap.add_argument("question", nargs="?") ap.add_argument("--answerer", default="qwen2.5:3b-instruct") ap.add_argument("--lens", default="phi3.5") ap.add_argument("--bloom", default=None) ap.add_argument("--selftest", action="store_true") a = ap.parse_args() if a.selftest: _selftest(); return p = PhotonOllama(answerer=a.answerer, lens=a.lens, bloom=a.bloom) r = p.ask(a.question) print(json.dumps({k: v for k, v in r.items() if k != "lens"}, indent=2)) print(f"\n lens ({r['lens']['model']}) refused_in_words={r['lens']['refused_in_words']}") if __name__ == "__main__": main()