We propose a method to guide Large Language Models (LLMs) in generating structured content adhering to specific conventions without fine-tuning. By utilizing coroutine-based content generation constraints through a pre-agreed context-free grammar (CFG), LLMs are directed during decoding to produce formal language compliant outputs. This enhances stability and consistency in generating target data structures, types, or instructions, reducing application development complexities. Experimentally, error rates of GPT-2 and Gemma exceed 95% for DSLs longer than 36 and 282 tokens, respectively. We introduce YieldLang, a coroutine-based DSL generation framework, and evaluate it with LLMs on various tasks including JSON and Mermaid flowchart generation. Compared to benchmarks, our approach improves accuracy by 1.09 to 11.6 times, with LLMs requiring only about 16.5% of the samples to generate JSON effectively. This enhances usability of LLM-generated content for computer programs.
翻译:我们提出一种无需微调即可引导大型语言模型生成遵循特定约定的结构化内容的方法。通过利用基于协程的内容生成约束(借助预先约定的上下文无关文法),在解码过程中引导语言模型生成符合形式语言规范的输出。该方法提升了生成目标数据结构、类型或指令的稳定性与一致性,降低了应用开发复杂度。实验表明,对于超过36个和282个token的领域特定语言,GPT-2和Gemma的错误率分别超过95%。我们提出了YieldLang——一种基于协程的领域特定语言生成框架,并在包含JSON和Mermaid流程图生成在内的多种任务中结合语言模型进行评测。与基准方法相比,本方法将准确率提升1.09至11.6倍,且语言模型仅需约16.5%的样本即可有效生成JSON。这增强了语言模型生成内容在计算机程序中的可用性。