Engineering Long-Horizon E-Commerce Tasks with Open-Source LLMs

    As LLMs improve at coding and complex tasks, engineering teams need practical methods for keeping multi-hour workflows stable, recoverable, and auditable. Using an e-commerce scenario—turning white-label products into branded presentations—this article examines the capabilities and limits of long-horizon task execution, a three-layer architecture, task orchestration design, idempotency and compensation, error classification, human handoff thresholds, and context and cost management. It includes a non-production code skeleton and implementation notes for reliable agent workflows.

    Introduction

    LLMs are improving at programming and complex tasks, but the industry lacks a consistent way to evaluate how long a task a model can complete, and different studies report very different growth rates. This article does not cite specific growth multiples. It focuses on engineering questions: how to keep a model advancing reliably through tasks that last several hours, recover from failures, and hand control back to humans when necessary.

    E-commerce is a good test case for long-horizon task capability. Consider “turning a white-label product into a branded presentation.” A single task typically includes reading product data, analyzing competitors, generating copy, generating image prompts, calling image APIs, uploading assets, and writing back to the database. Each step can fail: API timeouts, rate limits on image services, copy that triggers platform sensitive-word checks, or missing JSON fields in responses. The system must handle exactly these failures.

    1. Three Capabilities and Boundaries of Long-Horizon Tasks

    Long-horizon tasks depend on three capabilities:

    1. Autonomous planning: the model breaks a business goal into ordered steps with dependencies.
    2. Autonomous execution: the model selects tools, generates parameters, and handles intermediate results.
    3. Autonomous error correction: the model reads error information and decides whether to retry, switch approaches, or stop.

    These capabilities have clear boundaries. Planning quality depends on the specific model version and prompt, and the same model can perform very differently across task sets. Before launch, evaluate with real samples; do not directly reuse public data. During error correction, a model may propose plausible but incorrect fixes, so corrective actions must be constrained by rules and retain human review entry points.

    2. Architecture and Component Responsibilities

    The system has three layers. Their responsibilities and failure handling are as follows:

    Layer Main responsibilities Input Output Failure handling
    Model interaction layer Calls models, manages context, parses structured output Task state, tool definitions, error information Structured plan, tool parameters If output does not match the schema, ask the model to regenerate; after the maximum number of attempts, hand off to a human
    Task orchestration layer Maintains the task graph, schedules steps, controls retries and termination Model plan, step results Task state updates, next-step instructions Applies policies by error category; see Sections 3 and 5
    Infrastructure layer Provides containers, object storage, message queues, logging, and monitoring Task messages, files, logs Execution results, alerts Queue messages enter the dead-letter queue for investigation

    The data flow is as follows: a user request enters the orchestration layer, the model generates a plan, and the orchestration layer splits the plan into task nodes and writes them to the state store. Long-running tasks, such as batch image rendering, are sent to workers through a message queue. After a worker finishes, it writes back the result; the orchestration layer updates the state and decides the next step. Logs from all nodes go to a central logging service with the same run_id, making it possible to trace a complete task.

    3. Executable Design for the Task Orchestration Layer

    1. Task Node Fields

    Each task node contains at least the following fields:

    • task_id: unique identifier for the node.
    • idempotency_key: a hash computed from the run_id, tool name, and normalized parameters. An operation with the same key is executed only once, and duplicate messages directly return the existing result.
    • tool and params_schema_version: tool name and version of the parameter definition.
    • depends_on: list of predecessor nodes.
    • status: one of pending, running, succeeded, failed_retryable, failed_terminal, needs_human, or compensated.
    • attempt and max_attempts: current attempt count and upper limit.
    • timeout_s: timeout for a single call.
    • output_ref: location of the result in storage; large objects store only references.
    • compensate_tool: tool used for rollback; leave empty if none.

    2. State Transitions

    A node moves from pending to running. On success, it becomes succeeded. On a retryable error that has not exceeded the limit, the status returns to pending and waits according to the backoff time. When retries are exhausted or a non-retryable error occurs, the status becomes failed_terminal or needs_human, and a human decides the next action.

    3. Timeouts, Retries, and Total Limits

    • Single tool call timeout: 10 seconds for queries, 120 seconds for image generation, and 30 seconds for uploads.
    • Backoff policy: the nth retry waits 2^n seconds plus random jitter to avoid many tasks retrying at the same time.
    • A single node has at most 3 attempts.
    • A single task has at most 2 replans.
    • A single task has at most 50 tool calls; beyond that, stop and hand off to a human.
    • The maximum total duration for a single task is 6 hours.

    These values are examples and should be adjusted based on actual API response times and costs.

    4. Idempotency and Compensation

    Image uploads and database writes must carry an idempotency_key. Database writes use upsert, so repeated execution produces the same result.

    A typical compensation scenario is this: an image has been uploaded to object storage, but writing back to the product database fails. The system first calls a delete tool to clean up the orphan file. If deletion also fails, the file is recorded in a pending-cleanup list and operations is notified. Compensation actions themselves must also be logged.

    5. Interaction with the Message Queue

    When long-running tasks are published to the queue, the message body contains only task_id and idempotency_key, not large data. A worker acknowledges the message only after processing is complete and the result has been written back. The queue visibility timeout should be greater than the maximum tool timeout; otherwise, the same message may be delivered repeatedly. Messages that exceed the maximum delivery count enter the dead-letter queue for manual review.

    6. Human Takeover Thresholds

    The system should stop automatic execution and notify the owner when:

    • The same node fails twice consecutively.
    • The task involves external publishing, such as prices, promotional commitments, or brand claims.
    • The model cost for a single task exceeds 80% of the budget.
    • The replan count reaches the limit.
    • The error type is permission denied.

    4. Code Skeleton (Non-Production Illustration)

    The following code only illustrates the structure. It does not include authentication, log redaction, real model clients, or persistent storage, and these must be completed before production.

    1. import time
    2. from dataclasses import dataclass, field
    3. from enum import Enum
    4. class ErrorType(Enum):
    5. TIMEOUT = "timeout"
    6. RATE_LIMIT = "rate_limit"
    7. SENSITIVE_WORD = "sensitive_word"
    8. FORMAT_ERROR = "format_error"
    9. PERMISSION = "permission"
    10. UNKNOWN = "unknown"
    11. @dataclass
    12. class PlanStep:
    13. step_id: str
    14. tool: str
    15. depends_on: list = field(default_factory=list)
    16. max_attempts: int = 3
    17. class ToolError(Exception):
    18. def __init__(self, error_type: ErrorType, message: str):
    19. super().__init__(message)
    20. self.error_type = error_type
    21. class HumanHandoff(Exception):
    22. pass
    23. MAX_REPLAN = 2
    24. MAX_TOOL_CALLS = 50
    25. class ECommerceAgent:
    26. def __init__(self, model_client, tools, validators):
    27. self.model = model_client # provides plan / generate_params / replan methods
    28. self.tools = tools # tool name -> callable object
    29. self.validators = validators # tool name -> param validator; raises ValueError on failure
    30. self.tool_calls = 0
    31. def run(self, request):
    32. steps = self.model.plan(request, tools=list(self.tools)) # already sorted by dependencies
    33. results, replans, i = {}, 0, 0
    34. while i < len(steps):
    35. if self.tool_calls >= MAX_TOOL_CALLS:
    36. raise HumanHandoff("tool call count exceeds limit")
    37. step = steps[i]
    38. params = self.model.generate_params(step, results)
    39. try:
    40. results[step.step_id] = self._call_with_retry(step, params)
    41. i += 1
    42. except ToolError as e:
    43. if e.error_type == ErrorType.PERMISSION or replans >= MAX_REPLAN:
    44. raise HumanHandoff(f"{step.step_id}: {e}")
    45. replans += 1
    46. steps = steps[:i] + self.model.replan(steps[i:], e.error_type, str(e))
    47. return results
    48. def _call_with_retry(self, step, params):
    49. for attempt in range(1, step.max_attempts + 1):
    50. try:
    51. self.validators[step.tool](params)
    52. except ValueError as e:
    53. raise ToolError(ErrorType.FORMAT_ERROR, str(e))
    54. try:
    55. self.tool_calls += 1
    56. return self.tools[step.tool](**params)
    57. except ToolError as e:
    58. retryable = e.error_type in (ErrorType.TIMEOUT, ErrorType.RATE_LIMIT)
    59. if retryable and attempt < step.max_attempts:
    60. time.sleep(2 ** attempt)
    61. continue
    62. raise
    63. raise ToolError(ErrorType.UNKNOWN, "retries exhausted")

    This code has several points to note. replan only replaces steps that have not yet been executed; completed results remain in results. Sensitive-word errors are not automatically bypassed, because bypass rules may create compliance risk; they should be handled by the rules engine and human review.

    5. Error Classification and Correction Strategies

    Error type Typical symptom First strategy Fallback strategy Limit and termination condition
    Timeout API does not respond for a long time Retry after exponential backoff Switch to a backup API 3 attempts per node; mark failed_terminal after failure
    Rate limit Returns 429 or insufficient quota Back off and reduce concurrency Run at off-peak times or switch to a backup service 5 attempts; hand off to a human if cumulative wait exceeds 10 minutes
    Sensitive word Platform rejects the prompt or copy Have the model rewrite once, then recheck with compliance rules Hand off to human review 1 rewrite; if not approved, hand off to a human
    Format error Missing fields or type mismatch Send the validation error back to the model and regenerate parameters Use default values for non-critical fields only 2 attempts, then hand off to a human
    Permission denied Access denied Do not retry; hand off immediately None Record an audit log
    Unknown error Unclassifiable exception Log full details and retry once Hand off to a human 1 attempt

    The sensitive-word row needs special explanation. Automatic rewriting may cause copy to deviate from facts or evade platform rules. Rewritten results must pass rule rechecking, and before-and-after comparison records must be retained.

    6. Context Management and Cost

    Long-horizon tasks accumulate large amounts of intermediate logs, and the model context window quickly fills up. There are three common compression methods:

    • Summary: compress earlier steps into a few sentences. This is simple to implement, but details are easily lost.
    • Retrieval: store history in a vector database and retrieve it by relevance when needed. This suits scenarios with large information volume and diverse query patterns, but it adds retrieval latency and the risk of false retrieval.
    • Hierarchical memory: keep full logs for the most recent steps, store earlier steps as summaries, and the task’s