Building LLM-Powered Couplet Generation: A Constrained Text Generation Approach
This article explains how to build an intelligent Chinese couplet generation service by treating it as a high-constraint text generation problem. It covers a five-layer architecture, prompt and constraint design, rule-based validation for parallelism, responsive multilingual UI, calligraphy-style rendering and image export, performance and cost controls, and common failure modes with workarounds.
1. Why Couplet Generation Is a High-Constraint Text Generation Problem
Couplets are short, but they are among the most constraint-dense tasks in Chinese text generation. They require semantic relevance, structural symmetry, tonal harmony, equal character counts, and a complete arc of imagery and emotion within a limited number of characters. A general text generation model optimized only for fluency often produces lines of unequal length, mismatched parts of speech, or repeated imagery across the two lines (a flaw known as hezhang, or “joined palms”). Treating couplet generation as a constrained generation task rather than “write two auspicious lines” is the first step toward a working implementation.
Typical use cases include holiday celebrations, store and home decoration, cultural event planning, community outreach, and teaching demos. These scenarios share three traits: they are time-sensitive (demand spikes right before a holiday), theme-specific (New Year, grand opening, wedding, birthday), and they require ready-to-use output, including the horizontal scroll and layout. The system therefore has to do more than generate text: it must generate fast, generate reliably, and export the result.
2. Overall Technical Architecture
A usable intelligent couplet generation service can usually be split into five layers:
- Access layer: a web or mobile page that collects the upper line, a two-character blessing phrase, style, and layout choices.
- Service layer: receives requests, validates parameters, applies rate limiting, assembles prompts, and calls the model capability.
- Generation layer: calls the LLM API to produce the upper line, lower line, and horizontal scroll, with support for returning multiple candidates at once.
- Validation layer: rule-based filtering and scoring for character count, parts of speech, repeated characters, hezhang, and horizontal scroll length.
- Presentation layer: font rendering, horizontal scroll direction layout, and image export.
The validation layer is the easiest to overlook and the one that most affects user experience. A “generate, validate, retry or fall back” loop is preferable to handing raw output straight to the user.
interface CoupletRequest {theme?: string; // Theme words, e.g. "auspicious", "good health"upperLine?: string; // Upper linestyle: 'classical' | 'modern';candidateCount: number;scrollDirection: 'left-to-right' | 'right-to-left';font: 'brush' | 'kai' | 'song';}interface CoupletResult {upper: string;lower: string;horizontal: string; // Horizontal scrollscore: number; // Rule validation score}
3. Prompt and Constraint Design
The ceiling on couplet quality is largely set by prompt structure. It helps to split constraints explicitly into four groups: task definition, hard rules, style instructions, and output format.
- Hard rules: the two lines must have exactly the same character count; avoid reusing the same characters and the same imagery across lines; the horizontal scroll is four characters; no explanatory text.
- Style instructions: classical style leans on literary imagery and allusions, while modern style favors colloquial, everyday expression.
- Output format: return structured data so the program can parse it and handle multiple candidates.
Illustrative prompt (pseudocode):
You are a Chinese couplet writing assistant.Task: generate one couplet and a horizontal scroll from the input.Hard constraints:1) The upper and lower lines must have exactly the same character count;2) The two lines must not share any identical character; avoid hezhang;3) The horizontal scroll must be exactly four characters;4) Output JSON only, with no extra explanation.Style: {classical|modern}Input: {theme or upperLine}Output: {"upper":"","lower":"","horizontal":""}
In practice, keep temperature in a low range for stability. Replacing “generate once and return” with “multiple candidates plus rule-based scoring” significantly reduces the failure rate.
4. Rule-Based Validation of Parallelism
Even a strong model still needs rule-based validation. Practical checks include:
- Length check: identical character counts for the two lines, four characters for the horizontal scroll.
- Repetition check: count characters shared by both lines; a high overlap signals hezhang risk.
- Part-of-speech alignment: use general-purpose tokenization and POS tagging to check whether key positions match.
- Tonal reference: approximate judgment against a general tone table, used as a scoring item rather than a hard block, to avoid rejecting good couplets.
- Semantic relevance: general text embedding similarity to measure how well the result fits the theme.
function validate(c: CoupletResult): number {let s = 0;if (c.upper.length === c.lower.length) s += 40; else s -= 100;if (c.horizontal.length === 4) s += 20;const overlap = intersection(c.upper, c.lower).size;s += overlap === 0 ? 20 : -overlap * 5;s += partOfSpeechAligned(c.upper, c.lower) ? 20 : 0;return s;}
5. Multilingual UI and Responsive Experience
For a public-facing tool, front-end experience directly affects retention. A responsive layout is recommended: on mobile, make sure the input area, result area, and export button are reachable within the first screen; on desktop, show multiple candidates side by side for easy comparison. Multilingual UI can be implemented with unified copy resources and language pack switching, with attention to fallback strategies for Chinese fonts and vertical layout across language environments.
6. Font Rendering and Image Export
A calligraphic feel is a key differentiator for a couplet product. Render the text onto a canvas, load a calligraphy-style font, draw the upper line, lower line, and horizontal scroll, then decide the placement order based on the scroll direction (right-to-left or left-to-right) and export to an image. Three things need attention: font licensing compliance, adaptive scaling for long text, and export resolution plus margin ratio.
function renderToImage(c: CoupletResult, opt: RenderOptions): Promise<Blob> {const canvas = createCanvas(opt.width, opt.height);drawVerticalText(canvas, c.upper, opt.upperRect, opt.font);drawVerticalText(canvas, c.lower, opt.lowerRect, opt.font);drawHorizontalText(canvas, c.horizontal, opt.horizontalRect, opt.font, opt.scrollDirection);return canvas.toBlob('image/png');}
7. Performance, Cost, and Stability
For generation apps, resource consumption concentrates in model calls. Common optimizations include result caching (identical theme and style hit the cache and return immediately), rate limiting and queue-based peak shaving, dynamic reduction of candidate counts (return a single result at peak times), and timeout fallback to a template library. For self-hosted deployments, a container platform can run the stateless service, object storage can hold exported images, and logging plus monitoring with alerts can track call success rate and latency distribution.
8. Common Failure Modes and Workarounds
- Hezhang: the two lines repeat the same meaning. Explicitly forbid repeated imagery and run an overlap check.
- Character count drift: the model occasionally adds or drops a character. Enforce hard constraints and retry on length validation failure.
- Mixed styles: classical and modern writing bleed together. Keep the style instruction singular, one style per request.
- Off-topic horizontal scroll: the scroll disconnects from the couplet’s meaning. Have the model fix the theme words first, then generate the scroll.
9. Conclusion
The core competitiveness of intelligent couplet generation lies not in whether it can generate, but in whether it can reliably produce ready-to-use output. Combining the LLM’s semantic capability, the deterministic validation of a rule engine, and front-end layout and export completes the loop for real scenarios such as holiday celebrations and cultural event planning. Teams that want to validate quickly can build a minimal local loop first, then add caching, rate limiting, and monitoring step by step into a sustainable creative assistance tool.
