From Shopify product data to a 15-second video script with an LLM (and catching the made-up prices)
A practical pipeline: pull product data with the Shopify Admin GraphQL API, ask an LLM for a structured video script, then validate the JSON and the facts before anything is rendered. Ask an LLM to "write a TikTok scrip
A practical pipeline: pull product data with the Shopify Admin GraphQL API, ask an LLM for a structured video script, then validate the JSON and the facts before anything is rendered.
Ask an LLM to "write a TikTok script for this product" and you'll get something that sounds great. Read it closely and you'll often find a problem: a price that's slightly wrong, a feature the product doesn't have, or a 40-second script for a 15-second video.
We build Lyks, which turns Shopify product listings into short vertical videos, so the script step matters a lot to us. Once a video is rendered, a wrong price is expensive to fix. This post walks through a simple pipeline you can build yourself:
- Pull clean product data from Shopify
- Ask the model for a structured script, not free text
- Validate the script's shape and facts before rendering anything
The code is Python, and the model call is vendor-neutral.
Step 1: Get the product data
Use the Admin GraphQL API with an access token that has the read_products scope. Ask only for what the script needs:
import requests
SHOP = "your-store"
TOKEN = "shpat_..." # from your custom app; keep it in a secret store
API_VERSION = "2025-10"
QUERY = """
query ProductForScript($id: ID!) {
product(id: $id) {
title
description(truncateAt: 1200)
productType
tags
priceRangeV2 {
minVariantPrice { amount currencyCode }
}
}
}
"""
def fetch_product(product_gid: str) -> dict:
resp = requests.post(
f"https://{SHOP}.myshopify.com/admin/api/{API_VERSION}/graphql.json",
json={"query": QUERY, "variables": {"id": product_gid}},
headers={"X-Shopify-Access-Token": TOKEN},
timeout=15,
)
resp.raise_for_status()
p = resp.json()["data"]["product"]
return {
"title": p["title"],
"description": p["description"], # plain text, HTML already stripped
"type": p["productType"],
"tags": p["tags"],
"price": p["priceRangeV2"]["minVariantPrice"]["amount"],
"currency": p["priceRangeV2"]["minVariantPrice"]["currencyCode"],
}
Two things we learned here:
-
Use
description, notdescriptionHtml. Product descriptions often contain tables, inline styles and leftover template text. Plain text gives the model less noise. - Truncate long descriptions. Some descriptions are thousands of words of size charts and care instructions. The script needs the top two or three benefits, not everything.
Step 2: Ask for structure, not prose
A 15-second vertical video has a shape: a hook in the first two or three seconds, one or two scenes showing the product, and a call to action. So ask the model to fill in that shape as JSON:
PROMPT = """You write scripts for 9:16 product videos.
Rules:
- Use ONLY the facts in PRODUCT. Do not invent features, results or reviews.
- If you mention the price, use exactly {price} {currency}.
- The hook must work in the first 3 seconds, with the sound off.
- Total length: 8 to 15 seconds.
- Return JSON only, matching this shape:
{{"hook": str, "scenes": [{{"seconds": number, "voiceover": str,
"on_screen_text": str, "shot": "product_closeup"|"in_use"|"presenter"|"before_after"}}],
"cta": str, "duration_s": number}}
PRODUCT:
{product_json}
"""
Asking for fields like on_screen_text and shot does two jobs. It forces the model to think in scenes, and it gives the video renderer exactly what it needs, with no parsing of free text.
Step 3: Validate the shape
Models break JSON contracts more often than you'd hope: an extra field, a missing scene, a 9-second "scene". A JSON Schema catches all of these:
import json
import re
from jsonschema import Draft202012Validator
SCRIPT_SCHEMA = {
"type": "object",
"required": ["hook", "scenes", "cta", "duration_s"],
"additionalProperties": False,
"properties": {
"hook": {"type": "string", "maxLength": 60},
"scenes": {
"type": "array", "minItems": 2, "maxItems": 4,
"items": {
"type": "object",
"required": ["seconds", "voiceover", "on_screen_text", "shot"],
"additionalProperties": False,
"properties": {
"seconds": {"type": "number", "minimum": 1, "maximum": 6},
"voiceover": {"type": "string", "maxLength": 140},
"on_screen_text": {"type": "string", "maxLength": 40},
"shot": {"enum": ["product_closeup", "in_use", "presenter", "before_after"]},
},
},
},
"cta": {"type": "string", "maxLength": 40},
"duration_s": {"type": "number", "minimum": 6, "maximum": 15},
},
}
The maxLength limits aren't arbitrary. Forty characters is about what fits on a phone screen in a readable font, and 140 characters of voiceover is roughly what someone can say in five or six seconds.
Step 4: Validate the facts
Schema validation can't tell you the price is wrong. So add checks for the facts that matter most:
def validate_script(raw: str, product: dict) -> list[str]:
try:
script = json.loads(raw)
except json.JSONDecodeError as e:
return [f"Not valid JSON: {e}"]
problems = [f"{'/'.join(map(str, err.path)) or '(root)'}: {err.message}"
for err in Draft202012Validator(SCRIPT_SCHEMA).iter_errors(script)]
if problems:
return problems
total = sum(s["seconds"] for s in script["scenes"])
if abs(total - script["duration_s"]) > 0.5:
problems.append(f"Scenes add up to {total}s but duration_s is {script['duration_s']}s")
text = json.dumps(script).lower()
for amount in re.findall(r"\$\s?(\d+(?:\.\d{1,2})?)", text):
if float(amount) != float(product["price"]):
problems.append(f"Mentions ${amount}, but the product costs ${product['price']}")
return problems
Here's what it returns for a script that invented a lower price:
['Mentions $19, but the product costs $28.00']
You can extend the same idea to other facts: compare sizes and quantities with the description, flag words like "clinically proven" or "guaranteed" that need evidence, and check that the product name is spelled the way the store spells it.
Step 5: Retry with the errors
When validation fails, don't just retry with the same prompt. Send the problems back:
def generate_script(product: dict, call_llm, max_attempts: int = 3) -> dict:
prompt = PROMPT.format(price=product["price"], currency=product["currency"],
product_json=json.dumps(product, ensure_ascii=False))
for _ in range(max_attempts):
raw = call_llm(prompt)
problems = validate_script(raw, product)
if not problems:
return json.loads(raw)
prompt += "\n\nYour last answer had these problems. Fix them:\n- " + "\n- ".join(problems)
raise RuntimeError(f"No valid script after {max_attempts} attempts: {problems}")
call_llm is any function that takes a prompt and returns text, so you can use whichever model or provider you like. If your provider supports structured outputs, use them too. The validator still earns its keep, because a schema-valid script can still contain a wrong price.
Step 6: Keep a person in the loop
Validation catches the obvious problems. A person catches the subtle ones: a hook that's technically true but misleading, or a tone that doesn't fit the brand. Showing the script for a quick review before rendering is cheap; re-rendering a video isn't.
Where Lyks fits
This is roughly the shape of the script step in Lyks. Merchants connect their Shopify store, pick a product, and get a script they can review and edit before choosing a style (an AI presenter, or a cinematic product video) and generating a finished 9:16 video. It's pay as you go: a $10 top-up covers roughly five short standard videos, credits never expire, and the cost is shown before each task.
But you don't need Lyks to use any of this. If you're generating marketing copy from product data in any form, ask for structure, validate it, check the facts and let a person approve the result.
What's the worst thing an LLM has invented about your product? Prices, features, a warranty you don't offer? Tell us in the comments.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.