LLM brand-mention tracking with llm_responses

Ask ChatGPT, Claude and Perplexity models the prompts your buyers ask, then measure how often your brand is mentioned and which sources are cited.
Open as Markdown

This recipe sends a set of prompts to three answer engines through llm_responses with web search on, then counts brand mentions, competitor mentions and cited domains.

Cost: each answer is a base fee ($0.00054 live, $0.00018 in the standard queue) plus the model's tokens and web searches at the provider's list price. The token part is returned as money_spent; the task's cost is the total. 10 prompts × 3 engines is 30 answers, so $0.0162 in base fees plus tokens. A failed or empty answer costs $0.

You need: Python 3.9+, requests, DATAFORGAIO_API_KEY.

brand_mentions.py
import collections
import os
import re
from urllib.parse import urlsplit
 
import requests
 
BASE = "https://api.dataforgaio.com/v1"
AUTH = ("api", os.environ["DATAFORGAIO_API_KEY"])
 
BRAND = "Acme Trail"
COMPETITORS = ["Summit Gear", "Ridgeline"]
ENGINES = ["chat_gpt", "claude", "perplexity"]
PROMPTS = [
    "What are the best trail running shoes for muddy terrain?",
    "Which brands make the most durable hiking boots?",
    "Recommend a lightweight running vest for ultramarathons.",
]
 
 
def ask(engine, prompts):
    tasks = [{
        "user_prompt": p,
        "web_search": True,
        "web_search_country_iso_code": "US",
        "max_output_tokens": 1024,
        "max_cost": 0.05,           # never more than 5 cents per answer
        "tag": p[:255],
    } for p in prompts]
    body = requests.post(f"{BASE}/ai/{engine}/llm_responses/live", auth=AUTH, json=tasks, timeout=600).json()
    if body["status_code"] != 20000:
        raise SystemExit(f'{body["status_code"]}: {body["status_message"]}')
    return body["tasks"]
 
 
def mentioned(name, text):
    return re.search(rf"\b{re.escape(name)}\b", text, re.IGNORECASE) is not None
 
 
stats = collections.defaultdict(collections.Counter)
cited = collections.Counter()
spend = 0.0
 
for engine in ENGINES:
    for task in ask(engine, PROMPTS):
        spend += task["cost"]
        if task["status_code"] != 20000:
            print(engine, "failed:", task["status_message"])
            continue
        result = task["result"][0]
        sections = [s for item in result["items"] for s in item.get("sections") or []]
        text = "\n".join(s.get("text") or "" for s in sections)
        stats[engine]["answers"] += 1
        stats[engine]["brand"] += mentioned(BRAND, text)
        for c in COMPETITORS:
            stats[engine][c] += mentioned(c, text)
        for s in sections:
            for a in s.get("annotations") or []:
                if a.get("url"):
                    cited[urlsplit(a["url"]).netloc.removeprefix("www.")] += 1
 
for engine, s in stats.items():
    n = s["answers"] or 1
    others = ", ".join(f"{c} {s[c] / n:.0%}" for c in COMPETITORS)
    print(f"{engine:11} {BRAND} {s['brand'] / n:.0%} | {others}")
 
print("\nMost cited domains:")
for domain, count in cited.most_common(10):
    print(f"  {count:3}  {domain}")
print(f"\nTotal cost: ${spend:.4f}")

What's in each answer

FieldMeaning
result[0].model_nameThe model that answered. Choose one with model_name; GET /v1/ai/<engine>/llm_responses/models lists them (free).
result[0].items[].sections[].textThe answer text.
result[0].items[].sections[].annotations[]Citations with title, url and, where the engine provides them, start_index, end_index and text.
result[0].fan_out_queriesThe web searches the model ran.
result[0].search_resultsThe results it saw.
result[0].input_tokens, output_tokens, reasoning_tokens, money_spentUsage and its token cost.

Tracking over time

  • Queue it to pay less. For a daily run, post to /v1/ai/chat_gpt/llm_responses/task_post and /v1/ai/claude/llm_responses/task_post and collect with tasks_ready and task_get/{id}. Base fees drop to $0.00018 per answer. Queued answers go through the providers' batch processing (Beta) and can take hours. Perplexity is live only.
  • Answers aren't cached. Every call is a fresh sample, so day-to-day changes are real variation. Run each prompt a few times if you need stable rates.
  • Limits. user_prompt and system_message are up to 500 characters, max_output_tokens up to 4,096, and message_chain up to 10 alternating user / ai messages.
  • Set max_cost. It caps what each answer is billed, tokens included, and it's also what we reserve from your balance per task. Without it, we reserve the base fee plus a conservative estimate of the tokens the task could use, so a low balance may return 40210 even if the answers would cost less.

If you'd rather not build this yourself, the dashboard's AI visibility trackers run prompts on a schedule, and GET /v1/visibility/trackers/{id}/summary returns mention rates, citation rates, share of voice and sentiment.

Note:

Answers returned by llm_responses are added to our anonymized AI-answer dataset unless your organization opts out. See Data retention.

Reference: POSTChatGPT LLM Responses: Live, POSTClaude LLM Responses: Live, POSTPerplexity LLM Responses: Live.