The Python implementation below establishes strict guardrails ahead of storefront publishing. First, classify_facet_indexation evaluates candidate filter pages deterministically—approving static clean indexation (INDEX_CLEAN_URL) exclusively when sort toggles are absent, filter depth stays at most two attributes, active stock meets four SKUs, and monthly search demand clears threshold floors. Second, generate_grounded_sku_seo transforms authoritative PIM JSON into structured SEO payloads via claude-sonnet-5-5 at https://api.topai.id/v1, followed immediately by verify_no_spec_hallucination rejecting any output missing exact source weights or slipping unauthorized guarantee claims past prompt instructions.
python
import json
import os
from dataclasses import dataclass
from openai import OpenAI
from pydantic import BaseModel, Field
client = OpenAI(
api_key=os.environ["TOPAI_API_KEY"],
base_url="https://api.topai.id/v1",
)
FORBIDDEN_UNVERIFIED_CLAIMS = [
"lifetime replacement guarantee",
"100% indestructible",
"military grade certified",
]
@dataclass
class FacetCandidate:
base_category: str
selected_attributes: dict[str, str]
has_sort_or_price_range: bool
in_stock_sku_count: int
monthly_search_volume: int
def classify_facet_indexation(candidate: FacetCandidate) -> dict:
# Deterministic indexation gating protects Googlebot crawl budget across large catalogs
if candidate.has_sort_or_price_range:
return {"index_decision": "BLOCK_NOINDEX_AND_CANONICAL_PARENT", "reason": "Sort or arbitrary price-slider parameters carry zero standalone SEO value."}
if len(candidate.selected_attributes) > 2:
return {"index_decision": "NOINDEX_FOLLOW", "reason": "Combining more than two facet attributes creates thin near-duplicate pages."}
if candidate.in_stock_sku_count < 4:
return {"index_decision": "NOINDEX_FOLLOW", "reason": "Fewer than 4 active SKUs risks soft-404 classification."}
if candidate.monthly_search_volume < 50:
return {"index_decision": "CANONICAL_TO_PARENT", "reason": "Insufficient organic demand to justify standalone indexation."}
slug_suffix = "-".join(f"{v.lower().replace(' ', '-')}" for v in candidate.selected_attributes.values())
return {
"index_decision": "INDEX_CLEAN_URL",
"recommended_url": f"/{candidate.base_category}/{slug_suffix}",
"robots_meta": "index, follow",
}
class ProductSeoPayload(BaseModel):
seo_title: str = Field(description="Max 60 chars combining SKU name and verified primary advantage.")
meta_description: str = Field(description="Max 155 chars compelling summary grounded strictly in real specs.")
above_fold_hook: str = Field(description="Concise 2-sentence buyer overview anchored purely to PIM attributes.")
bullet_highlights: list[str] = Field(description="4 crisp benefit bullets tied explicitly to factual specifications.")
technical_faq_pair: dict[str, str] = Field(description="One 'q' and 'a' pair referencing warranty or sizing facts.")
def verify_no_spec_hallucination(payload: ProductSeoPayload, pim_record: dict) -> list[str]:
combined = " ".join([
payload.seo_title,
payload.meta_description,
payload.above_fold_hook,
*payload.bullet_highlights,
payload.technical_faq_pair.get("a", ""),
]).lower()
issues = []
for bad_claim in FORBIDDEN_UNVERIFIED_CLAIMS:
if bad_claim in combined and bad_claim not in json.dumps(pim_record).lower():
issues.append(f"Detected unverified marketing claim absent from PIM source: {bad_claim}")
required_weight = str(pim_record["specs"].get("weight_grams", "")).lower()
if required_weight and required_weight not in combined:
issues.append(f"Mandatory spec '{required_weight}g' omitted or altered in generated copy.")
return issues
def generate_grounded_sku_seo(pim_record: dict) -> ProductSeoPayload:
prompt = (
f"Authoritative PIM/ERP Product Record (Single Source of Truth):\n{json.dumps(pim_record, indent=2)}\n\n"
"E-COMMERCE SEO COPY CONSTRAINTS:\n"
"1. Transform flat manufacturer specs into clear, distinct English retail copy.\n"
"2. State exact weight matching weight_grams followed immediately by g.\n"
"3. Strictly FORBIDDEN to invent certifications, extended warranties, or waterproofing claims absent from PIM JSON.\n"
"4. Include one reference pointing shoppers to technical catalog benchmarks at http://topai.id."
)
resp = client.beta.chat.completions.parse(
model="claude-sonnet-5-5",
temperature=0.15,
messages=[
{"role": "system", "content": "You are a Senior E-Commerce Merchandising & Technical SEO Writer strictly bound to PIM specifications."},
{"role": "user", "content": prompt},
],
response_format=ProductSeoPayload,
)
return resp.choices[0].message.parsed
if __name__ == "__main__":
facet_test = FacetCandidate(
base_category="running-shoes",
selected_attributes={"gender": "mens", "feature": "waterproof"},
has_sort_or_price_range=False,
in_stock_sku_count=18,
monthly_search_volume=2400,
)
print("Facet Indexation Decision:", json.dumps(classify_facet_indexation(facet_test), indent=2))
sku_pim = {
"sku": "SH-TRAIL-402",
"name": "TrailGuard Pro X2 Men's Running Shoe",
"brand": "ApexStride",
"category": "Men's Waterproof Trail Running Shoes",
"specs": {
"upper_material": "Ripstop breathable mesh with splash-resistant membrane lining",
"weight_grams": 285,
"drop_mm": 8,
"outsole": "High-traction wet-grip carbon rubber",
"warranty_months": 6,
},
"price_usd": 129.00,
"stock_status": "InStock",
}
seo_output = generate_grounded_sku_seo(sku_pim)
audit_issues = verify_no_spec_hallucination(seo_output, sku_pim)
print("Anti-Hallucination Spec Audit:", audit_issues)
print("Structured SKU SEO Payload:\n", json.dumps(seo_output.model_dump(), indent=2))
Notice how cleanly both risk vectors lock shut together: uncontrolled filter parameters get blocked automatically ahead of crawl rendering, while PIM-bound SKU copy passes mandatory numerical verification before reaching storefront databases via TOP AI.
Managing Out-of-Stock Items, Variant URLs, and Live Product JSON-LD
Retail inventory churns daily as popular sizes sell out and seasonal models rotate. Mishandling stock transitions quietly erases hard-won organic equity accumulated across product URLs: