AI-Powered Chinese Couplet Generation: A Practical Engineering Guide
This article walks through the engineering practice of building an AI system that automatically generates Chinese couplets. It covers the problem definition, a five-layer architecture, prompt orchestration with structured JSON output, rule-based validation and fallback, rendering and export, non-functional design, use cases, and current limitations. Readers will find practical guidance on constraint satisfaction, candidate diversity, theme control, and deployment considerations.
1. Technical Background and Problem Definition
The Chinese couplet is a highly structured literary form: the upper and lower lines must have the same number of characters, matching parts of speech, harmonious tonal patterns, and related but non-repeating semantics, while the horizontal scroll summarizes the theme. This combination of “strict constraints plus high aesthetics” is a strong test of a large language model’s text generation ability—it must satisfy formal rules while keeping the language natural.
From an engineering perspective, couplet generation has to solve four kinds of problems:
- Constraint satisfaction: multiple hard conditions covering character count, parts of speech, structure, and tonal patterns;
- Diversity: a single upper line should return multiple lower-line candidates rather than templated output;
- Theme control: expanding from two-character blessing words (such as “auspicious” or “good health”) to full themed couplets;
- Presentation and delivery: font style, horizontal scroll layout direction, and image export.
2. Overall Architecture
A deployable system is typically split into five layers:
- Access layer: a responsive web interface that adapts to mobile and desktop, with multilingual UI copy;
- Input parsing layer: detects the input type (keyword / upper line / two-character blessing word) and validates length and characters;
- Orchestration layer: assembles prompts, injects style parameters, and controls candidate count and temperature;
- Model invocation layer: calls the large model API for generation, with timeout, retry, and fallback;
- Post-processing and rendering layer: rule validation, formatting, calligraphy font rendering, and image saving.
The orchestration layer is where quality is decided. It is best to separate the “rule description” from the “creative requirements”: the former stays stable, while the latter changes with user parameters.
type CoupletRequest = {mode: 'keyword' | 'upperLine' | 'blessing';input: string; // keyword, upper line, or two-character blessing wordstyle: 'classical' | 'modern';candidates: number; // 1~5 recommendedhorizontalDir: 'ltr' | 'rtl';font: 'brush' | 'kai' | 'song';};const RULE_PROMPT = `You are a couplet writing assistant. Strictly follow:1. Upper and lower lines must have exactly the same character count; the horizontal scroll is 4 characters;2. Parts of speech must match and structures must be symmetrical; avoid repeating characters across the two lines;3. Keep tonal patterns harmonious: the last character of the upper line should be oblique, and the last character of the lower line should be level;4. Output JSON only, with no explanation.`;async function generate(req: CoupletRequest) {const stylePrompt = req.style === 'classical'? 'Style: classical and elegant; allusions are allowed, avoid obscure ones.': 'Style: modern and lively, close to everyday context.';const payload = {system: RULE_PROMPT,user: `${stylePrompt} Input(${req.mode}): ${req.input}; return ${req.candidates} groups with fields upper/lower/horizontal.`};// Call the large model API with a reasonable temperature and timeout/retry settingsreturn await callModelAPI(payload);}
3. Key Implementation Points
1. Prefer structured output. Having the model return JSON instead of natural-language paragraphs significantly reduces post-processing cost and makes it easier for the frontend to render vertical couplets and the horizontal scroll by field.
2. Rule validation as a safety net. Generated results must pass local checks: equal character counts, no repeated characters, and a four-character horizontal scroll. If validation fails, retry once automatically; if it still fails, fall back to a preset generic Spring Festival couplet library to keep the service available.
3. Multiple candidates and deduplication. Increase the candidate count and apply semantic similarity deduplication to avoid pseudo-diversity that only rephrases the same idea.
4. Theme expansion. A two-character blessing word is an extremely short input with little information, so the prompt should add scenario constraints (Spring Festival, business opening, birthday banquet, campus event); otherwise the output tends to be vague.
5. Rendering and export. Calligraphy font rendering is essentially font loading plus Canvas drawing; the horizontal scroll direction is controlled by CSS direction or by drawing order; exported images should be output at 2x to suit high-density screens.
4. Non-Functional Design
- Performance: use streaming or chunked responses at the API layer to reduce time to first character; prepare rendering and generation in parallel;
- Stability: set timeouts and exponential backoff retries for model calls, and configure a fallback content source;
- Cost: cache results for high-frequency keywords and cap the number of candidates per user;
- Security: filter input for length and sensitive content, and keep keys only in server-side environment variables;
- Observability: integrate logging and monitoring with alerts, tracking success rate, latency, and validation failure rate.
For localization or private deployment, a mainstream combination of frontend framework, type system, and build tool can be used; configuring the model API key is enough to run it. In production, add a server-side proxy to avoid exposing the key.
5. Typical Use Cases
Batch Spring Festival couplet generation for holiday celebrations, themed customization for cultural events, interactive display boards for communities and campuses, festival operation material for content platforms, and inspiration support for couplet enthusiasts. The value lies in compressing the chain of “conception—parallelism—writing—delivery” into seconds while preserving room for manual fine-tuning.
6. Limitations and Future Directions
Large models are still unstable at handling tonal patterns, and obscure allusions are prone to errors. It is advisable to add a rule engine for secondary validation and to gradually accumulate domain corpora for fine-tuning or retrieval augmentation. Future work could extend to multimodal input (uploading a scene photo to generate matching lines), or combine with container platforms and object storage to form an elastically scalable online creation service.
