Building an E-Commerce Content Optimization Tool with Open-Source Coding LLMs

    This article shows how to build an e-commerce content optimization tool using open-source coding LLMs. It explains why building a full application is a long-horizon engineering task rather than a one-shot coding task, then breaks the business problem into a controllable pipeline of attribute structuring, selling-point extraction, multi-granularity copy generation, and quality scoring. It provides model-agnostic code skeletons built around structured contracts, error feedback, retry limits, and compliance hard-blocking, and covers engineering deployment, cost tiering, and a common-pitfalls checklist. By the end, you will understand how to turn long-horizon model capabilities into a repeatable, production-ready workflow rather than an unverifiable one-off script.

    1. Long-Horizon Coding: From “Writing Code” to “Delivering a Task”

    Before diving in, it helps to clear up a concept that is easy to confuse: a model that “can write a snippet of code” and a model that “can independently deliver a full project” are fundamentally different things.

    The former is a short-horizon task — clear input, well-defined boundaries, and a result delivered in a single response. Examples include completing a function, explaining an error message, or generating a regular expression. The latter is a long-horizon task: it requires sustained progress across steps, files, and tools, and it inevitably runs into surprises along the way — compilation failures, missing dependencies, mismatched interfaces. To succeed, the model must autonomously decompose the goal, plan a route, call tools, read feedback, and self-correct until the whole thing runs. Building an e-commerce content optimization tool is a textbook long-horizon task.

    Dimension Short-horizon task Long-horizon task
    Context Covered by a single prompt Accumulated across steps and files
    Tool use Usually not needed Reading files, running tests, calling APIs
    Failure modes One wrong answer ends it Compilation failure / missing dependencies / interface mismatch
    Typical scenarios Completion, explanation, snippet generation End-to-end delivery of a runnable project

    So how do you decide whether a development task should be handed off to a model entirely? A common industry measure is the task complexity — expressed as the time a human expert would need to complete it — at which a model finishes that class of task with roughly a 50% success rate. It is worth stressing that this metric depends heavily on the task set and the evaluation methodology, and cannot be directly compared across different benchmark sets or different model versions. There is no universal “trend conclusion” that holds everywhere. A more practical approach is this: for your own task, prepare a fixed set of sample cases, run a baseline, and obtain a success rate and average completion time that are specific to you. Then use those numbers to decide how far to hand development over to the model — the stronger the capability, the more worthwhile it is to let the model lead complex engineering, with humans reviewing only at key checkpoints.

    2. Requirement Breakdown: Where the Pain Points of White-Label Products Lie

    The point of turning a white-label product into something that reads like a major brand is not to make the product genuine — it is to strengthen how the product is expressed. White-label products (homogeneous goods that lack a brand premium) suffer from a core disadvantage: their detail-page copy is interchangeable with everyone else’s, selling points are extracted crudely, search-keyword coverage is thin, and there is no scenario-based storytelling. The end result is low conversion and low search visibility.

    Abstracting this business problem into engineering-ready technical goals breaks it down into four sub-capabilities:

    • Attribute structuring: Extract fields such as category, material, specifications, applicable scenarios, and target audience from messy raw information.
    • Selling-point extraction: Translate functional parameters into value propositions that speak to user pain points.
    • Content generation: Produce copy at different granularities — titles, selling-point lists, detail descriptions, and SEO keywords.
    • Quality evaluation and iteration: Score the results, automatically rewrite low-scoring items, and repeat until they meet the bar.

    These four stages form a closed loop of “input → processing → output → feedback,” which is a natural fit for orchestration and driving by a model with long-horizon capabilities.

    3. Architecture Design: Splitting a Long-Horizon Task into a Controllable Pipeline

    The biggest fear with long-horizon tasks is “going all in at once” — asking the model to generate the entire system in a single shot, which tends to be both uncontrollable and hard to debug. A more reliable approach is to split the work into stages with single responsibilities that can be verified independently, then wire them together with an orchestration layer:

    1. Raw product information
    2. │
    3. ▼
    4. [Step 1] Attribute extraction & structuring ──► on validation failure, retry with error context
    5. │
    6. ▼
    7. [Step 2] Selling-point extraction + keyword generation
    8. │
    9. ▼
    10. [Step 3] Multi-granularity copy generation (title / bullets / detail)
    11. │
    12. ▼
    13. [Step 3.5] Compliance hard block ──► on prohibited-term hit, route to human review
    14. │
    15. ▼
    16. [Step 4] Quality scoring ──► if below threshold, locate weak points and rewrite
    17. │
    18. ▼
    19. Structured result output (JSON)

    The key design principle is: the input and output of every step are structured data. Using Pydantic to define explicit contracts is recommended — it surfaces field problems at runtime and also enables programmatic validation:

    1. from pydantic import BaseModel
    2. from typing import List
    3. class Attributes(BaseModel):
    4. material: str = ""
    5. spec: str = ""
    6. scene: str = ""
    7. target_user: str = ""
    8. class CopyDoc(BaseModel):
    9. title: str
    10. bullets: List[str]
    11. detail: str
    12. keywords: List[str]

    4. Development Environment and Runtime Notes

    Because the coding ability of different open-source models varies widely, this article provides a model-agnostic code skeleton; the actual results depend on the model and configuration you choose. In practice, you will typically need:

    • Model access: A unified wrapper (such as llm.complete(prompt, json_mode=True)) hides the SDK differences between models; json_mode forces structured output.
    • Dependencies: pydantic (data validation), jsonschema (optional, for contract validation), the model SDK, and a logging library.
    • Key parameters: retry limit max_retry, scoring iteration limit max_iter, per-call timeout (30–60s recommended), and concurrency (set alongside rate limits and quotas).
    • Error codes and log fields: For each call, record request_id / step / model / prompt_hash / status / latency_ms / retry_times / error_code to make post-mortems straightforward.

    It is recommended to first run a baseline on a fixed set of samples (for example, 20 real product entries), recording success rate, average latency, and human-intervention rate as the basis for deciding whether to scale up. This is exactly how you put “measurement” into practice and avoid making decisions based on unverified conclusions.

    5. Step-by-Step Development Practice

    The illustrative code below shows the skeleton for each stage.

    Step 1: Attribute structuring + automatic retry. Force the model to output JSON, and feed errors back on failure:

    1. import json
    2. def extract_attributes(product: dict, llm, max_retry=3) -> dict:
    3. """Extract structured attributes; on failure, feed the error back to the model and retry"""
    4. feedback = ""
    5. for _ in range(max_retry):
    6. prompt = f"""
    7. You are an e-commerce product analyst. Extract the following fields from the
    8. information below and output strict JSON:
    9. {{"material": "", "spec": "", "scene": "", "target_user": ""}}
    10. Product title: {product["title"]}
    11. Product description: {product["desc"]}
    12. {feedback}
    13. """
    14. raw = llm.complete(prompt, json_mode=True)
    15. try:
    16. data = json.loads(raw)
    17. return Attributes(**data).model_dump() # Pydantic validation
    18. except (json.JSONDecodeError, ValueError) as e:
    19. feedback = f"Your last output was not valid JSON. Error: {e}. Please return JSON only."
    20. raise ValueError("Attribute extraction failed after multiple attempts; human intervention required")

    Step 2: Selling-point and keyword extraction. Emphasize the translation “from function to value”:

    1. def build_selling_points(attrs: dict, llm) -> dict:
    2. prompt = f"""
    3. Based on the attributes below, extract 3 selling points that address user pain
    4. points, and generate 8 highly relevant search keywords. First explain the user
    5. pain point each selling point solves, then provide the keywords.
    6. Attributes: {attrs}
    7. """
    8. return llm.complete(prompt)

    Step 3: Multi-granularity copy generation. Make the function signature, input/output structure, and failure retry explicit so that Step 4’s content has a clear source:

    1. def generate_copy(attrs: dict, selling_points: dict, llm, max_retry=3) -> dict:
    2. """
    3. Generate multi-granularity copy.
    4. Input: attrs (structured attributes); selling_points (selling points and keywords)
    5. Output: {"title": str, "bullets": [str], "detail": str, "keywords": [str]}
    6. """
    7. schema = {
    8. "title": "Product title containing core keywords, <=30 chars",
    9. "bullets": ["List of selling points, each addressing a user pain point"],
    10. "detail": "Detail description with scenario-based storytelling, <=300 chars",
    11. "keywords": ["SEO keywords"]
    12. }
    13. feedback = ""
    14. for _ in range(max_retry):
    15. prompt = f"""
    16. You are an e-commerce content operator. Based on the attributes and selling
    17. points, generate a title, selling points, detail, and keywords. Output JSON
    18. strictly following this structure: {json.dumps(schema, ensure_ascii=False)}
    19. Attributes: {attrs}
    20. Selling points: {selling_points}
    21. {feedback}
    22. """
    23. raw = llm.complete(prompt, json_mode=True)
    24. try:
    25. data = json.loads(raw)
    26. missing = [k for k in ("title", "bullets", "detail", "keywords") if k not in data]
    27. if missing:
    28. raise ValueError(f"Missing fields: {missing}")
    29. return CopyDoc(**data).model_dump() # Return after type validation
    30. except (json.JSONDecodeError, ValueError) as e:
    31. feedback = f"Your last output was invalid: {e}. Please complete the fields and return JSON only."
    32. raise ValueError("Copy generation failed after multiple attempts; human intervention required")

    Step 4: A quality-scoring-driven iteration loop. This is the heart of “self-correction” in long-horizon tasks. Make the scoring convention explicit: each of the four dimensions is scored 0–10, total is the weighted average of the four dimensions (also on a 0–10 scale), and the threshold uses the same 0–10 scale, then validate field presence and weighting consistency:

    1. def score_and_refine(content: dict, llm, threshold=8.0, max_iter=3):
    2. """Each of the four dimensions is scored 0-10; total is the weighted average (0-10); threshold uses the same scale"""
    3. weights = {"selling_point_clarity": 0.3, "scenario_immersion": 0.3,
    4. "SEO_coverage": 0.2, "compliance_risk": 0.2}
    5. report = None
    6. for _ in range(max_iter):
    7. eval_prompt = f"""
    8. Score the following copy on four dimensions, each from 0-10: selling_point_clarity,
    9. scenario_immersion, SEO_coverage, compliance_risk.
    10. Compute the weighted average total (0-10) with weights 0.3/0.3/0.2/0.2.
    11. Output JSON: {{"scores": {{"selling_point_clarity":0,"scenario_immersion":0,
    12. "SEO_coverage":0,"compliance_risk":0}}, "total": 0.0, "fix": ""}}
    13. Copy: {content}
    14. """
    15. report = json.loads(llm.complete(eval_prompt, json_mode=True))
    16. # Validate fields and scale
    17. for k in ("scores", "total", "fix"):
    18. assert k in report, f"Score is missing field: {k}"
    19. assert set(report["scores"]) == set(weights), "Score dimensions do not match"
    20. expect = sum(report["scores"][k] * w for k, w in weights.items())
    21. assert abs(expect - report["total"]) <= 0.5, "total is inconsistent with the weighted result"
    22. if report["total"] >= threshold:
    23. return content, report
    24. content = llm.complete(f"Rewrite the copy based on these improvement suggestions: {report['fix']}\nOriginal: {content}")
    25. return content, report # Return the best result even if the limit is reached; keep the score for human review

    This “score → locate weak points → rewrite → re-score” loop turns the model from a “generator” into an “executor that can deliver a task.”

    6. Self-Correction: The Real Dividing Line of Long-Horizon Capability

    A short-horizon model finishes writing and stops. A long-horizon model instead “runs it, looks at the results, and then corrects.” When putting this into practice, keep three points in mind:

    • Structured contracts first: Define an explicit input/output format (JSON Schema or Pydantic) for every step so that failures can be detected programmatically.
    • Errors must be fed back into context: Pass error messages, scores, and missing fields back to the model as new context — only then can it genuinely “read” what it got wrong.
    • Set retry limits and a human fallback: Automatic self-correction needs boundaries; once the limit is reached, hand off to human review.

    E-commerce compliance is a hard constraint that cannot be skipped. Beyond scoring, you need a hard block before publishing: check for absolute or superlative terms prohibited by advertising compliance regulations (such as “best,” “number one,” “top-tier,” “national-level,” “ultimate”), efficacy and sales claims (“cure,” “eradicate,” “100%,” “best-selling”), and image/font/copy copyright as well as platform restricted-product word rules. Any hit is blocked and routed to human review, never entering the downstream pipeline:

    1. ABSOLUTE_TERMS = ["best", "number one", "top-tier", "ultimate", "national-level", "100%", "permanent", "cure"]
    2. def compliance_guard(content: dict) -> dict:
    3. """E-commerce compliance hard block: route to human review on any hit"""
    4. text = json.dumps(content, ensure_ascii=False)
    5. hits = [w for w in ABSOLUTE_TERMS if w in text]
    6. if hits:
    7. return {"passed": False, "reason": f"Prohibited terms hit: {hits}", "action": "route to human review"}
    8. # Production must also integrate: platform restricted-product word library, copyright validation, category qualification checks
    9. return {"passed": True, "reason": "", "action": "continue"}

    7. Engineering Deployment: From Script to a Production-Ready Service

    Once the prototype passes, you need to add production-grade capabilities, typically carried by general-purpose cloud services: object storage (for assets and results), a message queue (for asynchronous tasks and smoothing out traffic spikes), a container platform (for elastic scaling and canary releases), a logging service (to record inputs, outputs, and retry traces), and monitoring and alerting (to track success rate, score distribution, and average retry count).

    Cost control is equally important, and tiered model calling is recommended: use low-cost models for structured tasks like attribute extraction and selling-point extraction, and invest in strong models only at high-value stages such as copy generation and quality evaluation. For example: if a single product takes about 6 calls (extract 1 + selling points 1 + copy 1 + scoring 1–3), switching 4 of those low-value calls to a cheaper model can cut overall cost substantially — though the exact benefit should be calculated from real-sample token consumption measurements.

    8. Common Mistakes Checklist

    Before wrapping up, this list of high-frequency pitfalls helps you avoid the traps:

    • Generating the entire system at once: It cannot be debugged or localized; always split into stages.
    • No structured validation: Relying on the human eye to check model output; always use JSON + Pydantic double validation.
    • No retry limit: Feeding errors back can create an infinite loop; always set max_retry / max_iter.
    • Ignoring compliance: Advertising-regulation prohibited terms and copyright issues can directly lead to delisting or penalties; always apply a hard block.
    • Choosing based on unverified conclusions: Look at baseline data from your own task set first, and don’t copy other people’s conclusions.

    9. Summary

    The value of long-horizon coding capability lies in transforming “can it be built?” from something that depends on individual experience into an engineering process that the model can lead. Using an e-commerce content optimization tool as the example, the correct path is: first abstract the closed loop of “structuring — extraction — generation — evaluation — compliance,” then use structured contracts, error feedback, retry limits, and compliance hard-blocking to make it controllable, and finally leverage general-purpose cloud capabilities to complete engineering deployment and cost governance. Once you master this approach, white-label products can achieve branded expression at the level of copy, selling points, and operations at scale and repeatably — and this is precisely where a model’s long-horizon capability truly translates into business value.