A Practical Guide to LLM-Driven Prompt Engineering
This article explains how prompt engineering has evolved from a personal skill into a managed engineering asset for generative applications. It covers structured prompt modeling across task, subject, style, negative constraints, and output specs; an automated generate-evaluate-revise loop powered by large language models; modality-specific practices for text, image, and video generation; quality evaluation using rule checks, model review, and human sampling; and the infrastructure needed for versioning, caching, observability, and cost control. It also lists common anti-patterns and how to avoid them. Readers will find vendor-neutral templates, sample pseudocode, and practical guidance for building reproducible generative content pipelines.
1. Background: Why Prompts Became a Core Engineering Concern
As generative AI moved into mainstream content production, prompts evolved from usage tips into engineering assets that need to be managed systematically. Whether the task is text completion, image generation, or video generation, output quality is highly sensitive to the input description: the same intent phrased differently can produce very different results, and the same prompt can suffer structural breakdown or semantic drift under different sampling parameters.
Early practice was driven by individual experience and had three common pain points. First, lack of reproducibility: without version records and parameter snapshots, results could not be regression-tested. Second, lack of maintainability: prompts were scattered across business code, documents, and chat logs, making the impact of changes hard to assess. Third, lack of measurability: without shared metrics, “it feels better” could not be turned into a comparable conclusion.
A common approach that has emerged in the industry is to use intelligent coding tools or large model services with reasoning and rewriting capabilities to expand and restructure user input semantically before generation, then diagnose the output and write back optimization suggestions afterward. This article abstracts away specific product forms and discusses the principles, workflow, and engineering implementation of the method itself.
2. Structured Prompt Modeling: Turning Natural Language into Controllable Input
A high-quality prompt can usually be broken down into several orthogonal dimensions. Making these dimensions explicit is the first step toward controllable model behavior.
- Task: State what to do and avoid ambiguous verbs.
- Subject & Constraints: Object, count, material, time, location, style, and so on.
- Style: Camera language, color palette, brushwork, narrative perspective.
- Negative Constraints: Elements to exclude, such as watermarks, distortions, or text in an image.
- Output Spec: Resolution, duration, aspect ratio, format.
A reusable template example (vendor-neutral) looks like this:
[Task] Generate a short product showcase video[Subject] Subject is {object}, material {texture}, count {count}[Scene] {scene}, time {time}, weather {weather}[Camera] {shot_type}, movement {camera_move}, focal length {focal}[Style] {style}, primary color palette {color_palette}[Negative] Do not include {exclude_list}[Spec] Duration {duration}s, aspect ratio {ratio}, frame rate {fps}
The direct benefit of structuring is replaceable slots: the business side only maintains slot values instead of rewriting the entire natural-language prompt each time. The prompt is upgraded from “text” to “configuration.”
3. An LLM-Assisted Prompt Generation and Optimization Loop
Involving large models in prompt engineering essentially replaces manual trial and error with an automated generate-evaluate-revise loop. The loop has four stages.
1) Intent clarification. User input is often short and vague, for example “make a tech-style video.” The model first fills in missing slots, outputs a structured draft, and proactively asks about uncertain items or states default assumptions.
2) Candidate expansion. Generate multiple differentiated candidates for the same intent, covering different styles and camera plans to avoid converging on a mediocre single result.
3) Diagnosis and rewriting. Score and rewrite candidates based on historical failure cases (such as structural breakdown, missing subject, or inconsistent style), with emphasis on strengthening negative and spec constraints.
4) Write-back and accumulation. Write effective prompts and their parameter snapshots into a template library to form searchable, reusable assets.
Illustrative code (pseudo-implementation that expresses the flow only and does not target any specific API):
def build_prompt(intent: str, slots: dict, template: str) -> str:draft = llm_complete(template, intent=intent, slots=slots) # structured draftcandidates = llm_expand(draft, n=4) # candidate expansionscored = [(score(c, eval_set), c) for c in candidates] # quality evaluationbest = max(scored, key=lambda x: x[0])[1]return llm_rewrite(best, negative=slots.get("exclude", [])) # diagnosis and rewrite
It is important to note that the evaluation function score is the key to the entire loop, because it determines whether the optimization direction is correct. Section 5 expands on this.
4. Key Differences Across Multimodal Scenarios
Text, image, and video tasks differ in their sensitivity to prompts, so strategies need to be designed separately.
Text generation focuses more on role setting, output structure, and length constraints. A four-part pattern of “role + goal + audience + format” works well. Explicitly stating prohibited items also helps reduce off-topic output and safety risks.
Image generation is extremely sensitive to subject count, spatial relationships, and negative constraints. In practice, it is recommended to write “count, position, material, lighting” as separate short sentences to avoid semantic dilution caused by long nested modifiers. Negative descriptions should be grouped together to prevent interference with positive descriptions.
Video generation adds a time dimension on top of image elements and requires additional description of camera movement, pacing, and transitions. Because temporal consistency is harder to maintain, it is recommended to split the prompt into a “global style section + shot-by-shot section,” describe each shot while keeping consistent subject references, and reduce the probability of cross-frame drift.
5. Quality Evaluation: Giving Optimization a Direction
Without measurement there is no optimization. A practical evaluation usually combines three types of signals.
- Rule checks: Whether specs are met (duration, ratio, count) and whether negative elements appear; these can be implemented with deterministic checks.
- Model review: A model with reasoning capability scores outputs against a unified rubric and returns structured comments with reasons for deductions.
- Human sampling: Keep human review for high-risk scenarios, with the sampling ratio adjusted dynamically based on online metrics.
The rubric should stay concise with mutually exclusive dimensions, for example four items: instruction following, structural completeness, style consistency, and safety, each scored 0–5. Evaluation results must be stored together with the prompt version and sampling parameters to support regression comparison.
6. Engineering Implementation: Versioning, Caching, and Cost
Bringing prompts into the engineering system requires three pieces of infrastructure.
Version management. Treat prompts the same as code, using text-based storage and diff comparison, with review required for changes; online issues can be rolled back quickly to a known-good version.
Caching and reuse. Build result caches and template reuse for high-frequency identical intents to reduce latency and control compute costs. Cache keys should include a prompt digest and key parameters to avoid cross-contamination.
Observability. Use logging services to record request summaries, latency, and failure reasons, with monitoring and alerting to trigger notifications when success rate or latency is abnormal. Object storage can archive generated artifacts, message queues can smooth traffic peaks, and container platforms can host elastic scaling for inference and batch processing tasks.
For cost control, a “tiered invocation” strategy is recommended: simple intents go to lightweight models or direct template output, while only complex intents are escalated to stronger reasoning models, with an upper limit set on the number of candidates.
7. Common Anti-Patterns and How to Avoid Them
- Excessive stacking: Cramming dozens of adjectives into one sentence dilutes key constraints. Split into short sentences and control total length.
- Mixed positive and negative: Interleaving positive and negative descriptions makes it hard for the model to distinguish them. Write them in separate sections.
- Iteration without evaluation: Changing words by feel makes it impossible to judge the benefit. Build a rubric first, then optimize.
- Rigid templates: Templates that are not updated for a long time cannot adapt to new scenarios. Revise them periodically using failed samples from production.
- Ignoring safety: Missing content compliance constraints exposes risk later. Add safeguards at both the prompt layer and the post-processing layer.
8. Conclusion
Prompt engineering is moving from individual technique to team-level engineering capability. The core is not dependence on any particular tool, but building a complete chain of “structured modeling — automated loop optimization — quantitative evaluation — versioned governance.” Combining this method with general cloud product capabilities from Baidu AI Cloud (such as object storage, message queues, container platforms, logging services, and monitoring alerts) can build a stable, reproducible, and scalable generative content production pipeline, turning output quality from chance into a manageable, deliverable engineering metric.
