Blog

How to build an AI shopping assistant: a tested Python example with live product data

Build a shopping assistant that turns a request like "men's pajama pants under $30" into live picks with price, sizes, delivery and link. Tested Python code.

Published

An AI shopping assistant takes what a shopper types, such as "men's pajama pants under $30", and comes back with a few products that fit: the price, the rating, the sizes in stock, when it would arrive, and a link to buy. The language model is good at the conversation. What it cannot do on its own is see what is for sale today and at what price. That part needs live product data.

This guide builds the data side of a shopping assistant in Python. The script is 81 lines, uses the standard library only, and does what most shopping assistants do on every request: one product search, a filter for the shopper's budget, and a closer read of the best few products. Everything below was run on 25 November 2026, and the output shown is the real output.

How does a shopping assistant work?

Most shopping assistants follow the same four steps for each request:

  1. Understand the request. Pull out what the shopper wants ("men's pajama pants") and any limits, such as a budget ("under $30"), a size or a delivery date.
  2. Search one shop. Run a product search on the shop that fits the request, and keep the organic results, not the ads.
  3. Filter and rank. Drop what breaks the limits, then rank what is left. Rating and the number of ratings are a simple, fair starting point.
  4. Read the top few products. A search result has the title, price and rating. The product page adds what a shopper asks next: which sizes there are, when it would arrive, and whether the discount is real.

The model can do step 1 well. Steps 2 to 4 need a data source it can call, such as a product search API. In this example a few lines of Python do step 1 too, so you can see every step and run it without a model.

What will you build?

A script, shopping_assistant.py, that:

  1. takes a request in plain words, such as men's pajama pants under $30,
  2. splits it into a search phrase and a budget,
  3. calls search_products on amazon.com for up to 20 results,
  4. keeps the results at or under the budget and ranks them by rating, then by number of ratings,
  5. calls get_product on the top three for sizes and delivery,
  6. prints three picks with price, original price, rating, sizes, delivery and link, plus the time the prices were read.

Each request costs 8 credits: 5 for the search and 1 for each of the three product reads. The 200 free credits every account starts with cover 25 shopper requests (pricing).

How do you set up access?

Every account starts with 200 free credits, and sign-in is by email. The quickest way is to give your coding agent (Claude Code, Cursor or similar) this line:

set up https://mcp.datawebot.com/setup.md

The agent asks for your email and you approve the sign-in from the email datawebot sends. The key is saved to ~/.datawebot/credentials, readable only by you, and the script reads it from there. That key lasts 30 days. For an assistant that runs on a server, create a key that lasts 90 or 365 days on the dashboard under API keys, and put it in an environment variable named DATAWEBOT_API_KEY from your secret store. Never commit it.

What does the code look like?

Python 3.9 or later, no packages to install.

"""A small shopping assistant: turn a shopper's request into one product search,
keep the results that fit the budget, read the best few for details, and print
picks with price, rating, sizes, delivery date and link. Uses the datawebot MCP server."""
import json, os, re, sys, urllib.request

MCP_URL = "https://mcp.datawebot.com/mcp"
SHOP = "amazon.com"   # the shop to search; any shop domain works, e.g. walmart.com
PICKS = 3             # how many products to read in detail


def api_key():
    key = os.environ.get("DATAWEBOT_API_KEY")
    if key:
        return key
    # Written by the agent setup (https://mcp.datawebot.com/setup.md).
    with open(os.path.expanduser("~/.datawebot/credentials")) as f:
        return json.load(f)["profiles"]["https://mcp.datawebot.com"]["api_key"]


def call_tool(name, arguments):
    body = {"jsonrpc": "2.0", "id": 1, "method": "tools/call",
            "params": {"name": name, "arguments": arguments}}
    req = urllib.request.Request(MCP_URL, data=json.dumps(body).encode(), headers={
        "Content-Type": "application/json",
        "Accept": "application/json, text/event-stream",
        "Authorization": "Bearer " + api_key()})
    with urllib.request.urlopen(req, timeout=120) as r:
        raw = r.read().decode()
    if raw.startswith("event:") or "\ndata:" in raw:  # streamed reply
        raw = "\n".join(l[5:].strip() for l in raw.splitlines() if l.startswith("data:"))
    result = json.loads(raw)["result"]
    payload = result.get("structuredContent") or json.loads(result["content"][0]["text"])
    if result.get("isError"):
        raise RuntimeError(f"{name} failed: {json.dumps(payload)[:300]}")
    # A slow request answers status "working"; get_results collects it, free.
    while payload["data"].get("status") == "working":
        payload = call_tool("get_results", {"request_id": payload["data"]["request_id"]})
    return payload


def parse_request(text):
    """Split "men's pajama pants under $30" into ("men's pajama pants", 30.0)."""
    m = re.search(r"\b(?:under|below|less than|up to)\s*\$\s*(\d+(?:\.\d+)?)", text, re.I)
    if not m:
        return text.strip(), None
    return (text[:m.start()] + text[m.end():]).strip(" ,."), float(m.group(1))


def amount(field):
    return (field or {}).get("amount")


def main(request):
    query, budget = parse_request(request)
    found = call_tool("search_products", {"query": query, "site": SHOP, "country": "US", "limit": 20})
    products = found["data"]["products"]  # organic results only; ads come back in "sponsored"
    fits = [p for p in products if amount(p["price"]) and (budget is None or amount(p["price"]) <= budget)]
    # Prefer what shoppers rate well: rating first, then how many people rated it.
    fits.sort(key=lambda p: (p.get("rating") or 0, p.get("review_count") or 0), reverse=True)
    print(f'Request: "{request}" -> search {SHOP} for "{query}"'
          + (f", budget ${budget:.0f}" if budget else ""))
    print(f"{len(products)} results, {len(fits)} within budget, read {found['meta']['as_of']}\n")
    for p in fits[:PICKS]:
        d = call_tool("get_product", {"url": p["url"]})["data"]["product"].get("details") or {}
        sizes = []
        for v in d.get("variants") or []:
            s = (v.get("options") or {}).get("Size")
            if s and s not in sizes:
                sizes.append(s)
        was = f" (was ${amount(p['original_price']):.2f})" if amount(p.get("original_price")) else ""
        print(f"* {p['title'][:80]}")
        print(f"  ${amount(p['price']):.2f}{was}, {p.get('rating')} stars from {p.get('review_count')} ratings")
        if sizes:
            print(f"  Sizes: {', '.join(sizes)}")
        if d.get("delivery"):
            print(f"  {d['delivery'][0]['text']}")
        print(f"  {p['url']}\n")


if __name__ == "__main__":
    main(" ".join(sys.argv[1:]) or "men's pajama pants under $30")

A few choices worth knowing:

  • One shop per search. search_products searches the shop you name, here amazon.com. A search across many shops costs 25 credits instead of 5, so an assistant should pick the shop that fits the shopper and the product, and search across shops only when the shopper asks to compare.
  • Organic results only. The search returns organic results in products and ads separately in sponsored. The script ranks only the organic ones. If you show ads, label them.
  • The budget is a hard filter. A product over budget is dropped, not ranked lower. Shoppers notice when an assistant ignores their budget.
  • The product read adds what a shopper asks next. Sizes come from the product's variants, and delivery from the delivery lines on the page. The search result alone does not have them.
  • Say when prices were read. Every answer carries meta.as_of. Prices change, so tell the shopper the time, and treat the shop's page as the final word at checkout.

What did it return?

Run on 25 November 2026 at 10:10 UTC:

$ python3 shopping_assistant.py "men's pajama pants under $30"
Request: "men's pajama pants under $30" -> search amazon.com for "men's pajama pants", budget $30
20 results, 16 within budget, read 2026-11-25T10:10:41.311Z

* #followme Men’s Buffalo Plaid Pajama Pants – Micro Fleece Lounge PJs with 2 Pock
  $14.99 (was $19.99), 4.7 stars from 43400 ratings
  Sizes: Small, Medium, Large, X-Large, XX-Large, 3X-Large
  FREE delivery Monday, November 30 on orders shipped by Amazon over $35
  https://www.amazon.com/dp/B06Y1RWZTG

* Nautica Men's Soft Knit Sleep Lounge Pant
  $15.96 (was $45.00), 4.7 stars from 7700 ratings
  Sizes: 3X Big, Small, Medium, Large, X-Large, XX-Large, 1XLT Tall, 1X Big, 2X, 2XLT Tall, 3XLT Tall
  FREE delivery Tuesday, December 1 on orders shipped by Amazon over $35
  https://www.amazon.com/dp/B079J1M8FV

* U2SKIIN 2 Pack Mens Fleece Pajama Pants, Warm Plaid Lounge Pj Bottoms for Men wi
  $24.99 (was $39.99), 4.7 stars from 811 ratings
  Sizes: Small, Medium, Large, X-Large, XX-Large
  FREE delivery Tuesday, December 1 on orders shipped by Amazon over $35
  https://www.amazon.com/dp/B0BDR81ZDM

Twenty organic results came back. Sixteen were at or under $30, and the script read the three best rated. Two things stand out. All three picks are discounted against their original price, which matters to a shopper who asked for a budget. And the size lists differ a lot: the second pick has big and tall sizes the other two do not. That is the kind of detail that decides a purchase and that only the product read gives you.

How do you turn this into an agent?

The script hard-codes the shop and parses the budget with a regular expression. In a real assistant, the language model does both. Connect the model to the datawebot MCP server and it gets the same two tools, search_products and get_product, with their descriptions, and decides when to call them (MCP tools).

A system prompt along these lines keeps the model to the pattern above:

You help shoppers find products. For each request:
1. Work out the product, the budget and any size or delivery need.
2. Call search_products once, on the shop that best fits the product and country.
3. Drop results over budget. Rank the rest by rating, then number of ratings.
4. Call get_product on the top three, then answer with price, rating,
   sizes, delivery and the link, and say when the prices were read.
Never show ads as organic results.

You can try this without writing code. After the setup line above, ask your coding agent "find me men's pajama pants under $30 on amazon.com, show the top three with sizes and delivery". It calls the same tools the script calls.

What does this not do?

  • It does not buy anything. The assistant finds products and links to them. Checkout happens on the shop.
  • It does not keep price history. Each request is a fresh read of the shop. If your assistant tracks prices over time, store each answer with its time.
  • It reads one shop per request. To compare the same product across shops, use a search across shops or read the product on each shop you care about.
  • It ranks simply. Rating and number of ratings are a starting point. Add your own signals, such as delivery date or brand, as your shoppers need them.

Other shops

Change SHOP to search a different shop, such as walmart.com, target.com or bestbuy.com. Before you switch, the free check_site tool tells you what datawebot can read on a shop and what each read costs.

Frequently asked questions

What is an AI shopping assistant?

A program, usually built on a language model, that takes a shopper's request in plain words and answers with products that fit: price, rating, sizes, delivery and a link to buy. The model handles the conversation, and a product data source supplies what is for sale right now.

Can ChatGPT or Claude be a shopping assistant on its own?

A model can talk about products it learned about in training, but it cannot see today's prices, stock or sizes on its own. Connect it to live product data, for example through an MCP server, and it can search a shop and read product pages while it answers.

How much does each shopper request cost?

In this example, 8 credits: 5 for the search on amazon.com and 1 for each of three product reads. The 200 free credits cover 25 requests. Other shops can cost a different amount, and the free check_site tool shows the price before anything runs.

How fresh are the prices?

Each request reads the shop when it runs, and every answer says when through meta.as_of. Prices can change after that, so show the shopper the time and send them to the shop's page to buy.

Can the assistant search Walmart, Target or Best Buy instead of Amazon?

Yes. Change SHOP in the script, or let the model pick the shop for each request. Search one shop at a time unless the shopper asks to compare shops.

Sources

  1. https://mcp.datawebot.com/setup.md
  2. https://www.datawebot.com/llms.txt
  3. https://www.datawebot.com/pricing
  4. https://modelcontextprotocol.io/specification/2025-06-18/server/tools
  5. https://docs.python.org/3/library/re.html

Search products in online shops from your agent or code.

Every account starts with 200 free credits, with no subscription: a search costs 5 credits and a product read 1. Failed requests are free.

← All articles