---
title: "How to Build an LLM Visibility Tracker With Python"
description: "Learn how to build an LLM visibility tracker with Python to monitor brand mentions, cited domains, ads, and price accuracy across ChatGPT, Gemini, and Google."
url: "https://www.scrapingbee.com/blog/how-to-build-an-llm-visibility-tracker-with-python/"
canonical: "https://www.scrapingbee.com/blog/how-to-build-an-llm-visibility-tracker-with-python/"
date: 2026-11-27
lastmod: 2026-11-27
author: "Satyam Tripathi"
publisher: "ScrapingBee"
---

# How to Build an LLM Visibility Tracker With Python

An LLM visibility tracker measures how AI engines present your brand. It sends a fixed prompt set to ChatGPT, Gemini, Google AI Mode, and AI Overviews on a schedule. It reports how often each engine mentions your brand or its competitors and cites your site.

In a test with the invoicing app FreshBooks, answers mentioned the brand but cited other sites. ChatGPT also showed ads, which a simple mention count treats as organic mentions.

This guide shows you how to build one in Python with the ScrapingBee APIs, separate ads from mentions and citations, and size the prompt set.

![How to build an LLM visibility tracker with Python](https://www.scrapingbee.com/blog/how-to-build-an-llm-visibility-tracker-with-python/cover.png)


## TL;DR

* **Separate mentions from citations**. ChatGPT, Gemini, and AI Mode mentioned FreshBooks in 39 of 60 answers to unbranded prompts but cited [freshbooks.com](http://freshbooks.com) once, in a US test through ScrapingBee.
* **Report ads separately**. Ads appeared in 16 of 24 ChatGPT answers, and counting them raised QuickBooks from 8 mentions to 11.
* **Count prompts, not repeated answers**. FreshBooks' 60% mention rate in ChatGPT comes from 5 prompts, so its 95% interval ranges from 20% to 100%.
* **Check stated prices**. Of 12 answers with a FreshBooks price, 6 were below the $23 list price, and 5 of those 6 cited one blog post.

## What an LLM visibility tracker measures

A visibility tracker stores every answer and reports 5 metrics:

* **Mention rate**. The share of answers that mention the brand.
* **Own-domain citation rate**. The share of answers that cite a page on the brand's own domain.
* **Cited domains**. The domains each engine cites for the topic, which show where your brand should appear.
* **Sponsored placements**. The ads shown with the answer, counted separately from organic mentions.
* **Price accuracy**. Whether the prices that the answers state for your brand match your pricing page.

The tracker reports rates rather than rankings, because a brand's rank shifts when the same prompt is sent again. Here, a brand's rank is its position among the tracked brands in the order that the answer mentions them. In the FreshBooks example, there were 45 cases where a brand appeared in all 4 answers to the same prompt, and the brand kept the same rank in only 8 of them. A rate with a confidence interval shows whether a change from one reporting window to the next is larger than the noise.

## Why the tracker collects answers from the apps, not the model APIs

The OpenAI and Gemini model APIs return the model's answer, with [web search](https://platform.openai.com/docs/guides/tools-web-search) or [Google Search grounding](https://ai.google.dev/gemini-api/docs/google-search) as an optional tool. The consumer apps add their own retrieval step, product cards, and inline citations. ChatGPT and Google AI Mode also add ads.

A [1K-prompt study of scraped and API answers](https://surfer.ai/blog/llm-scraped-ai-answers-vs-api-results) found that the OpenAI API mentioned almost twice as many brands per answer as the ChatGPT app. The app cited about 4 times as many sources as the API. A tracker built on the model APIs measures answers that can differ from what people see in the ChatGPT and Gemini apps.

This tracker collects its answers from the same apps that people use. In the FreshBooks example, the ChatGPT answers collected through ScrapingBee included the ads that ChatGPT shows on its [Free and Go plans](https://help.openai.com/en/articles/20001047-ads-in-chatgpt). The report lists those ads as sponsored placements.

The tracker sends the same prompts the same way on a schedule, geotargeted to the country you choose. A manual check, such as a colleague's screenshot, shows a single answer, and that person's memory, chat history, and location can change that answer. For example, a user signed in to ChatGPT in India asked for the "best invoicing software for freelancers" and got an answer localized for the Indian market:

![ChatGPT answering 'best invoicing software for freelancers' for a user signed in from India in November 2026. The highlighted opening line reads 'If you're freelancing in India' and the answer recommends Zoho Invoice and Refrens.](https://www.scrapingbee.com/blog/how-to-build-an-llm-visibility-tracker-with-python/chatgpt-answer.png)


## Which ScrapingBee APIs the tracker calls

The ScrapingBee [ChatGPT API](https://www.scrapingbee.com/features/chatgpt/) returns ChatGPT responses as JSON, with the answer text, citations, links, and ads. The ScrapingBee [Gemini API](https://www.scrapingbee.com/features/gemini/) returns Gemini's answer, with the sources Gemini cites in a dedicated `citations` field. The ScrapingBee Google Search API returns both [AI Mode](https://www.scrapingbee.com/scrapers/google-ai-mode-api/) answers and [AI Overviews](https://www.scrapingbee.com/scrapers/google-ai-overview-api/). One API key works for all 4 engines:

<!-- linear:table-colwidths:177,186,200,200 -->
| Engine | ScrapingBee endpoint | Request parameters | Response fields |
| -- | -- | -- | -- |
| ChatGPT | `/api/v1/chatgpt` | `prompt`, `search=true`, `country_code` | `results_markdown`, `citations`, `ads` |
| Gemini | `/api/v1/gemini` | `prompt`, `country_code` | `results_markdown`, `citations` |
| Google AI Mode | `/api/v1/google` | `search`, `search_type=ai_mode`, `country_code` | `ai_mode_answer` |
| Google AI Overviews | `/api/v1/google` | `search`, `expand_aio=true`, `country_code` | `ai_overviews` |

ScrapingBee bills each request in API credits. Each response reports its credit cost in the `spb-cost` response header, and the tracker stores that value with every answer. The [ChatGPT API documentation](https://www.scrapingbee.com/documentation/chatgpt/) lists the current credit cost of a ChatGPT request. The [Gemini API documentation](https://www.scrapingbee.com/documentation/gemini/) and the [Google Search API documentation](https://www.scrapingbee.com/documentation/google-api/) do the same for those APIs.

## Set up the project

The finished tracker has 4 short scripts (`tracker.py`, `report.py`, `claims.py`, `seed_prompts.py`), a SQLite database, and a daily cron job.

You need Python 3.11 or newer, the [uv](https://docs.astral.sh/uv/) package manager, and a ScrapingBee API key. [Create a free ScrapingBee account](https://dashboard.scrapingbee.com/account/register) to get the key and free API credits. No credit card is required. After you sign in, the **HTML Playground** shows **Your API Key** at the top right:

![The ScrapingBee HTML Playground after sign-in, with the Your API Key field highlighted at the top right. The key value is blurred.](https://www.scrapingbee.com/blog/how-to-build-an-llm-visibility-tracker-with-python/api-key.png)


Create the project and install its only dependency, HTTPX:

```python
uv init llm-visibility
cd llm-visibility
uv add httpx
```

`uv init` also creates a sample `main.py` file, which you can delete. If HTTPX is new to you, read [how to web scrape with HTTPX and Python](https://www.scrapingbee.com/blog/web-scraping-with-httpx/).

Store the key as an environment variable in a `.env` file in the project directory, so that scheduled runs can read the key later. Replace `YOUR_API_KEY` with the key from the dashboard:

```python
echo 'SCRAPINGBEE_API_KEY=YOUR_API_KEY' > .env
chmod 600 .env
```

On Windows, create the same `.env` file in a text editor and skip the `chmod` command.

## Collect answers from ChatGPT, Gemini, AI Mode, and AI Overviews

The collector sends each prompt to the 4 engines and normalizes every response into the same schema. It stores each record with the raw JSON in a SQLite database, which `report.py` and `claims.py` read later:

![The pipeline of the LLM visibility tracker, where prompts.txt feeds tracker.py, which sends each prompt to ChatGPT, Gemini, AI Mode, and AI Overviews through the ScrapingBee API and stores the answers in visibility.db, which report.py and claims.py read.](https://www.scrapingbee.com/blog/how-to-build-an-llm-visibility-tracker-with-python/pipeline.png)


### Save the prompt set

Keep the prompts in `prompts.txt`, one per line, so the set can grow without code changes. The FreshBooks example tracks the brand against 7 competitors with 6 questions that a freelancer might ask. These 6 questions are enough to test the pipeline but too few to report a rate. To follow along, save them as `prompts.txt`:

```python
best invoicing software for freelancers
what invoicing app should a freelance designer use
FreshBooks alternatives
cheapest way to send professional invoices as a freelancer
invoicing software that tracks time for freelancers
is Wave really free for invoicing
```

The prompts mix category, comparison, and branded questions, because different question types tend to produce answers with different brands. Google AI Mode receives each prompt as a Google search, so phrase your prompts the way people search. To track your own brand instead, write your own buyer questions in `prompts.txt` now, and change the brand settings in `report.py` and `claims.py` when you reach those scripts.

### Map each engine to its endpoint

The collector is one file, `tracker.py`. Create it with the first part, which loads the prompt set and maps each engine to its endpoint:

```python
"""Collect answers from ChatGPT, Gemini, Google AI Mode and AI Overviews
through ScrapingBee, and store every raw answer in SQLite."""

import asyncio
import json
import os
import re
import sqlite3
import sys
import time
import uuid

import httpx

API = "https://app.scrapingbee.com/api/v1"
AUTH = {"Authorization": f"Bearer {os.environ['SCRAPINGBEE_API_KEY']}"}
DB = "visibility.db"

with open("prompts.txt", encoding="utf-8") as f:
    PROMPTS = [line.strip() for line in f if line.strip()]
ENGINES = ["chatgpt", "gemini", "ai_mode", "ai_overview"]
COUNTRY = "us"


def request_for(engine: str, prompt: str) -> tuple[str, dict]:
    """Map one engine to its ScrapingBee endpoint and parameters."""
    if engine == "chatgpt":
        return "chatgpt", {"prompt": prompt, "search": "true",
                           "country_code": COUNTRY}
    if engine == "gemini":
        return "gemini", {"prompt": prompt, "country_code": COUNTRY}
    if engine == "ai_mode":
        return "google", {"search": prompt, "search_type": "ai_mode",
                          "country_code": COUNTRY}
    if engine == "ai_overview":
        return "google", {"search": prompt, "expand_aio": "true",
                          "country_code": COUNTRY}
    raise ValueError(engine)
```

The tracker sends the API key as a Bearer token in the `Authorization` header, which is the [recommended authentication method](https://www.scrapingbee.com/documentation/#api_key) for the ScrapingBee APIs. ChatGPT gets `search=true`, so its answer includes the sources it used. AI Overviews get `expand_aio=true`, which returns the expanded AI Overview that a user sees. If your buyers are outside the US, set `COUNTRY` to one of the [supported country codes](https://www.scrapingbee.com/documentation/country_codes/).

### Normalize the answers and strip ads

Add the second part to `tracker.py`. It normalizes each engine's response into the same schema and strips the sponsored block from ChatGPT's markdown before the report counts mentions:

```python
def strip_ads(md: str) -> str:
    """Cut each sponsored block out of ChatGPT's markdown, using the two
    markers the captured ads carried: an olref= link parameter and a
    closing 'Report this ad' line."""
    while (hit := md.find("olref=")) != -1:
        start = md.rfind("\n", 0, hit) + 1
        end = md.find("Report this ad", hit)
        end = md.find("\n", end) if end != -1 else -1
        if end == -1:  # the ad runs to the end of the answer
            return md[:start]
        nxt = md.find("\n", end + 1)
        line = md[end + 1:nxt if nxt != -1 else len(md)].strip()
        if line and set(line) <= set("-="):  # skip the dashed underline
            end = nxt if nxt != -1 else len(md)
        md = md[:start] + md[end:]
    return md


IMAGES = re.compile(r"!\[[^\]]*\]\([^)]*\)")


def normalize(engine: str, body: dict) -> dict:
    """Reduce each engine's payload to: answered, text, cited URLs, ads."""
    if engine == "chatgpt":
        text = strip_ads(body.get("results_markdown") or "")
        ads = [{"advertiser": (a.get("advertiser_info") or {}).get("name"),
                "title": a.get("title"), "url": a.get("url")}
               for a in body.get("ads") or []]
        urls = [c["url"] for c in body.get("citations") or []]
    elif engine == "gemini":
        text, ads = body.get("results_markdown") or "", []
        urls = [c["url"] for c in body.get("citations") or []]
    elif engine == "ai_mode":
        answer = body.get("ai_mode_answer") or {}
        text = answer.get("response_text") or ""
        ads = [{"advertiser": (a.get("source") or {}).get("title"),
                "title": a.get("title"),
                "url": (a.get("source") or {}).get("url")}
               for a in answer.get("sponsored_results") or []]
        urls = [u for c in answer.get("citations") or [] for u in c["urls"]]
        urls += [link["url"] for link in answer.get("links") or []]
    else:  # ai_overview: the field is empty when Google shows none
        parts, urls, ads = [], [], []
        for box in body.get("ai_overviews") or []:
            for block in box.get("answer_text") or []:
                for frag in block.get("fragments") or []:
                    parts.append(frag.get("text", ""))
                    urls += [r["url"] for r in frag.get("references") or []]
            for blist in box.get("bullet_list") or []:
                for point in blist.get("points") or []:
                    parts.append(point.get("text", ""))
                    urls += [r["url"] for r in point.get("references") or []]
            panel = (box.get("source_panel") or {}).get("items") or []
            urls += [item["url"] for item in panel]
        text = "\n".join(parts)
    text = IMAGES.sub("", text)
    return {"answered": bool(text.strip()), "text": text,
            "urls": list(dict.fromkeys(urls)), "ads": ads}
```

ScrapingBee returns ChatGPT's ads in a dedicated `ads` field, and `results_markdown` keeps the answer as ChatGPT shows it, sponsored block included. The tracker counts organic mentions only, so it strips that block first.

In every ad from the FreshBooks example, the ad link contained an `olref=` query parameter and the sponsored block ended with a "Report this ad" line. `strip_ads()` finds the sponsored block by those 2 markers instead of by the ad's text. New ad text doesn't break it, and a change to a marker needs only a one-line update.

For AI Mode, ScrapingBee returns the ads in a separate `sponsored_results` field and excludes them from `response_text`. The AI Mode branch copies them into `ads` and strips nothing.

When Google shows no AI Overview for a request, the AI Overview branch returns a record with `answered` set to `False`. Count that case separately from an AI Overview that skips your brand. If you count both as answers without your brand, the report understates your visibility.

### Send the requests and store the answers

Add the last part to `tracker.py`. It sends the requests [in parallel with asyncio](https://www.scrapingbee.com/blog/async-scraping-in-python/), resolves Google's redirect links, and writes everything to SQLite:

```python
async def resolve(client: httpx.AsyncClient, url: str) -> str:
    """Return the source URL behind a google.com/goto link. The request
    goes to Google and uses no ScrapingBee credits."""
    if "google.com/goto" not in url:
        return url
    try:
        r = await client.get(url, follow_redirects=False, timeout=15)
        return r.headers.get("location", url)
    except httpx.HTTPError:
        return url


async def ask(client, sem, engine, prompt, run_id, db):
    path, params = request_for(engine, prompt)
    async with sem:
        for attempt in range(3):
            try:
                r = await client.get(f"{API}/{path}", params=params,
                                     headers=AUTH, timeout=180)
            except httpx.HTTPError as exc:
                status, body = 0, {"error": repr(exc)}
            else:
                status = r.status_code
                body = r.json() if "json" in r.headers.get(
                    "content-type", "") else {"error": r.text[:500]}
            if status == 200 or status in (400, 401, 403):
                break  # success, or an error that a retry won't fix
            await asyncio.sleep(5 * (attempt + 1))
    cost = int(r.headers.get("spb-cost", 0)) if status == 200 else 0
    out = {"answered": False, "text": "", "urls": [], "ads": []}
    if status == 200:
        try:
            out = normalize(engine, body)
        except (KeyError, TypeError) as exc:  # a shape normalize() misses
            print(f"{engine:<12} raw answer kept, cannot parse it: {exc!r}")
    resolved = [await resolve(client, u) for u in out["urls"]]
    out["urls"] = list(dict.fromkeys(resolved))  # a redirect can repeat a URL
    # Store ChatGPT's answer in its markdown format only
    raw = {k: v for k, v in body.items()
           if k not in ("results_text", "results_json")}
    db.execute(
        "INSERT INTO answers VALUES (?,?,?,?,?,?,?,?,?,?,?,?)",
        (run_id, time.strftime("%Y-%m-%dT%H:%M:%S"), engine, prompt,
         COUNTRY, status, int(out["answered"]), out["text"],
         json.dumps(out["urls"]), json.dumps(out["ads"]), cost,
         json.dumps(raw)))
    db.commit()
    print(f"{engine:<12} {status} {cost:>3} credits  {prompt[:40]}",
          flush=True)


async def main(samples: int) -> None:
    db = sqlite3.connect(DB)
    db.execute("""CREATE TABLE IF NOT EXISTS answers (
        run_id TEXT, ts TEXT, engine TEXT, prompt TEXT, country TEXT,
        status INT, answered INT, text TEXT, urls TEXT, ads TEXT,
        credits INT, raw TEXT)""")
    usage = httpx.get(f"{API}/usage", headers=AUTH, timeout=30).json()
    left = usage["max_api_credit"] - usage["used_api_credit"]
    # Estimate the run from what each engine billed in earlier runs
    billed = dict(db.execute("SELECT engine, MAX(credits) FROM answers "
                             "GROUP BY engine"))
    need = samples * len(PROMPTS) * sum(billed.get(e, 0) for e in ENGINES)
    if need > left:  # a run that stops halfway leaves gaps in the history
        sys.exit(f"run needs about {need} credits, {left} left")
    run_id = uuid.uuid4().hex[:8]
    sem = asyncio.Semaphore(usage["max_concurrency"])
    # The key goes only to ScrapingBee, never to the Google redirects
    async with httpx.AsyncClient() as client:
        jobs = [ask(client, sem, e, p, run_id, db)
                for _ in range(samples) for p in PROMPTS for e in ENGINES]
        results = await asyncio.gather(*jobs, return_exceptions=True)
    for err in [r for r in results if isinstance(r, Exception)]:
        print(f"skipped a request: {err!r}")  # the rest of the run went on
    spent = db.execute("SELECT SUM(credits) FROM answers WHERE run_id=?",
                       (run_id,)).fetchone()[0]
    print(f"run {run_id}: {len(jobs)} requests, {spent} credits")


if __name__ == "__main__":
    asyncio.run(main(int(sys.argv[1]) if len(sys.argv) > 1 else 1))
```

When web search is enabled, ChatGPT runs a live web search before it answers, so `ask()` gives each request a long timeout. ScrapingBee retries failed requests automatically and bills only successful ones, as the documentation of the ChatGPT, Gemini, and Google Search APIs describes. `ask()` also retries network errors, rate limits (HTTP 429), and server errors (5xx) client-side, and those failed attempts cost no credits.

AI Mode wraps many source links in `google.com/goto` redirects. `resolve()` requests each redirect link without the `Authorization` header and reads the real URL from the `Location` header, so your API key goes only to ScrapingBee.

ScrapingBee returns ChatGPT's answer as plain text, markdown, and structured JSON. Before the tracker stores the raw JSON, it removes the plain-text and structured-JSON copies of ChatGPT's answer and keeps the markdown copy. Keeping the raw JSON lets you re-analyze old answers after you change a brand pattern, without paying for them again.

Before the first request, `main()` calls the account's `/usage` endpoint and sets the number of parallel requests to your plan's concurrency limit. From the second run on, `main()` knows what each engine costs. It then exits before sending any request if the remaining credits aren't enough for the run, because a half-finished run leaves gaps in the time series.

### Run the collector

The command-line argument after `tracker.py` sets the number of samples, which is how many times each prompt goes to each engine in one run. For a first run on the free credits and for daily runs, 1 sample is enough:

`uv run --env-file .env tracker.py 1`

Each line of output shows the engine, the HTTP status, and the credits billed, and the last line shows the run's total. Use more samples only when you want to measure the run-to-run variance of the answers to one prompt, which is why the FreshBooks example used 4 samples.

## Measure mentions, citations, and ads

The report reads the stored answers and makes no API calls. You can re-run it as often as you like, and adding a competitor later costs no extra credits. Save it as `report.py`:

```python
"""Score stored answers: mention rate, own-domain citation rate, and ads,
per engine and brand. Re-running it costs no credits."""

import json
import random
import re
import sqlite3
import sys
from collections import Counter, defaultdict
from urllib.parse import urlparse

BRANDS = {  # name: (case-sensitive pattern, owned domains)
    "FreshBooks": (r"FreshBooks", ["freshbooks.com"]),
    "QuickBooks": (r"QuickBooks", ["intuit.com"]),
    "Wave": (r"\bWave\b(?! of\b)", ["waveapps.com"]),
    "Zoho": (r"Zoho", ["zoho.com"]),
    "Bonsai": (r"Bonsai", ["hellobonsai.com"]),
    "HoneyBook": (r"HoneyBook", ["honeybook.com"]),
    "Invoice Ninja": (r"Invoice ?Ninja", ["invoiceninja.com"]),
    "Xero": (r"\bXero\b", ["xero.com"]),
}
OWNED = [d for _, domains in BRANDS.values() for d in domains]


def domain(url: str) -> str:
    host = urlparse(url).netloc.lower()
    return host.removeprefix("www.")


def owns(url: str, domains: list[str]) -> bool:
    host = domain(url)
    return any(host == d or host.endswith("." + d) for d in domains)


def rate(per_prompt: dict) -> float:
    """Average of each prompt's share, so every prompt counts once."""
    shares = [sum(v) / len(v) for v in per_prompt.values()]
    return sum(shares) / len(shares)


def prompt_interval(per_prompt: dict, draws: int = 2000) -> tuple:
    """95% interval that resamples whole prompts, because repeats of one
    prompt are correlated and do not add independent answers."""
    rng = random.Random(0)
    keys = list(per_prompt)
    means = sorted(rate({i: per_prompt[k] for i, k in
                         enumerate(rng.choices(keys, k=len(keys)))})
                   for _ in range(draws))
    return means[int(draws * 0.025)], means[int(draws * 0.975) - 1]


def main() -> None:
    since = sys.argv[1] if len(sys.argv) > 1 else ""  # e.g. 2026-11-01
    until = sys.argv[2] if len(sys.argv) > 2 else "9999"  # exclusive end date
    db = sqlite3.connect("visibility.db")
    rows = db.execute("SELECT engine, prompt, answered, text, urls, ads "
                      "FROM answers WHERE ts >= ? AND ts < ?",
                      (since, until)).fetchall()
    total, answered = Counter(), Counter()
    mentions = defaultdict(lambda: defaultdict(list))
    cites = defaultdict(lambda: defaultdict(list))
    cited_domains, advertisers = defaultdict(Counter), Counter()
    for engine, prompt, ok, text, urls, ads in rows:
        total[engine] += 1
        for advertiser in {ad["advertiser"] for ad in json.loads(ads)}:
            advertisers[(engine, advertiser)] += 1
        if not ok:
            continue
        answered[engine] += 1
        # Drop product-card logo pages, but keep the brands' own pages
        urls = [u for u in json.loads(urls)
                if "logo" not in u.lower() or owns(u, OWNED)]
        cited_domains[engine].update({domain(u) for u in urls})
        for brand, (pattern, owned) in BRANDS.items():
            if re.search(pattern, prompt, re.IGNORECASE):
                continue  # a prompt that names the brand gets it back
            key = (engine, brand)
            mentions[key][prompt].append(bool(re.search(pattern, text)))
            cites[key][prompt].append(any(owns(u, owned) for u in urls))

    for engine in total:
        print(f"\n{engine}: {answered[engine]} answers "
              f"from {total[engine]} requests")
        if answered[engine] == 0:
            continue
        print(f"  {'brand':<14}{'prompts':>8}{'mentioned':>11}"
              f"{'95% CI':>13}{'own site cited':>16}")
        for brand in BRANDS:
            key = (engine, brand)
            if not mentions[key]:
                continue
            lo, hi = prompt_interval(mentions[key])
            print(f"  {brand:<14}{len(mentions[key]):>8}"
                  f"{rate(mentions[key]):>10.0%} {lo:>5.0%}-{hi:<5.0%}"
                  f"{rate(cites[key]):>14.0%}")
        ranked = sorted(cited_domains[engine].items(),
                        key=lambda item: (-item[1], item[0]))
        top = ", ".join(f"{d} ({c})" for d, c in ranked[:5])
        print(f"  most cited: {top}")
    print("\nsponsored placements (separate from organic mentions):")
    for (engine, advertiser), count in sorted(
            advertisers.items(), key=lambda item: (-item[1], item[0])):
        print(f"  {engine}: {advertiser} in {count} of {total[engine]}")


if __name__ == "__main__":
    main()
```

The brand regex patterns are case-sensitive, so the `Wave` pattern doesn't match "a wave of" in lowercase text. Its `(?! of\b)` negative lookahead also skips "Wave of" at the start of a sentence but still matches "Wave offers" in an answer. Write these patterns from how the brands appear in your stored answers, not from the names on their pricing pages. Add your brand and its competitors to `BRANDS`, each with its regex pattern and owned domains.

ChatGPT's citations also include the pages that its product-card images come from, such as logo download sites. The logo filter drops URLs that contain "logo" from the cited domains, except pages on the tracked brands' own domains.

The report skips a brand on every prompt that names it. All 12 answers to "FreshBooks alternatives" mentioned FreshBooks, so that prompt would raise FreshBooks' rate without telling you much about its visibility. Use branded prompts to read what the answers say about you, and use unbranded prompts for the mention rate. Because the database keeps every answer, you can also read whether an engine recommends your brand or only lists it.

The rate gives every prompt the same weight, and the 95% confidence interval comes from a bootstrap that resamples whole prompts instead of single answers. Samples of one prompt are correlated, so an interval computed over single answers counts each sample as an independent observation and comes out too narrow. If every prompt gives the same share, the interval shrinks to one value. A single value doesn't mean that the rate is exact, because a small prompt set can give the same share on every prompt by chance.

Run the report:

`uv run report.py`

To analyze one time window, pass its start date and its end date. The end date is exclusive, so `uv run report.py 2026-11-01 2026-11-15` covers the first 2 weeks of November. To compare 2 windows, run the report once for each window.

Your own run will print different numbers, because the answers change from run to run. After 4 samples of the 6 prompts, the FreshBooks example printed this ChatGPT section and the sponsored placements of all engines. FreshBooks and Wave show 5 prompts, because each of them is named in one prompt:

```python
chatgpt: 24 answers from 24 requests
  brand          prompts  mentioned       95% CI  own site cited
  FreshBooks           5       60%   20%-100%             0%
  QuickBooks           6       33%    0%-67%              0%
  Wave                 5       90%   70%-100%             0%
  Zoho                 6       75%   42%-100%            50%
  Bonsai               6       58%   25%-92%              0%
  HoneyBook            6       25%    0%-58%              0%
  Invoice Ninja        6       17%    4%-33%              0%
  Xero                 6       17%    0%-50%              0%
  most cited: serpastra.com (14), hackceleration.com (13), rankite.com (12), zoho.com (12), itechguides.com (11)

sponsored placements (separate from organic mentions):
  chatgpt: Intuit Quickbooks in 9 of 24
  ai_mode: BILL in 4 of 24
  chatgpt: Mercury in 4 of 24
  ai_mode: Zoho in 2 of 24
  chatgpt: Housecall Pro in 1 of 24
  chatgpt: LegalTime, Inc. in 1 of 24
  chatgpt: Sage in 1 of 24
```

Compare these rates with your organic rankings and your analytics. Rankings show whether the cited pages also rank for the same questions. Our guide to [SERP monitoring with Python](https://www.scrapingbee.com/blog/how-to-monitor-google-serp/) builds a rank tracker with the same Google Search API.

In analytics, treat the sessions attributed to ChatGPT as a lower bound. In the FreshBooks example, only some links in ChatGPT's answers carried `utm_source=chatgpt.com`. Clicks from apps such as the ChatGPT desktop app can arrive without a referrer and count as direct traffic. To connect the rates to revenue, add a self-reported attribution question such as "How did you hear about us?" to your sign-up form, and track the answers over time.

## Check the prices the answers state

An answer can mention your brand and still state an incorrect fact about it. For example, on November 19, 2026, each app received the question "How much does FreshBooks Lite cost per month in the US?" Gemini answered $21, and ChatGPT and Google AI Mode answered $23, which matches the FreshBooks pricing page:

![The question 'How much does FreshBooks Lite cost per month in the US?' asked on November 19, 2026. Gemini answers '$21 per month at its standard US rate' while ChatGPT answers '$23 USD per month' and Google AI Mode answers '$23.00 USD per month' with a FreshBooks source link. Each answer is highlighted.](https://www.scrapingbee.com/blog/how-to-build-an-llm-visibility-tracker-with-python/price-question.png)


Price is a good fact to check first, because answers state it as a number and your pricing page lists the correct price. Save this as `claims.py`:

```python
"""Check the prices that AI answers state for your brand against your
price list, and find the cited pages that state the same wrong price."""

import json
import os
import re
import sqlite3

import httpx

from report import BRANDS

BRAND = "FreshBooks"
PRICE_LIST = {23, 43, 70, 20.70, 38.70, 63}  # monthly and yearly billing
API = "https://app.scrapingbee.com/api/v1/"
AUTH = {"Authorization": f"Bearer {os.environ['SCRAPINGBEE_API_KEY']}"}
PRICE = re.compile(r"\$\s?(\d{1,3}(?:,\d{3})+|\d+)(\.\d{2})?")  # $20.70
OTHERS = re.compile("|".join(p for b, (p, _) in BRANDS.items() if b != BRAND))


def money(price: float) -> str:
    return f"${price:.2f}".removesuffix(".00")


def stated_price(text: str) -> float | None:
    """First dollar amount after the brand name, on the same line and
    before any other tracked brand."""
    for hit in re.finditer(BRANDS[BRAND][0], text):
        window = text[hit.end():hit.end() + 300].split("\n")[0]
        window = OTHERS.split(window)[0]
        if match := PRICE.search(window):
            return float(match.group(1).replace(",", "") + (match.group(2) or ""))
    return None


def main() -> None:
    db = sqlite3.connect("visibility.db")
    wrong = {}  # cited page -> wrong prices it may carry
    for engine, text, urls in db.execute(
            "SELECT engine, text, urls FROM answers WHERE answered = 1"):
        price = stated_price(text)
        if price is None:
            continue
        ok = price in PRICE_LIST
        print(f"{engine:<12} {money(price)}" + ("" if ok else "  not on price list"))
        if not ok:
            for url in json.loads(urls):
                wrong.setdefault(url.split("#")[0], set()).add(price)

    print(f"\ncited pages that state a wrong {BRAND} price:")
    for url, prices in wrong.items():
        r = httpx.get(API, headers=AUTH, timeout=120, params={
            "url": url, "render_js": "false", "return_page_text": "true"})
        page = " ".join(r.text.split())
        if r.status_code == 200 and stated_price(page) in prices:
            print(f"  {money(stated_price(page))}  {url}")
    print(f"checked {len(wrong)} pages")


if __name__ == "__main__":
    main()
```

`PRICE_LIST` holds the US monthly prices from the [FreshBooks pricing page](https://www.freshbooks.com/pricing) for monthly and yearly billing, not the introductory discount for the first 4 months. For each wrong price, the script fetches the pages that the answer cited through the ScrapingBee [HTML API](https://www.scrapingbee.com/documentation/) and keeps the pages that state the same wrong price. The HTML API renders JavaScript in a headless browser by default, and the script disables rendering because most blog posts are server-rendered. Set `render_js` to `true` for a cited page that [renders its content client-side](https://www.scrapingbee.com/blog/scraping-javascript-rendered-web-pages/).

For your brand, set `BRAND`, `PRICE_LIST`, and the currency sign in the `PRICE` pattern first. Run it with `uv run --env-file .env claims.py`. For the FreshBooks example, it printed:

```python
ai_mode      $19  not on price list
gemini       $19  not on price list
ai_mode      $23
ai_mode      $23
chatgpt      $23
gemini       $19  not on price list
ai_mode      $23
ai_mode      $17  not on price list
ai_mode      $19  not on price list
ai_mode      $23
gemini       $19  not on price list
ai_mode      $23

cited pages that state a wrong FreshBooks price:
  $19  https://www.cloudbooksapp.com/blog/best-invoicing-software-for-freelancers
checked 14 pages
```

Half of the 12 answers that stated a FreshBooks price gave $17 or $19, below the $23 list price and below $20.70, the monthly price with yearly billing. The script then fetched the 14 pages that those 6 answers cited and found one with the same wrong price, a CloudBooks blog post that lists FreshBooks Lite at $19 a month. Of those 6 answers, 5 in Gemini and AI Mode cited that post. Citing the post didn't always mean repeating its price, because 3 other AI Mode answers cited the same post and still gave the correct $23.

The post still showed that price on November 19, 2026:

![The CloudBooks blog post 'Best Invoicing Software for Freelancers' on November 19, 2026, with the FreshBooks price line highlighted, which lists $19/month for Lite, $33/month for Plus, and $60/month for Premium.](https://www.scrapingbee.com/blog/how-to-build-an-llm-visibility-tracker-with-python/cloudbooks.png)


The tracker shows you which publisher to contact first. Engines refresh their answers on their own schedule. After the publisher fixes the page, compare the 2 weeks before the fix with the 2 weeks after it, and don't judge by the next day's run.

## What the FreshBooks example showed

These findings come from the FreshBooks example, run in the US in November 2026, with 24 answers from each of ChatGPT, Gemini, and AI Mode. Each finding shows what one part of the tracker can find for you.

**The engines mentioned FreshBooks but cited other sites**. On the 5 unbranded prompts, the 3 engines mentioned FreshBooks in 39 of their 60 answers but cited [freshbooks.com](http://freshbooks.com) only once. Getting cited is possible. The engines cited [zoho.com](http://zoho.com) in 20 of all 72 answers, although none of the prompts names Zoho. When you're mentioned but not cited, the answers mostly use pages that other people own, and the cited-domains list shows where you should try to appear.

**A competitor outside the brand list earned citations**. The database stores every cited URL, so a `sqlite3` query lists the pages each engine cited for one prompt, at no credit cost:

```python
sqlite3 visibility.db "SELECT engine, j.value, COUNT(*) FROM answers, json_each(urls) AS j
WHERE prompt = 'FreshBooks alternatives' AND j.value NOT LIKE '%logo%'
GROUP BY 1, 2 ORDER BY 3 DESC, 2 LIMIT 5"
```

The query printed the most cited pages for the prompt "FreshBooks alternatives" and, for each page, how many of the 4 answers per engine cited it:

```python
ai_mode|https://www.softwareadvice.com/accounting/freshbooks-profile/alternatives/|4
chatgpt|https://www.itechguides.com/best-quickbooks-online-alternatives-for-small-businesses-in-2026/|3
chatgpt|https://www.spotsaas.com/blog/best-quickbooks-alternatives-2026|3
ai_mode|https://zipbooks.com/free-freshbooks-alternative/|3
chatgpt|https://cpaadvisor.us/articles/freshbooks-alternatives/?utm_source=chatgpt.com|2
```

AI Mode cited a ZipBooks "FreshBooks alternative" page and mentioned ZipBooks in the same 3 answers, although ZipBooks wasn't on the tracked brand list. On November 19, 2026, that page still compared ZipBooks with FreshBooks plans named Sprout, Seedling, Evergreen, and Mighty Oak, while FreshBooks sold Lite, Plus, and Premium:

![The ZipBooks page 'ZipBooks vs. FreshBooks' on November 19, 2026, with its comparison table header highlighted, which names FreshBooks Sprout, Seedling, Evergreen, and Mighty Oak.](https://www.scrapingbee.com/blog/how-to-build-an-llm-visibility-tracker-with-python/zipbooks.png)


Read the cited pages for your most important prompts after each run, and add new competitors to `BRANDS`. The same query can also help explain a drop in your mention rate. Add a date filter such as `AND ts >= '2026-11-15'` to the `WHERE` line, and compare the pages that each engine cited before and after the rate fell.

**ChatGPT and AI Mode both showed ads**. Sponsored placements appeared in 16 of 24 ChatGPT answers, and 3 of the 4 answers to "FreshBooks alternatives" showed competitor ads. Counting mentions in ChatGPT's markdown without `strip_ads()` would have given QuickBooks 11 organic mentions instead of 8, because 3 answers mentioned QuickBooks only in an ad. Mercury isn't on the tracked brand list, but a search for its name finds it in 4 ChatGPT answers before `strip_ads()` and in none after it.

In AI Mode, all 4 answers to "best invoicing software for freelancers" showed ads from BILL. No engine mentioned BILL organically in any answer, so BILL appeared only as an ad. Read the ads list as a paid-media report on who buys ads for your prompts, much like a [Google Ads competitor analysis](https://www.scrapingbee.com/blog/google-ads-competitor-analysis/).

**Each engine cited different domains**. ChatGPT and Gemini cited 118 unique domains between them, and only 4 domains appeared in the answers of both engines. Gemini relied on the CloudBooks blog, which it cited in 16 of its 24 answers. A page that one engine cites often can be missing from another engine's answers, so check the cited domains for each engine separately.

**Which brands appeared depended more on the prompt than on the sample**. Across the 4 samples of a prompt, the full list of brands changed in 14 of 18 prompt and engine pairs, but single brands were far more stable. Out of 138 brand, prompt, and engine combinations, 106 had the brand in all 4 answers or in none. A second run half an hour later, with 1 answer per prompt and engine, agreed with 101 of those 106 cases. So repeating a prompt within the same hour adds little to what one answer already tells you.

**In ChatGPT, the country changed the competitor set**. With `country_code=de`, ChatGPT answered the English prompt "best invoicing software for freelancers" with 5 German tools, such as Lexware Office and sevdesk, and mentioned none of the 8 tracked brands. Gemini and AI Mode kept most of the tracked brands. That result comes from 1 sample per country, so treat it as a signal, and track each market in its own project folder with its own brand list.

## Size the prompt set before you report a change

A rate from 24 answers looks precise, but those answers came from 6 prompts, and the number of prompts is the effective sample size. FreshBooks' 60% mention rate in ChatGPT comes from 5 unbranded prompts, and its 95% confidence interval ranges from 20% to 100%. More samples of the same 5 prompts would barely narrow it.

The margin of error is roughly `1.96 * sqrt(p * (1 - p) / n)`, where `p` is the rate and `n` is the number of prompts. The formula counts each prompt once, so it fits when the samples of each prompt agree, as they did for most prompts here. At a 50% rate, about 96 prompts give you ±10 percentage points, and about 384 prompts give you ±5 percentage points. As a conservative rule, report a change only when it's larger than the margin of error.

So spend the budget on prompts, not on extra samples within one run. Citations can drift from day to day, so run each prompt once a day. Report over a rolling window of 2 to 4 weeks by passing its dates to `report.py`. Keep the prompt set fixed once you start reporting, because adding or rewording prompts makes the windows no longer comparable.

Engines also update their models, often without notice, and a new model can shift many rates at once. When the rates of most brands shift together in one engine, check for a model update before you conclude that your content caused the shift.

### Seed the prompt set from Google questions

Writing 96 good prompts by hand takes time, so seed the set with real Google queries. The ScrapingBee Google Search API returns People Also Ask questions and [related searches](https://www.scrapingbee.com/scrapers/google-related-searches-api/), and 1 request per seed keyword gives you phrasings that buyers type. Save this as `seed_prompts.py`:

```python
"""Collect real Google questions for seed topics, to use as tracker
prompts. One Google Search API request per topic."""

import os

import httpx

SEEDS = ["invoicing software for freelancers", "freshbooks"]
headers = {"Authorization": f"Bearer {os.environ['SCRAPINGBEE_API_KEY']}"}

for seed in SEEDS:
    r = httpx.get("https://app.scrapingbee.com/api/v1/google",
                  params={"search": seed, "country_code": "us"},
                  headers=headers, timeout=120)
    serp = r.json()
    print(f"# {seed}")
    for question in serp.get("questions") or []:
        print(question["text"])
    for related in serp.get("related_searches") or []:
        print(related["query"])
```

Run it with `uv run --env-file .env seed_prompts.py`. The first lines of output for the seed keyword "freshbooks" were:

```python
# freshbooks
What are the downsides of FreshBooks?
Is FreshBooks as good as QuickBooks?
What is the use of FreshBooks?
How much do FreshBooks cost monthly?
```

Copy the questions that a buyer would ask into `prompts.txt`. Keep questions such as "What are the downsides of FreshBooks?" too, because the answers show how an engine describes your weak points. The full output also includes navigational queries such as "FreshBooks login" that a buyer doesn't ask an AI assistant, so exclude those. For your brand, put your own topics in `SEEDS`, and change `country_code` for another market.

People Also Ask shows what people type into Google. Add the questions that your sales team hears from buyers, and check the set for gaps by funnel stage, from early problem questions to vendor comparisons. A comparison prompt such as "FreshBooks vs QuickBooks for a design studio" names both brands. The report leaves both brands out of the mention rate for that prompt, so read the answers to that prompt for what they say about each brand.

## Run the tracker daily on a fixed credit budget

Each run prints its total credits on its last line, so you can size a plan from your own usage data. Divide that total by the number of prompts times the number of samples, which gives the cost of sending one prompt to every engine once. Multiply that cost by your number of prompts and then by 30 days, and pick a plan on the [ScrapingBee pricing page](https://www.scrapingbee.com/pricing/) whose monthly API credits are enough for that monthly figure.

Size the plan for about 96 prompts, which give a margin of error of ±10 percentage points. If `ENGINES` lists only the engines that your buyers use, the same plan is enough for more prompts.

Every request also appears with its cost under [**Logs & Analytics**](https://help.scrapingbee.com/en/article/logs-and-analytics-1uebc0w/) in the ScrapingBee dashboard, where you can compare the tracker's spend with your account's total usage. Filter by a word from your prompts to see each prompt's **Total Requests** and **Total Cost** by **API**:

![ScrapingBee Logs & Analytics filtered to the invoicing prompts. Each prompt appears once per API (GOOGLE, CHATGPT_API, GEMINI_API) with its status codes, requests, and total cost, and the Total Cost column is highlighted.](https://www.scrapingbee.com/blog/how-to-build-an-llm-visibility-tracker-with-python/logs-analytics.png)


To schedule a daily run, find the absolute path of `uv` with `which uv`, then add a crontab entry like this with `crontab -e`:

`0 6 * * * cd "$HOME/llm-visibility" && /opt/homebrew/bin/uv run --env-file .env tracker.py 1 >> runs.log 2>&1`

Replace `/opt/homebrew/bin/uv` with the path that `which uv` printed, and `$HOME/llm-visibility` with your project directory. Cron runs jobs with a minimal environment and `PATH`, so the entry uses absolute paths and reads the key from `.env`. On Windows, schedule the same `uv run` command in Task Scheduler, with the project directory as the start folder.

In a scheduled GitHub Actions workflow, pass the key as a repository secret. Each job on a [GitHub-hosted runner starts on a new virtual machine](https://docs.github.com/en/actions/concepts/runners/github-hosted-runners), so restore `visibility.db` from the Actions cache at the start of each run and save it under a new cache key at the end. GitHub [removes cache entries](https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching) that nothing has read for 7 days, so also copy the database to persistent storage, such as object storage, after each run. At 96 prompts a day, the database grows by about 8 MB a day, or about 3 GB a year.

## Final thoughts

An LLM visibility tracker samples AI answers, and how much you can trust its rates depends on the number of prompts, not the number of answers. Report mentions, citations, and ads separately, because an engine can mention your brand without citing your pages, and ChatGPT can put ads in the answer. The stored answers also let you check the prices that engines state and trace a wrong price to the page they cited. Plan for about 96 prompts before you report a change, and use your analytics to confirm any effect on traffic. Create a [free ScrapingBee account](https://dashboard.scrapingbee.com/account/register) with no credit card, add your brand to the scripts, and run 1 sample to see which domains each engine cites.

## FAQ

### Can AI searches be tracked?

Yes, if you send a fixed prompt set to each AI assistant on a schedule and store every answer. Then count how often each brand is mentioned and how often each domain is cited. Report those counts as rates with confidence intervals. The ScrapingBee ChatGPT, Gemini, and Google Search APIs return these answers as JSON.

### How do you track brand mentions in ChatGPT?

Send your buyer prompts through the ScrapingBee ChatGPT API with web search enabled, repeat them on a schedule, and search the answer text for each brand name. Strip sponsored blocks first, because ChatGPT can put ads in the answer. In a 24-answer test, counting the ads gave QuickBooks 11 mentions instead of 8.

### How do you track Google AI Overviews?

Request Google results for each query through the ScrapingBee Google Search API with AI Overview expansion enabled. Then read the answer text and source links from the returned AI Overview data. Google shows an AI Overview only for some queries, so record "no AI Overview" and "brand not mentioned" as separate results.

### Why should I track AI brand visibility?

AI assistants answer buying questions directly, but traditional rank tracking reports SERP positions and misses what the answers say. A tracker shows whether you're mentioned, which pages engines cite, and who buys ads for your prompts. In a test, engines mentioned a brand in 39 of 60 answers but cited its site once.

### Is there a free LLM visibility tracker?

Yes, you can build a basic one with 2 Python scripts (a collector and a report) and add a price check later. You can start it on the free API credits that come with a new ScrapingBee account. The tracker prints the credits that each request bills, so you can see how many runs the free credits allow.
