ai-visibility-index / code /avi_stability.py
jacobezra93's picture
v1.1.0: add the stability sub-study and what it means for the published rates
4ec1bb3 verified
Raw History Blame Contribute Delete
7.92 kB
# -*- coding: utf-8 -*-
"""AI Visibility Index: how stable is an AI answer?
SparkToro's 2026 work found that asking an AI tool the same recommendation
prompt repeatedly rarely returns the same list. Every published AI-visibility
number, including ours, takes ONE draw per market and reports it as a rate. If
the answer moves, that rate is one sample of a distribution nobody has measured.
This measures the distribution. It deliberately does NOT change the main index:
the monthly run keeps taking one draw per market so the series stays comparable
with August and September. This is a sub-study on a seeded random SUBSET, which
answers the question at about the cost of one ordinary run.
avi_stability.py --dry-run show the plan and cost, call nothing
avi_stability.py run it (default 10 markets x 5 repeats)
AVI_SB_MARKETS=8 AVI_SB_REPEATS=7 avi_stability.py
Output: ai_index/stability_<stamp>.json
"""
import datetime, json, os, random, statistics as st, sys, time
sys.path.insert(0, "/root/Desktop/SEMPITE Reports")
import ai_visibility_index as avi # safe to import since 2026-09-20
from avi_matcher import mentioned, MATCHER_VERSION
N_MARKETS = int(os.environ.get("AVI_SB_MARKETS", 10))
N_REPEATS = int(os.environ.get("AVI_SB_REPEATS", 5))
SEED = int(os.environ.get("AVI_SB_SEED", 20261001))
DRY = "--dry-run" in sys.argv
OUT_DIR = "/root/Desktop/SEMPITE Reports/ai_index"
# from the cron note: a 50-market full run costs about $1.75 across 4 calls each
COST_PER_MARKET_COLLECTION = 1.75 / 50
MIN_BALANCE_HEADROOM = 5.00
ENGINES = ["chatgpt", "chatgpt_web", "google_ai"] # claude stays paused
# ---------------------------------------------------------------- the subset
markets = [(c, city) for c in avi.FULL["categories"] for city in avi.FULL["cities"]]
rng = random.Random(SEED)
subset = rng.sample(markets, min(N_MARKETS, len(markets)))
collections = len(subset) * N_REPEATS
est_cost = collections * COST_PER_MARKET_COLLECTION
print(f"stability sub-study: {len(subset)} markets x {N_REPEATS} repeats = {collections} collections")
print(f"seed {SEED}, engines {ENGINES}")
print(f"estimated DataForSEO cost: ${est_cost:.2f} (a full 50-market run is ~$1.75)")
print("\nmarkets:")
for c, city in subset:
print(f" {c} / {city}")
if DRY:
print("\nDRY RUN. nothing called, nothing spent.")
sys.exit(0)
bal = avi.dfs_balance()
print(f"\nDataForSEO balance: ${bal:.2f}")
if bal < est_cost + MIN_BALANCE_HEADROOM:
sys.exit(f"balance ${bal:.2f} is under the estimate ${est_cost:.2f} plus ${MIN_BALANCE_HEADROOM:.2f} headroom. Not starting.")
# ---------------------------------------------------------------- collect
rows = []
for cat, city in subset:
print(f"\n[{cat} / {city}]", flush=True)
top3 = avi.maps_top3(cat, city)
if not top3:
print(" no maps data, skipping market"); continue
q = (f"I need a {cat} in {city}. Who are the best {cat}s there? "
f"Please recommend specific businesses by name.")
row = {"category": cat, "city": city, "top3": top3, "repeats": []}
for i in range(N_REPEATS):
answers = {"chatgpt": avi.ask_chatgpt(q), "chatgpt_web": avi.ask_chatgpt(q, web=True),
"google_ai": avi.ask_google_ai(cat, city)}
rep = {"repeat": i + 1, "collected_utc": datetime.datetime.utcnow().isoformat(timespec="seconds") + "Z",
"answers": {}}
for eng, ans in answers.items():
if ans is None:
continue # unavailable, never counted as a miss
rep["answers"][eng] = {
"top3_mentioned": [bool(mentioned(b["name"], ans, b.get("domain"))) for b in top3],
"text": ans,
}
row["repeats"].append(rep)
print(f" repeat {i+1}/{N_REPEATS}: " +
", ".join(f"{e}={sum(a['top3_mentioned'])}/3" for e, a in rep["answers"].items()), flush=True)
time.sleep(1.5)
rows.append(row)
# ---------------------------------------------------------------- stability
def analyse(rows):
out = {}
for eng in ENGINES:
pairs = [] # (times_named, repeats_with_an_answer) per business
per_repeat_rates = []
market_detail = []
for r in rows:
reps = [rep["answers"][eng] for rep in r["repeats"] if eng in rep["answers"]]
if len(reps) < 2:
continue # cannot say anything about stability from one draw
n = len(reps)
counts = [sum(rep["top3_mentioned"][i] for rep in reps) for i in range(len(r["top3"]))]
pairs += [(c, n) for c in counts]
rates = [100 * (1 - sum(rep["top3_mentioned"]) / len(r["top3"])) for rep in reps]
per_repeat_rates += rates
market_detail.append({
"market": f"{r['category']} / {r['city']}",
"repeats": n,
"per_business_times_named": counts,
"invisibility_by_repeat_pct": [round(x, 1) for x in rates],
"spread_pct": round(max(rates) - min(rates), 1),
})
if not pairs:
out[eng] = {"status": "insufficient repeats"}
continue
always = sum(1 for c, n in pairs if c == n)
never = sum(1 for c, n in pairs if c == 0)
sometimes = len(pairs) - always - never
ever = always + sometimes
spreads = [m["spread_pct"] for m in market_detail]
out[eng] = {
"businesses_observed": len(pairs),
"always_named": always,
"never_named": never,
"sometimes_named": sometimes,
"unstable_share_of_ever_named_pct": round(100 * sometimes / ever, 1) if ever else None,
"invisibility_mean_pct": round(st.mean(per_repeat_rates), 1),
"invisibility_sd_pct": round(st.pstdev(per_repeat_rates), 1) if len(per_repeat_rates) > 1 else 0.0,
"market_spread_pct": {"median": round(st.median(spreads), 1),
"max": round(max(spreads), 1)},
"markets": market_detail,
}
return out
stability = analyse(rows)
stamp = os.environ.get("AVI_STAMP") or datetime.date.today().strftime("%Y-%m")
out = {
"run": stamp,
"study": "stability sub-study",
"generated_utc": datetime.datetime.utcnow().isoformat(timespec="seconds") + "Z",
"design": {
"why": ("Published AI-visibility rates, including our own, take one draw per market. "
"This measures how much a single draw moves when the same prompt is repeated."),
"markets_sampled": len(rows), "repeats_per_market": N_REPEATS, "seed": SEED,
"selection": "seeded random sample of the 50-market frame; the frame itself is unchanged",
"engines": ENGINES, "matcher": MATCHER_VERSION,
"note": ("The monthly index still takes ONE draw per market so the series stays "
"comparable with earlier editions. This sub-study does not replace it."),
},
"stability": stability,
"rows": rows,
}
path = f"{OUT_DIR}/stability_{stamp}.json"
if os.path.exists(path):
path = f"{OUT_DIR}/stability_{stamp}_{datetime.datetime.utcnow():%d%H%M}.json"
json.dump(out, open(path, "w"), ensure_ascii=False, indent=1)
print("\n=== STABILITY ===")
for eng, s in stability.items():
if s.get("status"):
print(f"{eng:12} {s['status']}"); continue
print(f"{eng:12} of {s['businesses_observed']} top-3 businesses: "
f"{s['always_named']} always named, {s['sometimes_named']} sometimes, {s['never_named']} never")
print(f"{'':12} {s['unstable_share_of_ever_named_pct']}% of those ever named were NOT named every time")
print(f"{'':12} invisibility {s['invisibility_mean_pct']}% mean, sd {s['invisibility_sd_pct']} points, "
f"median market spread {s['market_spread_pct']['median']} points")
print("\nsaved:", path)