Blog / AI agents

Summarise Restaurant Reviews with an AI Agent

An AI review summarizer is only useful if you can check it. This tutorial builds one in Python for a restaurant: it pulls the place's Google Maps and Yelp reviews, normalises them into one list with source-prefixed IDs, asks Claude for themes in a fixed JSON schema where every theme names its review IDs and quotes them word for word, then checks each quote against the cited reviews in code. A summary costs 3 credits per place.

What does the agent do?

It turns a pile of reviews into a short list of themes you can audit. Code does the parts that need to be exact: fetching, normalising, giving each review an ID, and checking the output. The model does the part that needs judgment: grouping reviews into themes and choosing quotes. That split is what makes the summary checkable.

  1. Fetch Google Maps reviews for the place's business_id and Yelp reviews for its business alias.
  2. Normalise both into {id, source, rating, date, language, text}, with no author fields.
  3. Send the list to Claude with a JSON schema: themes, sentiment, review IDs and verbatim quotes.
  4. Check every theme: do its IDs exist, and does each quote appear in the reviews it cites?
  5. Print the themes and flag any that fail the check as unsupported.

You need Python 3.10 or later, a Perceptlayer API key and an Anthropic API key. Get a free API key; verified accounts get 100 free credits on signup. Install pip install anthropic requests and export PERCEPTLAYER_API_KEY and ANTHROPIC_API_KEY.

Why not use the official review APIs?

Because they return only a handful of reviews per place, which is too few to find themes. Google's Places API returns at most five reviews for a place, sorted by relevance (Google Places API, 2026). Yelp's Places API returns up to three review excerpts on its Enhanced plan and up to seven on Premium (Yelp Places API plans, 2026).

If you're showing a couple of reviews next to a map pin, those APIs are the right fit: they're first-party and their display terms are clear. For a summary across dozens of reviews, you need more of them. The Google Maps reviews endpoint takes page, pages, limit, sort and search, and the Yelp reviews endpoint takes sort (relevance, newest, oldest, highest, lowest, elite), rating and an after cursor. Data is collected from publicly available sources and returned as found at the time of the call.

How do you fetch and normalise the reviews?

Call each endpoint once and map its fields onto one shape. These are the exact requests behind the recordings used here; the Google business_id comes from a Google Maps search, and the Yelp alias is the last part of a Yelp business URL:

curl "https://api.perceptlayer.com/v1/google-maps/reviews?business_id=0x60188b88b7d8f7ab%3A0x2133080e9923eaac" \
  -H "X-API-Key: $API_KEY"

curl "https://api.perceptlayer.com/v1/yelp/reviews?business=gary-danko-san-francisco&sort=newest" \
  -H "X-API-Key: $API_KEY"

The two recordings are for two different places, a Tokyo café on Google Maps and a San Francisco restaurant on Yelp, so they show each source's shape rather than one place's reviews. Here's one Yelp review, trimmed with …, with the author object cut:

{
  "success": true,
  "data": {
    "business": { "alias": "gary-danko-san-francisco", "name": "Gary Danko", … },
    "review_count": 6149,
    "reviews": [
      {
        "id": "4qYbbI9JbtCDUOtQRcJfDA",
        "rating": 5,
        "text": "The staff is top notch.\nI really like the way their menu works, where you can pick any 3, 4, or 5 courses, fixed price.  The cheese cart is ah-mazing, and really, only one person at the table needs to order it, for sharing. (depending on yo…",
        "language": "en",
        "created_at": "2026-10-22T21:21:22Z",
        …
      },
      …
    ],
    "has_more": true,
    "next_after": "eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoib2Zmc2V0Iiwib2Zmc2V0Ijo5fQ"
  }
}

Google Maps reviews come in items, with review_id, rating, a millisecond timestamp, and review_text and review_language as lists. Both sources also carry author names, profile links and photos; the normaliser keeps none of them.

"""Summarise one place's Google Maps and Yelp reviews, with every theme tied to review IDs."""
import datetime
import json
import os
import sys

import anthropic
import requests

API = "https://api.perceptlayer.com/v1"
HEADERS = {"X-API-Key": os.environ["PERCEPTLAYER_API_KEY"]}
MODEL = os.environ.get("CLAUDE_MODEL", "claude-opus-5-5")


def get(path, **params):
    r = requests.get(f"{API}/{path}", headers=HEADERS, params=params, timeout=90)
    r.raise_for_status()
    return r.json()


def google_reviews(business_id):
    body = get("google-maps/reviews", business_id=business_id)
    for r in body.get("items", []):
        yield {
            "id": "g:" + r["review_id"],
            "source": "google",
            "rating": r["rating"],
            "date": datetime.datetime.fromtimestamp(r["timestamp"] / 1000, datetime.timezone.utc).date().isoformat(),
            "language": (r.get("review_language") or [None])[0],
            "text": " ".join(r.get("review_text") or []),
        }


def yelp_reviews(business):
    body = get("yelp/reviews", business=business, sort="newest")
    for r in body["data"].get("reviews", []):
        yield {
            "id": "y:" + r["id"],
            "source": "yelp",
            "rating": r["rating"],
            "date": r["created_at"][:10],
            "language": r.get("language"),
            "text": r.get("text", ""),
        }

Run on the two recordings, with requests.get mocked, these produced six normalised reviews, three per source, 2,307 characters of JSON in all. Every one was rated 5, and every text ended in ….

Why do the excerpts and the ratings matter?

Because they decide what a summary can honestly say. The texts in both recordings are cut short with an ellipsis, so a theme like "the cheese cart is popular" can be supported, but anything about how a review ends can't. The system prompt below tells the model so. If you need full texts, check whether the single-review endpoint, /v1/google-maps/review, returns more; we haven't recorded it.

The ratings matter more. Six 5-star reviews will produce a glowing summary, but that reflects the sample: recent reviews on a well-rated place. Balance it on purpose. Yelp's sort=lowest fetches the critical end, and a second call costs 1 more credit. Report the rating mix next to the themes, so a reader knows what the summary is based on. Our guide to review data for sentiment analysis goes further into sampling.

How do you make the model cite its sources?

Give it IDs and require them in a schema. Structured outputs (output_config with a JSON schema) make the response valid JSON in a fixed shape (Anthropic, structured outputs, 2026). Each theme has a sentiment, the IDs of the reviews behind it, and quotes copied from those reviews. The prompt forbids guessing beyond the excerpts.

SCHEMA = {
    "type": "object",
    "properties": {
        "themes": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "theme": {"type": "string"},
                    "sentiment": {"type": "string", "enum": ["positive", "negative", "mixed"]},
                    "review_ids": {"type": "array", "items": {"type": "string"}},
                    "quotes": {"type": "array", "items": {"type": "string"}},
                },
                "required": ["theme", "sentiment", "review_ids", "quotes"],
                "additionalProperties": False,
            },
        }
    },
    "required": ["themes"],
    "additionalProperties": False,
}

SYSTEM = """You summarise customer reviews of one place into themes.
Every theme must list the IDs of the reviews that support it, and at least one
quote copied word for word from one of those reviews. Use only the reviews given.
Review texts may be cut short with an ellipsis; don't guess how they end."""


def summarise(reviews):
    client = anthropic.Anthropic()
    response = client.messages.create(
        model=MODEL,
        max_tokens=16000,
        system=SYSTEM,
        messages=[{"role": "user", "content": json.dumps(reviews, ensure_ascii=False)}],
        output_config={"format": {"type": "json_schema", "schema": SCHEMA}},
    )
    if response.stop_reason == "refusal":
        raise RuntimeError("the model declined")
    return json.loads(next(b.text for b in response.content if b.type == "text"))

How do you flag claims the reviews don't support?

Check every theme in code. A theme fails if it cites an ID that isn't in the input, if it cites none, or if a quote doesn't appear in the text of the reviews it cites. The check is a plain substring match after trimming quote marks and ellipses: crude, but it catches the two failures that matter, invented quotes and quotes attributed to the wrong review.

def check(summary, reviews):
    """Flag themes whose IDs don't exist or whose quotes aren't in the cited reviews."""
    by_id = {r["id"]: r for r in reviews}
    problems = []
    for t in summary["themes"]:
        missing = [i for i in t["review_ids"] if i not in by_id]
        if missing:
            problems.append((t["theme"], f"unknown review IDs {missing}"))
        cited = " ".join(by_id[i]["text"] for i in t["review_ids"] if i in by_id)
        for q in t["quotes"]:
            if q.strip(" .…\"'") not in cited:
                problems.append((t["theme"], f"quote not found in cited reviews: {q!r}"))
        if not t["review_ids"]:
            problems.append((t["theme"], "no supporting reviews"))
    return problems


if __name__ == "__main__":
    google_id, yelp_alias = sys.argv[1], sys.argv[2]
    reviews = list(google_reviews(google_id)) + list(yelp_reviews(yelp_alias))
    summary = summarise(reviews)
    for t in summary["themes"]:
        print(f'- {t["theme"]} ({t["sentiment"]}, {len(t["review_ids"])} reviews): "{t["quotes"][0]}"')
    for theme, problem in check(summary, reviews):
        print(f"UNSUPPORTED  {theme}: {problem}")

We tested check on the six recorded reviews with three themes we wrote as test input, not model output. A theme quoting "The cheese cart is ah-mazing" and citing the Yelp review it came from passed. The same quote cited against a Google review failed with "quote not found in cited reviews". A theme citing y:doesnotexist failed twice: unknown ID, and its quote not found. Run it with a Google business_id and a Yelp alias for the same restaurant: python summarise.py <business_id> <yelp-alias>.

What does a summary cost?

Each call costs 1 credit on success, and failed calls cost nothing. One Google Maps reviews call and two Yelp calls, newest and lowest, make 3 credits a place; add 1 credit per extra page. The Claude call is billed separately by Anthropic. The credits docs explain billing.

Job Calls Credits
One place, 3 calls 3 3
One place, plus 2 more pages from each source 7 7
100 places, 3 calls each 300 300
100 places, re-summarised monthly for a year 3,600 3,600

Worked example: summarising 100 restaurants monthly at 3 calls each is 300 credits a month. The 100 free credits on signup cover a first run of 33 restaurants, and the monthly job needs a pack. A year of it, 3,600 credits, fits in a Starter pack of 10,000 credits, and purchased credits last 12 months. See pricing for what credits cost. For paging and rate limits, see the Yelp reviews API guide, the Google Maps reviews guide and the rate limits docs.

What should you watch for in production?

Three things, all about the reviews rather than the model. First, attribution: if you display review text, the source's terms apply; Google, for example, asks developers to show the author's name next to Google reviews they display through its API. This agent displays themes and short quotes without names, so decide what your use needs. Second, language: Google returns review_language, so filter or translate before summarising a mixed set. Third, recency: store each review's date and summarise a fixed window.

To run it, get a free API key and look up a restaurant in the playground on the Google Maps API page and the Yelp API page. The AI agents docs cover the same endpoints over MCP, and the errors docs list the codes a fetch can return.

APIs in this post

Frequently asked questions

What is an AI review summarizer?

A program that collects reviews of a place or product and has a language model group them into themes, such as service, value or a signature dish. This one pulls Google Maps and Yelp reviews as JSON, requires the model to cite review IDs and quote them, and checks every quote against the cited reviews before printing the result.

How do I stop the summary from making things up?

Give each review an ID, require IDs and verbatim quotes for every theme with a JSON schema, and check the quotes in code. A substring check catches quotes that don't exist and quotes attributed to the wrong review. Anything that fails is printed as unsupported rather than silently shown.

Why are all the reviews positive?

Because of the sample, not the place. Recent reviews of a well-rated restaurant skew high: all six recorded reviews used here are 5-star. Pull Yelp's sort=lowest as well, report the rating mix next to the themes, and summarise positive and negative reviews separately if you need both sides.

How much does it cost to summarise a restaurant's reviews?

3 credits per place: one Google Maps reviews call and two Yelp reviews calls, at 1 credit per successful call. Extra pages cost 1 credit each, and failed calls cost nothing. Every account gets 100 free credits after verifying an email address. Model tokens are billed separately by your model provider.

Does the agent store reviewers' names?

No. The normaliser keeps each review's ID, source, rating, date, language and text, and drops author names, profile links and photos before anything reaches the model. If you later display reviews to users, check each source's attribution terms, which may require showing the author's name.

  1. AI Agent Tools: What an Agent Needs for Web Data

    An agent tool is a name, a description, an input schema and a result. How search, lookup and fetch tools map to three MCP tools, two of them free.

  2. CrewAI Tools: Build a Custom Tool for Live Web Data

    Build a CrewAI custom tool (a BaseTool subclass) that searches Google for live results, cap it at 5 calls a run, or load MCP tools instead. Tested code.

  3. Build a Market Research Agent with Search and Trends Data

    Wire Google Search, Trends and News into one Python agent, cap it at 8 credits per question, and see a recorded Trends response.

Start with 100 free credits

No password to set. We email you a sign-in link, and your key works on every API.

No credit card. 100 free credits on signup.