Review Sentiment Analysis With an LLM: A Working Pipeline

Scrape real customer reviews with Magpie, then run review sentiment analysis with an LLM in a Python script. Real commands, real output, real cost.

MMotherlode Lab10 min read
Magpie title card: Review Sentiment Analysis With an LLM: A Working Pipeline

The tools that sell review sentiment analysis are bundling two jobs. The first, collecting reviews off the web, is plumbing; the second, deciding what “the package was immediately returned to the vendor” means for your product, is judgment. The bundles charge monthly for both, and most people only need the second one on their own terms.

This guide runs both halves locally. Magpie (a free CLI scraper) fetches and cleans the reviews; a hundred-line Python script and any OpenAI-compatible LLM score them. I ran the pipeline today against Trustpilot reviews of DPD UK: 60 reviews fetched, 24 survived dedupe, and scoring all 24 cost $0.001. Every command and number below is from that run.

What Magpie does here, and what it doesn’t

Magpie gets and cleans the data. Its trustpilot vertical reads the structured JSON-LD that Trustpilot embeds in review pages and returns typed records: author, body, date, star rating. No LLM call, no API key, no cost.

Magpie does not do sentiment analysis. There is no sentiment button. It doesn’t dedupe, aggregate, chart, or alert on themes. If a scraper vendor implies otherwise, read the fine print: the analysis is a different product tier or a different product entirely.

I think the split is right. Scoring logic is product judgment: your theme taxonomy, your mixed-sentiment rules, your tolerance for false positives. That belongs in code you own, where you can test it and rerun it when you change your mind. This page’s job is to hand you both halves wired together.

Before you start

  • Magpie CLI on your PATH (the core is a single static Go binary; AGPL-3.0-or-later or a commercial licence)
  • Python 3.10+ (the script uses only the standard library)
  • An API key for any OpenAI-compatible endpoint: OpenAI, OpenRouter, or local Ollama all work

Step 1: Pull reviews from a Trustpilot page (zero LLM cost)

Pick the business whose reviews you want. Trustpilot review pages live at trustpilot.com/review/<domain>. One command:

magpie scrape "https://www.trustpilot.com/review/dpd.co.uk" \
  --vertical auto --format json > tp1.json

What you should see: exit code 0, and a JSON array whose record holds the review list. Abridged from my run:

{
  "vertical": "trustpilot",
  "record": {
    "name": "Trustpilot",
    "reviews": [
      {
        "author": "Mrs White",
        "body": "Efficient and friendly, delivered exactly within the 1hr time slot",
        "date": "2026-10-17T13:27:32.000Z",
        "rating": 5
      }
    ]
  }
}

Twenty reviews per page, every one with the four fields the analysis needs. The vertical reads server-rendered JSON-LD, so nothing renders in a browser and the call is free.

When it doesn’t work: not every review site cooperates, and the famous ones are the worst. In my testing, Yelp, G2, TripAdvisor, and Amazon’s review text all sit behind bot walls that Magpie correctly refuses to fight; it detects challenges and reports them, by design. If a page has no vertical, --page-format markdown still returns cleaned text you can read, but you lose the typed fields and the analysis gets harder.

Step 2: Paginate, merge, dedupe

Reviews arrive in pages of 20, and new ones land while you’re paging. Fetch a few pages with a pause between calls:

for p in 2 3; do
  magpie scrape "https://www.trustpilot.com/review/dpd.co.uk?page=$p" \
    --vertical auto --format json > "tp$p.json"
  sleep 3
done

Here’s the part the bundles never mention: those 60 reviews contained only 24 unique ones. The rest were duplicates, because live pagination shifts under you: a review that sat on page 2 when you fetched it has moved to page 1 by the time you get there. Skip the dedupe and your “average sentiment” double-counts whatever happened to be on top that hour.

The merge in the script below dedupes on (author, body). It dropped 36 of my 60 rows. This is exactly where the scraper’s job ends and yours begins. No scraping tool will make that call for you, and it’s the difference between data and noise.

Step 3: Score the reviews with an LLM

This is the whole analysis script. Save it as analyze.py:

#!/usr/bin/env python3
"""Score scraped reviews with an LLM.

Input : JSON files written by `magpie scrape --vertical trustpilot --format json`
Output: reviews-scored.csv + a printed aggregate

Env: LLM_BASE_URL (default https://openrouter.ai/api/v1),
     LLM_API_KEY, LLM_MODEL (default openai/gpt-4o-mini).
Stdlib only.
"""
import csv, json, os, sys, time, urllib.request

BASE = os.environ.get("LLM_BASE_URL", "https://openrouter.ai/api/v1")
KEY = os.environ["LLM_API_KEY"]
MODEL = os.environ.get("LLM_MODEL", "openai/gpt-4o-mini")

def llm(messages, retries=3):
    body = json.dumps({
        "model": MODEL,
        "messages": messages,
        "response_format": {"type": "json_object"},
        "max_tokens": 1500,
    }).encode()
    req = urllib.request.Request(
        BASE + "/chat/completions", data=body,
        headers={"Authorization": f"Bearer {KEY}",
                 "Content-Type": "application/json"})
    for attempt in range(retries):
        try:
            with urllib.request.urlopen(req, timeout=90) as r:
                return json.loads(r.read())["choices"][0]["message"]["content"]
        except Exception as e:
            if attempt == retries - 1:
                raise
            print(f"  retry {attempt+1} after error: {e}", file=sys.stderr)
            time.sleep(5 * (attempt + 1))

def load_reviews(paths):
    """Merge magpie vertical records; dedupe on (author, body)."""
    seen, dupes = {}, 0
    for path in paths:
        data = json.load(open(path))
        for rec in (data if isinstance(data, list) else [data]):
            for rev in rec.get("record", {}).get("reviews", []):
                k = (rev["author"].strip(), rev["body"].strip())
                if k in seen:
                    dupes += 1
                else:
                    seen[k] = {"text": rev["body"].strip(),
                               "rating": rev.get("rating"),
                               "date": rev.get("date", "")[:10],
                               "author": rev["author"].strip()}
    return list(seen.values()), dupes

PROMPT = """You are scoring customer reviews for a delivery courier.
For each review, decide:
- "sentiment": "positive", "negative", or "mixed" (genuine praise AND complaint)
- "themes": 1-3 concrete topics from: delivery speed, parcel condition,
  driver behaviour, communication, price, app/website, other
- "quote": the shortest span of the review that justifies the sentiment

Return JSON: {"results": [{"id": <int>, "sentiment": ..., "themes": [...],
"quote": ...}]}
Reviews:
__REVIEWS__"""

def main():
    reviews, dupes = load_reviews(sys.argv[1:])
    print(f"loaded {len(reviews)} unique reviews ({dupes} duplicates dropped)")
    results = {}
    for i in range(0, len(reviews), 15):
        chunk = reviews[i:i + 15]
        payload = [{"id": i + j, "text": r["text"], "stars": r["rating"]}
                   for j, r in enumerate(chunk)]
        content = llm([{"role": "user",
                        "content": PROMPT.replace("__REVIEWS__",
                                                  json.dumps(payload))}])
        for item in json.loads(content)["results"]:
            results[item["id"]] = item
        print(f"  scored {min(i+15, len(reviews))}/{len(reviews)}")

    with open("reviews-scored.csv", "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["date", "stars", "sentiment", "themes", "quote", "text"])
        for i, r in enumerate(reviews):
            s = results[i]
            w.writerow([r["date"], r["rating"], s["sentiment"],
                        "; ".join(s["themes"]), s["quote"], r["text"]])

    from collections import Counter
    senti = Counter(results[i]["sentiment"] for i in range(len(reviews)))
    themes = Counter(t for i in range(len(reviews))
                     for t in results[i]["themes"])
    print("\nsentiment:", dict(senti))
    print("themes:   ", themes.most_common())
    print("wrote reviews-scored.csv")

if __name__ == "__main__":
    main()

Three design choices worth explaining, because you’ll want to change them:

Batching at 15. One API call per review triples your request count for no quality gain; one call for all 300 makes the model lazy at the end of the list. Fifteen per call kept the JSON valid on every chunk in my run.

response_format: json_object. Structured output or nothing. If your endpoint doesn’t support it, parse defensively, but never regex an LLM.

The justifying quote. Forcing the model to name the exact span that drove its verdict makes spot-checking possible and lazy classifications rare. When it tagged a review negative with the quote “the package was immediately returned to the vendor”, I could verify the call in two seconds.

Swap providers with environment variables; nothing else changes:

export LLM_API_KEY="sk-..."          # or OPENROUTER key, or Ollama needs no key
export LLM_MODEL="openai/gpt-4o-mini"
python3 analyze.py tp1.json tp2.json tp3.json

For a fully local run, point LLM_BASE_URL at Ollama (http://localhost:11434/v1) and pick a small instruct model. It’s slower and rougher on mixed sentiment, but the data never leaves your machine.

Step 4: Read the output like a skeptic

Real output from my run:

loaded 24 unique reviews (36 duplicates dropped)
  scored 15/24
  scored 24/24

sentiment: {'positive': 22, 'negative': 2}
themes:    [('delivery speed', 17), ('driver behaviour', 10),
            ('parcel condition', 3), ('communication', 3), ('service', 1)]
wrote reviews-scored.csv

The CSV is the deliverable: one row per review, stars beside sentiment, themes beside quotes. Abridged:

stars sentiment themes quote
5 positive driver behaviour; delivery speed “Freddies brill, always polite and on time”
1 negative other “the package was immediately returned to the vendor”
1 negative communication “Bunch of liars”

Now the honest part, three things my run got wrong or oddly right:

  1. The model invented a theme. “service” appears in the theme counts though my prompt listed seven allowed topics and “service” wasn’t one. If your taxonomy feeds a dashboard, validate theme values in code and fold strays into other.
  2. Vague reviews came back with empty themes. “Great. Thanks.” scored positive with an empty theme list; correct, and better than a keyword tagger that would have invented a label.
  3. Short praise and short rage both classify cleanly; middling text doesn’t. My 24 reviews had no genuinely mixed one, so the “mixed” label went untested. Before you trust this on your own data, cross-tab stars against sentiment (one line in pandas) and read every row where a 5-star review scored anything but positive. That’s where the sarcasm lives.

Step 5: What review sentiment analysis costs, and how to keep it running

The scoring run’s real numbers: one 15-review chunk cost 570 prompt tokens plus 656 completion tokens — $0.00048 at gpt-4o-mini’s list price of $0.15 and $0.60 per million tokens. Two chunks, so 24 reviews cost about a tenth of a cent. A 10,000-review back catalog comes to about $0.30 at this review length. The scraping side is free; the full cost model for LLM-assisted scraping lives in our per-page cost breakdown.

To keep the pipeline warm, schedule it. A cron entry running the loop nightly gives you a scored CSV per day; the diff between yesterday’s and today’s files is your alert. For change-driven triggering instead of schedules, Magpie’s watch mode fires a webhook when a review page changes; our review-monitoring guide covers that setup.

Two variants worth knowing:

  • App Store reviews come from three places: the 8 reviews embedded in each app page (a curated, mostly five-star showcase), Apple’s legacy 500-review feed (disallowed in itunes.apple.com/robots.txt), and the App Store Connect API for apps you own. Magpie’s RSS vertical can’t feed this script: it drops each entry’s stars, text, and author. Reshape whichever source you use into the script’s review shape (author, body, date, rating) and the scoring half runs unchanged. The App Store review scraper guide measures all three.
  • Any review page without a vertical can still feed an LLM through schema-driven extraction, which trades typed fields for flexibility at a per-page token cost. That’s the AI web scraper route.

One line on legality: this pipeline reads public pages with a 3-second pause between them. A single magpie scrape doesn’t consult robots.txt, so check a site’s rules before pointing the loop at it. Don’t republish review text or reviewer names: score them, aggregate them, quote a line or two under fair use for internal analysis. The fuller picture is in our piece on scraping for AI training.

FAQ

Can’t I just paste reviews into ChatGPT? For 20 reviews, yes. For ongoing work, no: pagination walls most review sites past page one, pasted context shrinks every session, and you can’t rerun a chat prompt on next week’s reviews. A script plus a recorded prompt is repeatable; a chat tab isn’t.

Do I need an LLM, or is VADER enough? VADER (a rule-based sentiment lexicon) is free and instant, and it’s fine for a rough positive/negative trend. It can’t handle mixed sentiment, domain slang, or “great, another delayed parcel”. If your counts drive decisions, spend the tenth of a cent.

Is scraping Trustpilot allowed? The public review pages are server-rendered and robots.txt-readable, and the pipeline above stays polite: no logins, no protection bypass, throttled requests. Republishing reviews is a different question than reading them: score internally, don’t republish.

Which review sites work with this pipeline? Trustpilot works via the vertical shown here. App Store reviews work from the app page (a curated handful) or, for your own app, the App Store Connect API. Yelp, G2, TripAdvisor, and Amazon’s review text are bot-walled as of October 2026. Google reviews have no public page structure to read. Anything with server-rendered reviews, or a feed its robots.txt allows, is a candidate.

How many reviews fit in one LLM call? Fifteen worked in my run with themes and quotes, staying under 1,500 output tokens. Longer reviews mean fewer per call. If you only need sentiment without themes, 30 or more will fit.


Run it against your own product’s review page tonight. The CSV lands in your working directory, the aggregate prints in seconds, and if the counts surprise you, you’ll want to know before your next pricing meeting — not after.

Stop renting credits.

One flat price, your machine, your keys.

Download free for Windows, macOS and Linux

Windows · macOS · Linux $49/mo flat, cancel anytime