Sub topic 10
Scripting repeated runs and scoring
This chapter turns the manual process from earlier chapters into a script. It assumes you already have a prompt set file in the format from the prompt-design chapter, a documented test protocol, and the scoring definitions (mention rate, position, share of voice). It also assumes you can read Python: functions, dictionaries, and file I/O. Scripting is optional. A spreadsheet works for a small prompt set. A script pays off once you have dozens of prompts, several repeats per prompt, and more than one assistant.
Split collection from scoring
Write two separate stages that communicate through a file.
- Collect. Send each prompt to the assistant several times. Save the raw answer and the test conditions, and do nothing else.
- Score. Read the saved file and compute mentions, positions, rates, and share of voice.
The split matters because collecting costs time and money, while scoring is free. If you find that your alias list missed "Acme" written as "ACME Analytics Ltd", you can fix the matcher and rescore the same answers. If the script stored only the computed mentions, you would have to re-run every prompt, and the new answers would differ from the old ones.
What to store for each run
Use JSON Lines (JSONL): one JSON object per line, appended as each run finishes. If the script crashes at run 140 of 200, the first 139 records are already on disk. Each record should carry enough to reproduce the protocol you documented earlier.
| Field | Example | Why it is stored |
|---|---|---|
| `prompt_id` | `disc-01` | Links the run to the prompt set and its type |
| `run` | `3` | Distinguishes repeats of the same prompt |
| `timestamp` | `2026-11-29T10:19:41+00:00` | Needed for comparing across dates |
| `conditions` | assistant, model, mode, settings | The protocol values for this batch |
| `answer` | full text | Raw material for rescoring |
| `error` | `null` or a message | Lets scoring skip failed runs without mistaking them for "brand not mentioned" |
The collection script
Save the next three blocks, in order, into one file named visibility_test.py. Save the prompt set from the earlier chapter as prompts.json in the same folder.
The first block loads the prompt set and detects mentions. The function build_name_map maps every alias to the canonical brand name. Without it, an answer saying "Acme Analytics (or just Acme)" would count as two brand mentions and inflate share of voice.
import json
import math
import random
import re
import time
import datetime as dt
from collections import defaultdict
from pathlib import Path
def load_prompt_set(path):
return json.loads(Path(path).read_text(encoding="utf-8"))
def build_name_map(prompt_set):
"""Map every surface form (brand, aliases, competitors) to one canonical name."""
brand = prompt_set["brand"]
name_map = {brand: brand}
for alias in prompt_set.get("aliases", []):
name_map[alias] = brand
for competitor in prompt_set.get("competitors", []):
name_map[competitor] = competitor
return name_map
def find_mentions(answer, name_map):
"""Canonical names found as whole words, ordered by first appearance."""
first_pos = {}
for surface, canonical in name_map.items():
match = re.search(r"\b" + re.escape(surface) + r"\b", answer, flags=re.IGNORECASE)
if match and (canonical not in first_pos or match.start() < first_pos[canonical]):
first_pos[canonical] = match.start()
return sorted(first_pos, key=first_pos.get)The second block does the collecting. The ask argument is any function that takes a prompt string and returns the answer text. Passing it in keeps the runner independent of the provider.
def with_retries(fn, attempts=3, base_delay=2.0):
"""Call fn(); on failure wait 2s, 4s, ... and try again. Re-raise after the last attempt."""
for attempt in range(attempts):
try:
return fn()
except Exception:
if attempt == attempts - 1:
raise
time.sleep(base_delay * 2 ** attempt)
def run_tests(prompt_set, ask, repeats, conditions, out_path, pause=1.0):
with open(out_path, "a", encoding="utf-8") as out:
for prompt in prompt_set["prompts"]:
for run in range(1, repeats + 1):
answer, error = "", None
try:
answer = with_retries(lambda: ask(prompt["text"]), base_delay=pause * 2 or 0)
except Exception as exc:
error = f"{type(exc).__name__}: {exc}"
record = {
"prompt_id": prompt["id"],
"run": run,
"timestamp": dt.datetime.now(dt.timezone.utc).isoformat(),
"conditions": conditions,
"answer": answer,
"error": error,
}
out.write(json.dumps(record) + "\n")
out.flush()
time.sleep(pause)Three details are deliberate:
- Failures are logged, not dropped. A record with
errorset is skipped at scoring time. Treating a failed call as an empty answer would count it as a miss and push your mention rate down for reasons unrelated to the brand. pausespaces out requests. This keeps you inside rate limits. Sending all repeats of a prompt in a burst can also trigger caching or throttling on some services.out.flush()after each line means a crash loses at most one record.
The scoring script
The third block reads the file and groups results by prompt type. It computes the mention rate, the average position when mentioned, and share of voice. It also computes a Wilson interval, a standard range for a proportion estimated from few trials. With 5 runs the interval will be wide, and that is the honest answer.
def wilson(hits, n, z=1.96):
"""Approximate 95% interval for a proportion hits/n."""
if n == 0:
return 0.0, 0.0
p = hits / n
denom = 1 + z * z / n
centre = (p + z * z / (2 * n)) / denom
half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom
return max(0.0, centre - half), min(1.0, centre + half)
def score(path, prompt_set):
name_map = build_name_map(prompt_set)
brand = prompt_set["brand"]
prompt_type = {p["id"]: p["type"] for p in prompt_set["prompts"]}
runs = defaultdict(int)
counts = defaultdict(lambda: defaultdict(int))
positions = defaultdict(list)
with open(path, encoding="utf-8") as f:
for line in f:
record = json.loads(line)
if record["error"]:
continue
ptype = prompt_type[record["prompt_id"]]
ordered = find_mentions(record["answer"], name_map)
runs[ptype] += 1
for name in ordered:
counts[ptype][name] += 1
if brand in ordered:
positions[ptype].append(ordered.index(brand) + 1)
rows = []
for ptype, n in runs.items():
hits = counts[ptype][brand]
total = sum(counts[ptype].values())
low, high = wilson(hits, n)
rows.append({
"type": ptype,
"runs": n,
"mention_rate": round(hits / n, 2),
"ci_95": (round(low, 2), round(high, 2)),
"avg_position": round(sum(positions[ptype]) / len(positions[ptype]), 2)
if positions[ptype] else None,
"share_of_voice": round(hits / total, 2) if total else 0.0,
})
return rowsShare of voice here is the brand's mentioned runs divided by all tracked-name mentioned runs, counted once per name per answer. Position is the rank of the brand among tracked names by first appearance. It ignores untracked tools the assistant names, so it is a relative position among the names you track.
Try it offline first
Before you spend money on API calls, test the pipeline with a fake assistant. This verifies the file format, the matcher, and the arithmetic. Add this to the bottom of visibility_test.py.
def fake_ask(text):
return random.choice([
"For a small shop, consider Example BI or Acme Analytics.",
"Sample Metrics and Example BI are popular choices.",
"Acme is a good fit for small teams.",
"Try a funnel report in your analytics tool.",
])
if __name__ == "__main__":
random.seed(7)
prompt_set = load_prompt_set("prompts.json")
conditions = {"assistant": "fake", "mode": "no-web", "settings": "default"}
run_tests(prompt_set, fake_ask, repeats=5, conditions=conditions,
out_path="runs.jsonl", pause=0)
for row in score("runs.jsonl", prompt_set):
print(row)Run python visibility_test.py. You should get one row per prompt type, each with 5 runs. The exact rates depend on the random seed, but the rows should show mention_rate between 0 and 1 and a wide ci_95.
Connecting a real assistant
Replace fake_ask with a function that calls your provider's client library and returns the answer text. Keep these points in mind:
- Read API keys from an environment variable, never from the script or the output file.
- Record the exact model identifier and the settings you pass (such as temperature) in
conditions. - Check whether the API behaves like the consumer app. Web search, saved memory, and system instructions can differ, so an API run may not match what a user sees. Record the mode and avoid claiming that results describe the consumer product unless you tested it there.
- Run one prompt per fresh conversation. Reusing a conversation lets earlier answers influence later ones.
Common errors
- Aliases counted twice. A matcher that checks "Acme Analytics" and "Acme" separately reports two mentions for one. Map aliases to one canonical name, as
build_name_mapdoes. - Word-boundary failures.
\bassumes the name begins and ends with a letter or digit. A name such as "C++" or "Acme!" will not match as intended. Use a custom pattern for those names. - Common-word brand names. A brand called "Notion" or "Slack" may match ordinary words. Review a sample of flagged answers by hand. Tighten the pattern or add a manual check where needed.
- Failed calls scored as misses. Always keep the
errorfield and exclude those runs from the denominator. - Scoring only the first sentence. Brands often appear in a list further down. Match against the full answer.
- Treating the interval as exact. The Wilson interval assumes independent trials. Repeats of one prompt are correlated, so the real uncertainty is somewhat larger. Use the interval as a warning sign for small samples.
- Not checking the matcher. Read at least 10 stored answers next to their computed mentions before trusting any table. Substring matching has no sense of context, so "Acme is not recommended" still counts as a mention. Sentiment and recommendation need a separate check, manual or otherwise.
Exercises
Exercise
The collection script saves the raw answer text instead of the list of mentions it found. Give two reasons this is the better design.
Show answer
First, you can rescore without new calls. If you add an alias or fix a matching bug, you rerun only the scoring stage, and the results stay comparable because they use the same answers. Second, the raw text lets you audit the matcher by reading answers next to their computed mentions, and lets you add metrics later (accuracy, sentiment, cited sources) that you did not plan for at collection time.
Exercise
A prompt was run 5 times and mentioned the brand in 2 runs. The mention rate is 0.4, and the Wilson interval is about 0.12 to 0.77. What does the interval tell you, and what would you change before drawing conclusions?
Show answer
The interval shows that 5 runs are too few to say whether the true rate is low or high; the data fit anything from roughly one in eight to three in four. To narrow it, increase the number of repeats per prompt, and group related prompts by type so the rate rests on more runs. Avoid claiming a change between two dates unless the intervals are clearly separated.
Exercise
For the "discovery" prompts, 12 tracked-name mentions were counted across all runs: 4 for the brand, 6 for Example BI, and 2 for Sample Metrics. What is the brand's share of voice, and why can a brand have a high mention rate but a low share of voice?
Show answer
Share of voice is 4 / 12, about 0.33. Mention rate asks how often the brand appears; share of voice asks how much of the tracked-name mentions it takes. If the assistant almost always names several competitors alongside the brand, the brand's mention rate can be high while its share stays low.