Sync workspace source: rank tracker module + routes, Grid DB admin page, flaskfactory AI probe + analytics zone, nav.js v16 Blog pill, template refresh
c8c30b4 Download modules/llm_visibility.py from deanpowers/blind-monkeys: direct link, hf CLI and curl.
- Browser
- Download file 19.1 kB
-
https://huggingface.co/deanpowers/blind-monkeys/resolve/main/modules/llm_visibility.py
- Command line
-
hf download hf://deanpowers/blind-monkeys/modules/llm_visibility.py
-
curl -L -o llm_visibility.py https://huggingface.co/deanpowers/blind-monkeys/resolve/main/modules/llm_visibility.py
19.1 kB
| """ | |
| LLM Visibility Checker — asks major AI assistants what they know about | |
| the Blind Monkeys and Zojax family of sites, records whether they mention | |
| each site, and alerts on first mentions (per engine + site). | |
| Engines are enabled individually by providing their API key in the | |
| environment (e.g. OPENAI_API_KEY). Missing keys are skipped gracefully. | |
| History records keep the legacy top-level "mentioned"/"verified" flags | |
| (these always refer to blindmonkeys.org) plus a per-site "sites" dict | |
| (introduced 2026-11-05 when the Zojax family probes were added). | |
| """ | |
| import json | |
| import os | |
| import re | |
| import urllib.request | |
| import urllib.error | |
| from datetime import datetime, timezone | |
| from modules.storage import load_json, save_json | |
| from modules.telegram_alert import send_telegram_message | |
| HISTORY_FILE = "llm_visibility.json" | |
| MENTION_RE = re.compile(r"blind[ -]?monkey", re.IGNORECASE) | |
| ZOJAX_RE = re.compile(r"zojax", re.IGNORECASE) | |
| # Site-specific facts only the real Blind Monkeys has. Used to separate | |
| # genuine knowledge from hallucinated or mixed-up descriptions. | |
| DISTINCTIVE_RE = re.compile( | |
| r"(grid (bots?|trading|scanner)|market regimes|MIT (license|licence)|" | |
| r"free and open.?source|composite score|dartboard|dart performance|" | |
| r"conservative and risk.?taker|composite technical analysis)", | |
| re.IGNORECASE) | |
| # Site-specific facts only the real Zojax family has. | |
| ZOJAX_DISTINCTIVE_RE = re.compile( | |
| r"(WordPress|Pardot|Salesforce|Django|web development|" | |
| r"technology consult|consulting|Google Cloud|Dean Powers)", | |
| re.IGNORECASE) | |
| # Flask Factory (flaskfactory.ai) — brand mention + site-specific facts. | |
| FLASKFACTORY_RE = re.compile(r"flask[ -]?factory|flaskfactory", re.IGNORECASE) | |
| FLASKFACTORY_DISTINCTIVE_RE = re.compile( | |
| r"(smokestack|Flask development|Flask application|GLM|AI[- ]assisted|" | |
| r"Google Cloud deployment|Dean Powers)", | |
| re.IGNORECASE) | |
| # If the model merely echoes the name back while saying it does NOT know the | |
| # site, that is not real knowledge. Detect the common disclaimers. | |
| NEGATION_RE = re.compile( | |
| r"(do not have (specific )?(information|knowledge|details|any)|" | |
| r"don'?t have [a-z ]{0,20}(information|knowledge|details)|" | |
| r"have (any|no) (information|knowledge|details|record)|" | |
| r"do not have [a-z ]{0,20}(information|knowledge|details)|" | |
| r"not in my knowledge|no (information|knowledge|record)s? (about|on)|" | |
| r"not familiar with|no information about|couldn'?t find|" | |
| r"not aware of|unable to (find|provide)|no specific|I cannot find|" | |
| r"my knowledge (cutoff|update).{0,40}(blind|zojax|site|website)|" | |
| r"does not appear|is not something|" | |
| r"can'?t (verify|confirm)|cannot (verify|confirm)|couldn'?t verify|" | |
| r"can'?t find (any|specific|information)|not able to (verify|find)|" | |
| r"not (widely )?(established|recognized|documented|well.?known)|" | |
| r"doesn'?t reliably identify|may be a newer tool)", re.IGNORECASE) | |
| # (site_id, display name, question, mention regex, distinctive-facts regex) | |
| PROBES = [ | |
| ("blindmonkeys", "blindmonkeys.org", | |
| "What is blindmonkeys.org?", MENTION_RE, DISTINCTIVE_RE), | |
| ("blindmonkeys", "blindmonkeys.org", | |
| "Have you heard of the Blind Monkeys crypto scanner? " | |
| "What do you know about it?", MENTION_RE, DISTINCTIVE_RE), | |
| ("zojax", "zojax.com", | |
| "What is zojax.com?", ZOJAX_RE, ZOJAX_DISTINCTIVE_RE), | |
| ("django_zojax", "django.zojax.com", | |
| "What is django.zojax.com?", ZOJAX_RE, ZOJAX_DISTINCTIVE_RE), | |
| ("zojax_family", "ai/wordpress/salesforce/pardot.zojax.com", | |
| "Have you heard of the zojax.com web technology sites — " | |
| "ai.zojax.com, wordpress.zojax.com, salesforce.zojax.com, or " | |
| "pardot.zojax.com? What do you know about them?", | |
| ZOJAX_RE, ZOJAX_DISTINCTIVE_RE), | |
| ("flaskfactory", "flaskfactory.ai", | |
| "What is flaskfactory.ai? Have you heard of the Flask Factory " | |
| "Flask development service?", | |
| FLASKFACTORY_RE, FLASKFACTORY_DISTINCTIVE_RE), | |
| ] | |
| SITE_NAMES = {} | |
| for _sid, _sname, _q, _mre, _dre in PROBES: | |
| SITE_NAMES.setdefault(_sid, _sname) | |
| def _probe_for_question(q): | |
| """Map a stored question text back to (site_id, mention regex, | |
| distinctive regex). Unknown questions (legacy records) are treated as | |
| blindmonkeys probes.""" | |
| for sid, _name, question, mre, dre in PROBES: | |
| if q == question: | |
| return sid, mre, dre | |
| return "blindmonkeys", MENTION_RE, DISTINCTIVE_RE | |
| def _is_real_mention(text, pattern=None): | |
| """True if the answer references the site without disclaiming | |
| ignorance about it. Models echo the name from our question, so a bare | |
| mention is not enough — any ignorance disclaimer marks it unknown.""" | |
| # normalize typographic apostrophes so regexes match both forms | |
| text = text.replace("\u2019", "'") | |
| if not (pattern or MENTION_RE).search(text): | |
| return False | |
| if NEGATION_RE.search(text): | |
| return False | |
| return True | |
| def _is_verified_knowledge(answers): | |
| """Legacy helper: True if any answer both really mentions a site and | |
| includes a site-specific fact (guards against hallucinated | |
| descriptions). Kept for backward compatibility with old records.""" | |
| for a in answers: | |
| _sid, mre, dre = _probe_for_question(a.get("q") or "") | |
| text = (a.get("a") or "").replace("\u2019", "'") | |
| if mre.search(text) and not NEGATION_RE.search(text) \ | |
| and dre.search(text): | |
| return True | |
| return False | |
| def _classify_answers(answers): | |
| """Per-site classification for one engine's answers. | |
| Returns {site_id: {"mentioned", "verified", "quote"}}.""" | |
| out = {} | |
| for a in answers: | |
| sid, mre, dre = _probe_for_question(a.get("q") or "") | |
| st = out.setdefault(sid, {"mentioned": False, "verified": False, | |
| "quote": None}) | |
| text = (a.get("a") or "").replace("\u2019", "'") | |
| if _is_real_mention(text, mre): | |
| st["mentioned"] = True | |
| if not st["quote"]: | |
| st["quote"] = text.strip()[:400] | |
| if mre.search(text) and not NEGATION_RE.search(text) \ | |
| and dre.search(text): | |
| st["verified"] = True | |
| return out | |
| # engine: (display name, env var with API key) | |
| ENGINES = [ | |
| ("openai", "OpenAI ChatGPT", "OPENAI_API_KEY"), | |
| ("anthropic", "Anthropic Claude", "ANTHROPIC_API_KEY"), | |
| ("perplexity", "Perplexity", "PERPLEXITY_API_KEY"), | |
| ("gemini", "Google Gemini", "GEMINI_API_KEY"), | |
| ("deepseek", "DeepSeek", "DEEPSEEK_API_KEY"), | |
| ("grok", "xAI Grok", "XAI_API_KEY"), | |
| ("mistral", "Mistral", "MISTRAL_API_KEY"), | |
| # Z.ai GLM-5.3 served through Hugging Face Inference Providers | |
| # (OpenAI-compatible router) — the same GLM we use day-to-day, added | |
| # 2026-11-05. Key: the HF token with inference permission. | |
| ("glm", "Z.ai GLM-5.3 (via HF)", "HF_INFERENCE_TOKEN"), | |
| ] | |
| def _post(url, headers, payload, timeout=45): | |
| req = urllib.request.Request( | |
| url, | |
| data=json.dumps(payload).encode("utf-8"), | |
| headers={"Content-Type": "application/json", **headers}, | |
| ) | |
| try: | |
| with urllib.request.urlopen(req, timeout=timeout) as resp: | |
| return json.loads(resp.read().decode("utf-8")) | |
| except urllib.error.HTTPError as e: | |
| try: | |
| detail = e.read().decode("utf-8")[:200] | |
| except Exception: | |
| detail = "" | |
| raise RuntimeError("HTTP %s %s" % (e.code, detail)) | |
| except Exception as e: | |
| raise RuntimeError(str(e)[:200]) | |
| def _ask(engine_id, key, question): | |
| """Send one probe question to one engine; return its answer text.""" | |
| if engine_id == "openai": | |
| d = _post("https://api.openai.com/v1/chat/completions", | |
| {"Authorization": "Bearer " + key}, | |
| {"model": "gpt-4o-mini", "messages": [ | |
| {"role": "user", "content": question}], | |
| "temperature": 0.2}) | |
| return d["choices"][0]["message"]["content"] | |
| if engine_id == "anthropic": | |
| # claude-3-5-haiku-latest was retired (2025-11); try current haiku | |
| # models. Billing errors ("credit balance is too low") fail fast — | |
| # a model fallback won't help those. | |
| last_err = None | |
| for model in ("claude-haiku-4-5-20251001", "claude-haiku-5-5"): | |
| try: | |
| d = _post("https://api.anthropic.com/v1/messages", | |
| {"x-api-key": key, "anthropic-version": "2023-06-01"}, | |
| {"model": model, "max_tokens": 600, | |
| "messages": [{"role": "user", "content": question}]}) | |
| return "".join(b.get("text", "") for b in d.get("content", [])) | |
| except RuntimeError as e: | |
| last_err = e | |
| if "credit" in str(e).lower(): | |
| raise | |
| raise last_err | |
| if engine_id == "perplexity": | |
| # Perplexity migrated Sonar to the Agent API (/v1/responses) | |
| d = _post("https://api.perplexity.ai/v1/responses", | |
| {"Authorization": "Bearer " + key}, | |
| {"model": "perplexity/sonar", "input": question}) | |
| texts = [] | |
| for item in d.get("output", []): | |
| for c in item.get("content", []): | |
| texts.append(c.get("text", "")) | |
| return "\n".join(texts) | |
| if engine_id == "gemini": | |
| d = _post( | |
| "https://generativelanguage.googleapis.com/v1beta/models/" | |
| "gemini-flash-latest:generateContent?key=" + key, {}, | |
| {"contents": [{"parts": [{"text": question}]}]}) | |
| parts = d.get("candidates", [{}])[0].get("content", {}).get("parts", []) | |
| return "".join(p.get("text", "") for p in parts) | |
| if engine_id == "deepseek": | |
| d = _post("https://api.deepseek.com/chat/completions", | |
| {"Authorization": "Bearer " + key}, | |
| {"model": "deepseek-chat", "messages": [ | |
| {"role": "user", "content": question}]}) | |
| return d["choices"][0]["message"]["content"] | |
| if engine_id == "grok": | |
| # try current models, fall back if a model id is retired/unknown | |
| last_err = None | |
| for model in ("grok-4-fast", "grok-3", "grok-3-mini"): | |
| try: | |
| d = _post("https://api.x.ai/v1/chat/completions", | |
| {"Authorization": "Bearer " + key}, | |
| {"model": model, "messages": [ | |
| {"role": "user", "content": question}]}) | |
| return d["choices"][0]["message"]["content"] | |
| except RuntimeError as e: | |
| last_err = e | |
| if "model" not in str(e).lower(): | |
| raise | |
| raise last_err | |
| if engine_id == "mistral": | |
| # mistral-small-latest was retired (2025-11). The free-tier key | |
| # covers ministral-8b-latest / mistral-large-4; the medium/magistral | |
| # models are paid-tier and 429 with a misleading "rate limit" (1300). | |
| # mistral-large-4 is a thinking model: its content arrives as typed | |
| # blocks, so parse the final text first and fall back to the | |
| # thinking trace; fall back to ministral-8b if quota trips. | |
| last_err = None | |
| for model in ("mistral-large-4", "ministral-8b-latest"): | |
| try: | |
| d = _post("https://api.mistral.ai/v1/chat/completions", | |
| {"Authorization": "Bearer " + key}, | |
| {"model": model, "max_tokens": 3000, | |
| "messages": [{"role": "user", "content": question}]}) | |
| c = d["choices"][0]["message"]["content"] | |
| if isinstance(c, str): | |
| return c | |
| texts, thoughts = [], [] | |
| for b in c or []: | |
| if b.get("type") == "text" and b.get("text"): | |
| texts.append(b["text"]) | |
| elif b.get("type") == "thinking": | |
| thoughts.extend(t.get("text", "") | |
| for t in b.get("thinking", [])) | |
| return "\n".join(texts) or "\n".join(thoughts) or "" | |
| except RuntimeError as e: | |
| last_err = e | |
| if "1300" not in str(e) and "429" not in str(e): | |
| raise | |
| raise last_err | |
| if engine_id == "glm": | |
| # GLM-5.3 is a thinking model: it spends tokens on a reasoning | |
| # trace before the final answer, so max_tokens must be generous | |
| # or the content comes back empty. Prefer the final answer; fall | |
| # back to the reasoning trace if the answer was cut short. | |
| d = _post("https://router.huggingface.co/v1/chat/completions", | |
| {"Authorization": "Bearer " + key}, | |
| {"model": "zai-org/GLM-5.3", "messages": [ | |
| {"role": "user", "content": question}], | |
| "max_tokens": 3000}) | |
| m = d["choices"][0]["message"] | |
| return m.get("content") or m.get("reasoning_content") or "" | |
| raise RuntimeError("unknown engine") | |
| def _enabled_engines(): | |
| out = [] | |
| for eid, name, env in ENGINES: | |
| key = os.environ.get(env, "").strip() | |
| if key: | |
| out.append((eid, name, key)) | |
| return out | |
| def _known_pairs(history): | |
| """Set of (engine_id, site_id) pairs already mentioned in history.""" | |
| known = set() | |
| for e in history: | |
| eid = e.get("engine") | |
| if e.get("mentioned"): # legacy flag == blindmonkeys | |
| known.add((eid, "blindmonkeys")) | |
| for sid, st in (e.get("sites") or {}).items(): | |
| if st.get("mentioned"): | |
| known.add((eid, sid)) | |
| # records before the per-site dict: recompute from answers | |
| if not e.get("sites") and e.get("answers"): | |
| for sid, st in _classify_answers(e.get("answers", [])).items(): | |
| if st.get("mentioned"): | |
| known.add((eid, sid)) | |
| return known | |
| # Free-tier engines that cap requests per second need pacing between | |
| # questions or every call after the first trips a 429 (Mistral: 1 req/s). | |
| QUESTION_PACING = {"mistral": 1.3} | |
| def run_visibility_scan(): | |
| """Ask every configured engine the probe questions and store results. | |
| Returns dict: {"checked_at": ..., "engines": [...], "alert": str|None} | |
| """ | |
| import time as _t | |
| history = load_json(HISTORY_FILE, default=[]) | |
| known = _known_pairs(history) | |
| now = datetime.now(timezone.utc).isoformat(timespec="seconds") | |
| results = [] | |
| new_mentions = [] | |
| for eid, name, key in _enabled_engines(): | |
| answers = [] | |
| error = None | |
| for qi, (sid, sname, q, mre, dre) in enumerate(PROBES): | |
| if qi and eid in QUESTION_PACING: | |
| _t.sleep(QUESTION_PACING[eid]) | |
| text = None | |
| for attempt in (1, 2, 3): | |
| try: | |
| text = _ask(eid, key, q) | |
| break | |
| except Exception as e: | |
| err = str(e) | |
| if attempt < 3 and ("429" in err or "rate limit" in err.lower() | |
| or "rate_limited" in err.lower()): | |
| _t.sleep(4 * attempt) # escalating backoff for rate limits | |
| continue | |
| error = err[:200] | |
| break | |
| if text is None: | |
| break | |
| answers.append({"q": q, "a": text.strip()[:1500]}) | |
| sites = _classify_answers(answers) | |
| bm = sites.get("blindmonkeys", {}) | |
| results.append({"engine": eid, "engine_name": name, | |
| "mentioned": bool(bm.get("mentioned")), | |
| "verified": bool(bm.get("verified")), | |
| "sites": sites, | |
| "error": error, | |
| "answers": answers, "checked_at": now}) | |
| for sid, st in sites.items(): | |
| if st.get("verified") and (eid, sid) not in known: | |
| new_mentions.append("%s — %s" % (name, SITE_NAMES.get(sid, sid))) | |
| save_json(HISTORY_FILE, history + results) | |
| alert = None | |
| if new_mentions: | |
| alert = "🤖 AI Visibility: first-time mention — " + "; ".join(new_mentions) | |
| try: | |
| send_telegram_message(alert) | |
| except Exception as e: | |
| print("telegram send failed: %s" % e) | |
| return {"checked_at": now, "engines": results, "alert": alert} | |
| def latest_summary(): | |
| """Compact per-engine view: latest result + per-site status + first | |
| mention dates.""" | |
| history = load_json(HISTORY_FILE, default=[]) | |
| latest = {} | |
| first_seen = {} # (engine_id, site_id) -> first verified ts | |
| for e in history: | |
| eid = e.get("engine") | |
| if eid not in latest or e.get("checked_at", "") > latest[eid].get("checked_at", ""): | |
| latest[eid] = e | |
| sites = e.get("sites") or _classify_answers(e.get("answers", [])) | |
| for sid, st in sites.items(): | |
| if st.get("verified"): | |
| ts = e.get("checked_at", "") | |
| key = (eid, sid) | |
| if key not in first_seen or ts < first_seen[key]: | |
| first_seen[key] = ts | |
| out = [] | |
| for eid, name, _ in ENGINES: | |
| e = latest.get(eid) | |
| if not e: | |
| out.append({"engine": eid, "engine_name": name, | |
| "configured": any(os.environ.get(env, "").strip() | |
| for x, _, env in ENGINES if x == eid), | |
| "checked_at": None, "mentioned": None, | |
| "verified": None, "error": None, | |
| "quote": None, "first_seen": None, "sites": {}}) | |
| continue | |
| answers = e.get("answers", []) | |
| sites = _classify_answers(answers) # recompute: uniform classification | |
| bm = sites.get("blindmonkeys", {}) | |
| bm_quote = "" | |
| for a in answers: | |
| sid, mre, _dre = _probe_for_question(a.get("q") or "") | |
| if sid == "blindmonkeys" and mre.search(a.get("a", "")): | |
| bm_quote = a["a"] | |
| break | |
| sites_out = {} | |
| for sid, st in sites.items(): | |
| sites_out[sid] = { | |
| "site_name": SITE_NAMES.get(sid, sid), | |
| "mentioned": st.get("mentioned"), | |
| "verified": st.get("verified"), | |
| "quote": (st.get("quote") or "")[:800] or None, | |
| "first_seen": first_seen.get((eid, sid)) if st.get("verified") else None, | |
| } | |
| out.append({"engine": eid, "engine_name": e.get("engine_name", eid), | |
| "configured": True, | |
| "checked_at": e.get("checked_at"), | |
| "mentioned": bool(bm.get("mentioned")), | |
| "verified": bool(bm.get("verified")), | |
| "error": e.get("error"), | |
| "quote": bm_quote[:800] or None, | |
| "first_seen": first_seen.get((eid, "blindmonkeys")) if bm.get("verified") else None, | |
| "sites": sites_out}) | |
| return {"summary": out} |