Engineering Practices for AI Video Generation with LLM APIs

    This article explains how to build a production-grade AI video generation pipeline on top of large language model (LLM) APIs. It covers why calling an API is not enough to deliver videos, a five-layer decoupled architecture, turning vague requirements into structured scripts, asynchronous task queues and state machines, cost control with budget guardrails, observability and quality evaluation, and a practical rollout plan. The core takeaway is to treat the model as a replaceable operator in the chain, so the system can evolve sustainably.

    1. Background: Why Calling an API Is Far from Delivering a Video

    Many teams discover after integrating LLM capabilities that the real engineering effort is not the model call itself, but the entire set of infrastructure built around it. The original request is often just a sentence in natural language, while the final deliverable is a playable, distributable, and reusable video file. In between, the pipeline spans semantic understanding, script decomposition, asset generation, rendering and composition, transcoding, and distribution.

    The typical pain points concentrate in three areas:

    • Long-running tasks and synchronous timeouts: Video generation is a minute-level or even longer task, and synchronous HTTP requests easily trigger gateway timeouts.
    • Ambiguous failure semantics: Content moderation rejections, missing assets, rendering failures, and network jitter require different handling strategies, and a single retry policy amplifies cost.
    • Unpredictable cost: When billing is based on call volume or compute duration, missing budget guardrails can quickly spiral out of control in batch jobs.

    The right approach is to treat “model capability” as one operator in the chain, rather than betting the entire chain on a single request.

    2. Overall Architecture: Five Decoupled Layers

    A five-layer structure is recommended, with each layer communicating only through explicit contracts:

    1. Access layer: Receives requests (text, transcribed speech, images) and handles authentication, rate limiting, and parameter validation.
    2. Orchestration layer: Decomposes the request into a structured script (scenes, duration, narration, subtitles). This is the core of the entire chain.
    3. Capability layer: Encapsulates general capabilities such as LLM inference, speech synthesis, and image generation, with unified timeout and retry policies.
    4. Execution layer: An asynchronous task queue plus rendering/composition and transcoding, responsible for the heavy lifting.
    5. Distribution layer: Object storage holds the artifacts, working with a content delivery network, logging service, and monitoring/alerting to complete delivery and observability.

    The key design principle is: the synchronous API only validates and enqueues; all time-consuming operations are asynchronous.

    3. Requirement Structuring: Turning Vague Descriptions into Executable Scripts

    The orchestration layer should not output free-form text, but constrained structured data. A sample structure is shown below:

    1. {
    2. "title": "Product Introduction Short Film",
    3. "aspect_ratio": "16:9",
    4. "scenes": [
    5. {
    6. "index": 1,
    7. "duration_ms": 4000,
    8. "narration": "A one-sentence narration",
    9. "visual_prompt": "An objective description of the subject, scene, lighting, and camera movement",
    10. "subtitle": "Subtitle text consistent with the narration"
    11. }
    12. ],
    13. "voice": { "speed": 1.0, "style": "neutral" }
    14. }

    Constraining the structured output has two benefits: first, the rendering stage no longer needs to parse natural language; second, static validation can be performed before enqueuing, blocking errors ahead of expensive computation. In practice, it is recommended to set hard upper limits on duration, number of scenes, and subtitle length, and to run a sensitive-content pre-check on prompts.

    4. Asynchronous Tasks and State Machine

    Define a clear state for each task to avoid “stuck but nobody knows”:

    1. CREATED -> VALIDATED -> QUEUED -> RUNNING -> COMPOSITING -> SUCCEEDED
    2. | | |
    3. +-> REJECTED +-> FAILED <-+

    Key points:

    • Idempotency key: Deduplicate using a unique identifier generated on the business side to prevent duplicate billing from repeated user submissions.
    • Tiered retries: Retry network-type errors with exponential backoff; terminate immediately on content moderation rejection, with no retry.
    • Timeout fallback: Set an independent timeout for each stage; on timeout, enter the failed state and release resources.
    • Priority queue: Paid or interactive requests go through a high-priority channel, while batch offline jobs go through a low-priority one.

    5. Cost Control: Budget Guardrails Before Optimization Tricks

    Cost governance should be solved at the architecture level, not reviewed after the fact:

    • Perform quota and budget checks at the access layer, degrading to lower resolution or shorter duration when approaching the threshold.
    • Apply cache reuse to prompts and scripts, so identical scripts directly hit historical artifacts.
    • Separate draft and final pipelines, with drafts going through a low-precision fast preview.
    • Set lifecycle policies for artifacts, with hot/cold tiered storage and automatic cleanup on expiration.

    6. Observability and Quality Evaluation

    The metrics to collect are not just success rate, but also: latency distribution across stages, compute consumption per task, retry rate, distribution of moderation rejection reasons, and artifact reuse hit rate. Logs must carry the task identifier for full-chain tracing, and failure reasons should be categorized and counted, rather than recording only a generic error message.

    On the quality side, it is recommended to build a small regression set and run it after each adjustment to prompt templates or model parameters, combining human scoring with automated metrics, to avoid “tuning by feel”.

    7. Rollout Roadmap

    In the first week, get the minimal loop working: structured script + single-scene generation + writing artifacts to object storage; in the second week, add the asynchronous queue, state machine, and retries; in the third week, integrate budget guardrails, caching, and monitoring/alerting; then gradually expand to multi-scene concatenation, subtitle styling, and multi-aspect-ratio output.

    Baidu AI Cloud provides product categories such as a container platform, message queue, object storage, logging service, and monitoring/alerting, which can serve as the foundation for the architecture above, with teams choosing the level of managed service according to their own scale. The core conclusion is not complicated: the difficulty of AI video generation lies in engineering orchestration and cost governance; only by treating the model as a replaceable operator can the chain have the ability to evolve sustainably.