AI 与诗词生成从语言模型到意境表达当算法遇见古典文学的跨界实验一、AI 诗词生成的工程困境格律合规与意境表达的鸿沟大语言模型在自由文本生成上表现优异但中文古典诗词生成面临独特挑战格律约束平仄、押韵、对仗是硬性规则意境表达是软性审美。现有 LLM 生成的诗词往往格律错乱——该平声处用了仄声该押韵处韵脚不一致更遑论对仗工整。根本原因在于LLM 的训练目标是最小化 Token 级别的交叉熵而非学习诗词的格律规则与审美范式。AI 诗词生成的工程价值不仅在于自动写诗更在于探索结构化约束下的语言生成——如何在严格规则框架内保持语义连贯与审美表达。这一问题与代码生成语法约束下的逻辑表达、数学证明逻辑约束下的推理表达具有同构性。理解 AI 诗词生成的技术路径对结构化文本生成具有普遍参考意义。二、诗词生成的技术架构与约束注入flowchart TD A[用户输入主题/意象] -- B[诗词生成引擎] subgraph 约束层 C[格律约束: 平仄模板] D[押韵约束: 韵书检索] E[对仗约束: 词性对齐] end B -- C B -- D B -- E subgraph 生成策略 F[约束解码: 每步检查格律] G[模板填充: 先定骨架再填词] H[后处理校验: 生成后修正] end C -- F C -- G D -- H subgraph 意境评估 I[语义连贯性: 句间逻辑] J[意象丰富度: 感官词汇密度] K[审美评分: 对比学习模型] end F -- I G -- J H -- K subgraph 训练数据构建 L[全唐诗/全宋词语料] M[格律标注: 平仄/韵脚] N[质量筛选: 去除残缺/重复] end L -- M -- N -- B三种约束注入策略的对比约束解码在每个 Token 生成时检查格律合规性精度最高但搜索空间受限模板填充先确定诗词骨架平仄模板 韵脚位置再逐字填词效率高但灵活性低后处理校验生成后修正违规字词最灵活但修正可能破坏语义连贯。三、工程实现约束驱动的诗词生成系统# poetry_generator.py — 约束驱动的中文古典诗词生成系统 import json from dataclasses import dataclass from typing import List, Optional, Dict, Set from enum import Enum class ToneType(Enum): 声调类型平声与仄声 PING ping # 平声 ZE ze # 仄声 dataclass class PoetryTemplate: 诗词格律模板 name: str # 诗体名称如七言绝句 line_count: int # 句数 chars_per_line: int # 每句字数 tone_pattern: List[List[ToneType]] # 平仄模板 rhyme_positions: List[int] # 押韵句索引0-based rhyme_group: Optional[str] None # 韵部 # 七言绝句的平仄模板仄起首句入韵式 QIJUE_TEMPLATE PoetryTemplate( name七言绝句, line_count4, chars_per_line7, tone_pattern[ [ToneType.ZE, ToneType.ZE, ToneType.PING, ToneType.PING, ToneType.ZE, ToneType.ZE, ToneType.PING], [ToneType.PING, ToneType.PING, ToneType.ZE, ToneType.ZE, ToneType.PING, ToneType.PING, ToneType.ZE], [ToneType.PING, ToneType.PING, ToneType.ZE, ToneType.ZE, ToneType.PING, ToneType.PING, ToneType.ZE], [ToneType.ZE, ToneType.ZE, ToneType.PING, ToneType.PING, ToneType.ZE, ToneType.ZE, ToneType.PING], ], rhyme_positions[0, 1, 3], # 首句、二句、四句押韵 ) class ToneDictionary: 声调字典查询汉字的平仄属性 def __init__(self): # 简化版声调映射实际工程需加载完整平水韵表 self._tone_map: Dict[str, ToneType] {} self._rhyme_groups: Dict[str, Set[str]] {} def load(self, tone_file: str, rhyme_file: str) - None: 加载声调表与韵书 with open(tone_file, r, encodingutf-8) as f: for line in f: char, tone line.strip().split(\t) self._tone_map[char] ToneType(tone) with open(rhyme_file, r, encodingutf-8) as f: data json.load(f) for group, chars in data.items(): self._rhyme_groups[group] set(chars) def get_tone(self, char: str) - Optional[ToneType]: return self._tone_map.get(char) def get_rhyme_group(self, char: str) - Optional[str]: for group, chars in self._rhyme_groups.items(): if char in chars: return group return None def chars_with_tone(self, tone: ToneType) - List[str]: return [c for c, t in self._tone_map.items() if t tone] def chars_in_rhyme_group(self, group: str) - List[str]: return list(self._rhyme_groups.get(group, set())) class ConstrainedPoetryGenerator: 约束驱动的诗词生成器 def __init__( self, tone_dict: ToneDictionary, llm_clientNone, ): self.tone_dict tone_dict self.llm_client llm_client def generate_with_template( self, theme: str, template: PoetryTemplate, temperature: float 0.8, ) - Optional[str]: 模板填充法先确定韵脚再逐句生成 策略先选定韵部与韵脚字再按格律模板逐字约束生成。 每个位置只允许符合平仄要求的字词大幅缩小搜索空间。 # Step 1: 确定韵部与韵脚字 rhyme_chars self._select_rhyme_chars(theme, template) if not rhyme_chars: return None # Step 2: 逐句生成每字检查平仄约束 lines [] for line_idx in range(template.line_count): line self._generate_line( themetheme, line_idxline_idx, templatetemplate, rhyme_charsrhyme_chars, prev_lineslines, temperaturetemperature, ) if line is None: return None lines.append(line) return \n.join(lines) def _select_rhyme_chars( self, theme: str, template: PoetryTemplate ) - Optional[Dict[int, str]]: 为主题选择韵脚字 # 基于主题生成候选韵脚 prompt f请为主题{theme}的{template.name}选择{len(template.rhyme_positions)}个押韵的字要求意境贴切。 # 实际工程中调用 LLM 生成候选此处简化 candidate_chars self.tone_dict.chars_with_tone(ToneType.PING) # 从候选中选择同韵部的字 rhyme_group None selected {} for pos in template.rhyme_positions: for char in candidate_chars: group self.tone_dict.get_rhyme_group(char) if group is None: continue if rhyme_group is None: rhyme_group group if group rhyme_group and char not in selected.values(): selected[pos] char break if pos not in selected: return None return selected def _generate_line( self, theme: str, line_idx: int, template: PoetryTemplate, rhyme_chars: Dict[int, str], prev_lines: List[str], temperature: float, ) - Optional[str]: 生成单句逐字约束平仄 tone_pattern template.tone_pattern[line_idx] chars [] for pos, required_tone in enumerate(tone_pattern): # 韵脚位置使用预选的韵脚字 if line_idx in rhyme_chars and pos template.chars_per_line - 1: chars.append(rhyme_chars[line_idx]) continue # 获取符合平仄要求的候选字 candidates self.tone_dict.chars_with_tone(required_tone) if not candidates: return None # 构建 LLM 提示约束输出必须为候选字之一 context .join(chars) prompt ( f主题{theme}\n f前文{.join(prev_lines)}\n f当前句已生成{context}__\n f当前位置需要{required_tone.value}声字 f请从候选中选择最贴切的一个字。 ) # 实际工程中调用 LLM此处简化 chars.append(candidates[0]) return .join(chars) def validate_poem( self, poem: str, template: PoetryTemplate ) - Dict[str, bool]: 校验诗词是否满足格律约束 lines poem.strip().split(\n) results { line_count: len(lines) template.line_count, chars_per_line: all( len(line) template.chars_per_line for line in lines ), tone_correct: True, rhyme_correct: True, } # 校验平仄 for line_idx, line in enumerate(lines): for pos, char in enumerate(line): actual_tone self.tone_dict.get_tone(char) expected_tone template.tone_pattern[line_idx][pos] if actual_tone ! expected_tone: results[tone_correct] False break # 校验押韵 rhyme_chars [] for pos in template.rhyme_positions: if pos len(lines): rhyme_chars.append(lines[pos][-1]) groups [ self.tone_dict.get_rhyme_group(c) for c in rhyme_chars ] if len(set(groups)) 1: results[rhyme_correct] False return results四、AI 诗词生成的边界与权衡格律合规与语义连贯的冲突严格的约束解码确保每个字都符合平仄要求但极大缩小了候选空间导致语义不连贯——凑字现象严重。模板填充法缓解了这一问题但灵活性不足。工程实践中需要在格律严格度与语义质量间权衡可放宽一三五不论位置的平仄约束古典诗词本身允许仅严格约束关键位置。训练数据的质量瓶颈古典诗词语料全唐诗约 5 万首、全宋词约 2 万首相对 LLM 训练数据极为稀少。微调 LLM 时容易过拟合生成内容倾向于复制训练集中的句子。数据增强策略同义替换、意象扩展可部分缓解但增强后的数据质量难以保证。意境评估的客观性缺失格律合规可程序化校验但意境好坏缺乏客观度量。基于对比学习的审美评分模型需要大量人工标注的偏好数据标注成本高且主观性强。当前工程实践采用间接指标语义连贯性分数、意象密度、与经典作品的相似度近似评估但与人类审美判断仍有差距。文化敏感性与伦理考量AI 生成的诗词可能无意中组合出具有特定文化含义的句子在特定语境下产生误解。部署诗词生成系统时需对输出内容做文化敏感性过滤。五、总结AI 诗词生成的核心挑战在于结构化约束格律规则与自由表达意境创造的平衡。三种约束注入策略——约束解码、模板填充、后处理校验——在精度与灵活性间提供不同权衡。工程落地的关键在于利用一三五不论规则放宽非关键位置的平仄约束以扩大搜索空间、通过韵书与声调字典构建硬约束保障格律合规、间接指标近似评估意境质量。AI 诗词生成不是要替代诗人而是探索结构化约束下语言生成的技术边界——这一问题的解法对代码生成、数学证明等结构化文本生成任务具有方法论参考价值。
AI 与诗词生成:从语言模型到意境表达,当算法遇见古典文学的跨界实验
AI 与诗词生成从语言模型到意境表达当算法遇见古典文学的跨界实验一、AI 诗词生成的工程困境格律合规与意境表达的鸿沟大语言模型在自由文本生成上表现优异但中文古典诗词生成面临独特挑战格律约束平仄、押韵、对仗是硬性规则意境表达是软性审美。现有 LLM 生成的诗词往往格律错乱——该平声处用了仄声该押韵处韵脚不一致更遑论对仗工整。根本原因在于LLM 的训练目标是最小化 Token 级别的交叉熵而非学习诗词的格律规则与审美范式。AI 诗词生成的工程价值不仅在于自动写诗更在于探索结构化约束下的语言生成——如何在严格规则框架内保持语义连贯与审美表达。这一问题与代码生成语法约束下的逻辑表达、数学证明逻辑约束下的推理表达具有同构性。理解 AI 诗词生成的技术路径对结构化文本生成具有普遍参考意义。二、诗词生成的技术架构与约束注入flowchart TD A[用户输入主题/意象] -- B[诗词生成引擎] subgraph 约束层 C[格律约束: 平仄模板] D[押韵约束: 韵书检索] E[对仗约束: 词性对齐] end B -- C B -- D B -- E subgraph 生成策略 F[约束解码: 每步检查格律] G[模板填充: 先定骨架再填词] H[后处理校验: 生成后修正] end C -- F C -- G D -- H subgraph 意境评估 I[语义连贯性: 句间逻辑] J[意象丰富度: 感官词汇密度] K[审美评分: 对比学习模型] end F -- I G -- J H -- K subgraph 训练数据构建 L[全唐诗/全宋词语料] M[格律标注: 平仄/韵脚] N[质量筛选: 去除残缺/重复] end L -- M -- N -- B三种约束注入策略的对比约束解码在每个 Token 生成时检查格律合规性精度最高但搜索空间受限模板填充先确定诗词骨架平仄模板 韵脚位置再逐字填词效率高但灵活性低后处理校验生成后修正违规字词最灵活但修正可能破坏语义连贯。三、工程实现约束驱动的诗词生成系统# poetry_generator.py — 约束驱动的中文古典诗词生成系统 import json from dataclasses import dataclass from typing import List, Optional, Dict, Set from enum import Enum class ToneType(Enum): 声调类型平声与仄声 PING ping # 平声 ZE ze # 仄声 dataclass class PoetryTemplate: 诗词格律模板 name: str # 诗体名称如七言绝句 line_count: int # 句数 chars_per_line: int # 每句字数 tone_pattern: List[List[ToneType]] # 平仄模板 rhyme_positions: List[int] # 押韵句索引0-based rhyme_group: Optional[str] None # 韵部 # 七言绝句的平仄模板仄起首句入韵式 QIJUE_TEMPLATE PoetryTemplate( name七言绝句, line_count4, chars_per_line7, tone_pattern[ [ToneType.ZE, ToneType.ZE, ToneType.PING, ToneType.PING, ToneType.ZE, ToneType.ZE, ToneType.PING], [ToneType.PING, ToneType.PING, ToneType.ZE, ToneType.ZE, ToneType.PING, ToneType.PING, ToneType.ZE], [ToneType.PING, ToneType.PING, ToneType.ZE, ToneType.ZE, ToneType.PING, ToneType.PING, ToneType.ZE], [ToneType.ZE, ToneType.ZE, ToneType.PING, ToneType.PING, ToneType.ZE, ToneType.ZE, ToneType.PING], ], rhyme_positions[0, 1, 3], # 首句、二句、四句押韵 ) class ToneDictionary: 声调字典查询汉字的平仄属性 def __init__(self): # 简化版声调映射实际工程需加载完整平水韵表 self._tone_map: Dict[str, ToneType] {} self._rhyme_groups: Dict[str, Set[str]] {} def load(self, tone_file: str, rhyme_file: str) - None: 加载声调表与韵书 with open(tone_file, r, encodingutf-8) as f: for line in f: char, tone line.strip().split(\t) self._tone_map[char] ToneType(tone) with open(rhyme_file, r, encodingutf-8) as f: data json.load(f) for group, chars in data.items(): self._rhyme_groups[group] set(chars) def get_tone(self, char: str) - Optional[ToneType]: return self._tone_map.get(char) def get_rhyme_group(self, char: str) - Optional[str]: for group, chars in self._rhyme_groups.items(): if char in chars: return group return None def chars_with_tone(self, tone: ToneType) - List[str]: return [c for c, t in self._tone_map.items() if t tone] def chars_in_rhyme_group(self, group: str) - List[str]: return list(self._rhyme_groups.get(group, set())) class ConstrainedPoetryGenerator: 约束驱动的诗词生成器 def __init__( self, tone_dict: ToneDictionary, llm_clientNone, ): self.tone_dict tone_dict self.llm_client llm_client def generate_with_template( self, theme: str, template: PoetryTemplate, temperature: float 0.8, ) - Optional[str]: 模板填充法先确定韵脚再逐句生成 策略先选定韵部与韵脚字再按格律模板逐字约束生成。 每个位置只允许符合平仄要求的字词大幅缩小搜索空间。 # Step 1: 确定韵部与韵脚字 rhyme_chars self._select_rhyme_chars(theme, template) if not rhyme_chars: return None # Step 2: 逐句生成每字检查平仄约束 lines [] for line_idx in range(template.line_count): line self._generate_line( themetheme, line_idxline_idx, templatetemplate, rhyme_charsrhyme_chars, prev_lineslines, temperaturetemperature, ) if line is None: return None lines.append(line) return \n.join(lines) def _select_rhyme_chars( self, theme: str, template: PoetryTemplate ) - Optional[Dict[int, str]]: 为主题选择韵脚字 # 基于主题生成候选韵脚 prompt f请为主题{theme}的{template.name}选择{len(template.rhyme_positions)}个押韵的字要求意境贴切。 # 实际工程中调用 LLM 生成候选此处简化 candidate_chars self.tone_dict.chars_with_tone(ToneType.PING) # 从候选中选择同韵部的字 rhyme_group None selected {} for pos in template.rhyme_positions: for char in candidate_chars: group self.tone_dict.get_rhyme_group(char) if group is None: continue if rhyme_group is None: rhyme_group group if group rhyme_group and char not in selected.values(): selected[pos] char break if pos not in selected: return None return selected def _generate_line( self, theme: str, line_idx: int, template: PoetryTemplate, rhyme_chars: Dict[int, str], prev_lines: List[str], temperature: float, ) - Optional[str]: 生成单句逐字约束平仄 tone_pattern template.tone_pattern[line_idx] chars [] for pos, required_tone in enumerate(tone_pattern): # 韵脚位置使用预选的韵脚字 if line_idx in rhyme_chars and pos template.chars_per_line - 1: chars.append(rhyme_chars[line_idx]) continue # 获取符合平仄要求的候选字 candidates self.tone_dict.chars_with_tone(required_tone) if not candidates: return None # 构建 LLM 提示约束输出必须为候选字之一 context .join(chars) prompt ( f主题{theme}\n f前文{.join(prev_lines)}\n f当前句已生成{context}__\n f当前位置需要{required_tone.value}声字 f请从候选中选择最贴切的一个字。 ) # 实际工程中调用 LLM此处简化 chars.append(candidates[0]) return .join(chars) def validate_poem( self, poem: str, template: PoetryTemplate ) - Dict[str, bool]: 校验诗词是否满足格律约束 lines poem.strip().split(\n) results { line_count: len(lines) template.line_count, chars_per_line: all( len(line) template.chars_per_line for line in lines ), tone_correct: True, rhyme_correct: True, } # 校验平仄 for line_idx, line in enumerate(lines): for pos, char in enumerate(line): actual_tone self.tone_dict.get_tone(char) expected_tone template.tone_pattern[line_idx][pos] if actual_tone ! expected_tone: results[tone_correct] False break # 校验押韵 rhyme_chars [] for pos in template.rhyme_positions: if pos len(lines): rhyme_chars.append(lines[pos][-1]) groups [ self.tone_dict.get_rhyme_group(c) for c in rhyme_chars ] if len(set(groups)) 1: results[rhyme_correct] False return results四、AI 诗词生成的边界与权衡格律合规与语义连贯的冲突严格的约束解码确保每个字都符合平仄要求但极大缩小了候选空间导致语义不连贯——凑字现象严重。模板填充法缓解了这一问题但灵活性不足。工程实践中需要在格律严格度与语义质量间权衡可放宽一三五不论位置的平仄约束古典诗词本身允许仅严格约束关键位置。训练数据的质量瓶颈古典诗词语料全唐诗约 5 万首、全宋词约 2 万首相对 LLM 训练数据极为稀少。微调 LLM 时容易过拟合生成内容倾向于复制训练集中的句子。数据增强策略同义替换、意象扩展可部分缓解但增强后的数据质量难以保证。意境评估的客观性缺失格律合规可程序化校验但意境好坏缺乏客观度量。基于对比学习的审美评分模型需要大量人工标注的偏好数据标注成本高且主观性强。当前工程实践采用间接指标语义连贯性分数、意象密度、与经典作品的相似度近似评估但与人类审美判断仍有差距。文化敏感性与伦理考量AI 生成的诗词可能无意中组合出具有特定文化含义的句子在特定语境下产生误解。部署诗词生成系统时需对输出内容做文化敏感性过滤。五、总结AI 诗词生成的核心挑战在于结构化约束格律规则与自由表达意境创造的平衡。三种约束注入策略——约束解码、模板填充、后处理校验——在精度与灵活性间提供不同权衡。工程落地的关键在于利用一三五不论规则放宽非关键位置的平仄约束以扩大搜索空间、通过韵书与声调字典构建硬约束保障格律合规、间接指标近似评估意境质量。AI 诗词生成不是要替代诗人而是探索结构化约束下语言生成的技术边界——这一问题的解法对代码生成、数学证明等结构化文本生成任务具有方法论参考价值。