A method and apparatus for progressive generation of a document with dual constraints of theme and template

CN122221826BActive Publication Date: 2026-08-07GUSU LAB OF MATERIALS
View PDF 2 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
GUSU LAB OF MATERIALS
Filing Date
2026-04-27
Publication Date
2026-08-07

AI Technical Summary

Technical Problem

由此,本发明能够在长篇文档生成过程中实现模板结构的严格遵循与进度的精准控制,避免了章节遗漏、顺序错乱及逻辑断层,有效解决了现有技术中结构失控、主题漂移及分步生成缺乏衔接的问题,显著提升了文档生成的正确性与连续性

Benefits of technology

[0014] Fourthly, the present invention also provides a computer-readable storage medium storing a computer program, which, when executed by a processor, implements the progressive document generation method with dual constraints of theme and template provided in the first aspect.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122221826B_ABST
    Figure CN122221826B_ABST
Patent Text Reader

Abstract

The application discloses a document progressive generation method and device with theme and template double constraints, and relates to the technical field of text processing. The method comprises the following steps: acquiring theme constraints and template constraints input by a user, and analyzing and generating a structured template representation; initializing a task, a progress and a final document file; in a main loop, planning a chapter range according to the progress, calling a large language model to generate candidate content, performing progressive checking and clipping insertion on the candidate content, and only writing continuous correct chapters starting from a next to-be-written chapter into the final document, while updating the progress file. The application realizes structured generation under strong template constraints, avoids chapter omission and sequence disorder, reduces model capability dependence, and is suitable for automatic writing of long technical documents.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of text processing technology, and more specifically to a method and apparatus for progressive document generation under dual constraints of theme and template. Background Technology

[0002] With the rapid development of large language models, LLM-based text generation has been widely applied in scenarios such as document writing and report generation. However, in the automatic generation of long documents (such as technical white papers, research reports, and patent specifications), especially in scenarios that require the simultaneous output of multimodal content such as images, charts, and flowcharts, existing technologies still have significant problems. Pure prompt-driven generation methods cannot guarantee that the output document strictly follows the predefined chapter structure, and are prone to problems such as missing chapters, disordered order, and chaotic hierarchy. At the same time, during the generation of long documents, the model is prone to deviating from the user-specified topic or writing requirements, resulting in content that does not match expectations, i.e., structural loss of control and topic drift.

[0003] Limited by the model context window, existing solutions cannot generate extremely long documents in one go, requiring step-by-step generation. However, the lack of effective connections and consistency guarantees between these steps easily leads to logical gaps or content duplication. Furthermore, existing technologies lack real-time verification and reflection mechanisms for generated content; once errors are written, they are difficult to correct, easily resulting in "illusions" or content inconsistent with the knowledge base, leading to uncontrollable overall quality. Regarding multimodal content processing, existing solutions often prioritize text generation, lacking a unified mechanism for controlling the generation, referencing, and insertion of multimodal content such as images, charts, and flowcharts, as well as their correspondence with the chapter structure, making it difficult to create richly illustrated and structurally complete long documents.

[0004] To address the aforementioned issues, existing technical solutions include one-time generation driven by pure prompts, chapter-by-chapter generation after template parsing, and document generation agents equipped with search enhancements. These solutions share common shortcomings: weak template constraints and a lack of rigorous pre-write validation; scattered topic constraints that fail to form a closed loop; a lack of a "progress-template-validation" guarantee mechanism for long-form, step-by-step generation; and a lack of coordinated arrangement between the generation and insertion of multimodal content and the chapter structure. Therefore, there is an urgent need for a method that can achieve progressive, structured generation of long-form multimodal documents under the dual constraints of topic and template, in order to solve the aforementioned technical problems. Summary of the Invention

[0005] The purpose of this invention is to provide a method and apparatus for progressive document generation under dual constraints of theme and template. This method generates a structured template representation by acquiring and parsing template constraints, and tracks completed chapters and the next chapter to be written using a progress log file. In each generation step, the chapter range is planned according to the current progress, and progressive verification, trimming, and insertion are performed on the candidate content generated by the model. Only consecutive correct chapters starting from the next chapter to be written are written to the final document file, while erroneous parts are discarded. Therefore, this invention can achieve strict adherence to the template structure and precise control of progress during the generation of long documents, avoiding chapter omissions, disordered order, and logical breaks. It effectively solves the problems of structural uncontrollability, theme drift, and lack of connection in step-by-step generation in existing technologies, significantly improving the correctness and continuity of document generation.

[0006] To achieve the above objectives, the present invention provides the following technical solution: In a first aspect, the present invention provides a progressive document generation method with dual constraints of theme and template, the method comprising: Obtain the topic constraints and template constraints input by the user. The topic constraints include writing requirements, and the template constraints define the preset chapter structure of the document. Parse template constraints to generate a structured template representation that includes chapter hierarchy and order; Initialize the task configuration file, progress log file, and final document file. The task configuration file records the topic constraints, and the progress log file is used to track completed chapters and the next chapter to be written. Read the task configuration file, template constraints, progress log file, and final document file; Based on the next chapter to be written in the progress log file, and combined with the structured template representation, plan the scope of chapters to be generated this time; The large language model is invoked to generate candidate content corresponding to the chapter range; Perform progressive validation and pruning insertion on candidate content, including: comparing the chapter titles in the candidate content with the structured template representation; when multiple consecutive chapters in the candidate content starting from the next chapter to be written are completely consistent with the template representation, write the multiple consecutive chapters as the correct part into the final document file, and truncate and discard the incorrect parts in the candidate content that are after the correct parts. Once the correct section is successfully written, update the progress log file and reread the task configuration file, template constraints, progress log file, and final document file until all chapters are generated.

[0007] In some embodiments, performing progressive validation and pruning insertion on candidate content further includes: Extract chapter titles and corresponding title level tags from candidate content; The extracted chapter titles and title level tags are compared one by one with the chapter index, title text and hierarchical relationship in the structured template representation; If the comparison reveals that the starting chapter of the candidate content is inconsistent with the next chapter to be written recorded in the progress log file, the writing is rejected and an error message is returned; When the comparison reveals that the heading level or heading text of any chapter in the candidate content is inconsistent with the template representation, the incorrect section is truncated from that chapter.

[0008] In some embodiments, the method further includes: Monitor the status variables during the document generation process. These status variables include the number of words generated in the current chapter, the number of chapters completed since the last reflection, and whether the current chapter contains preset complex elements. When any state variable meets the preset trigger threshold, the reflection tool is invoked. The reflection tool guides the large language model to read the most recently generated content in the final document file, evaluate it from the dimensions of length, logical coherence and boundary clarity, and decide whether to correct the generated content based on the evaluation results.

[0009] In some embodiments, the method further includes: When parsing template constraints, further identify and record the constraint requirements of each chapter for multimodal elements. Multimodal elements include at least one or more of the following: images, statistical charts, flowcharts, and formulas. After planning the scope of the chapters to be generated, one or more multimodal generation tools are called to generate the corresponding multimodal content based on the constraint requirements of the multimodal elements corresponding to the chapter. When writing the correct portion to the final document file, the generated multimodal content is simultaneously inserted into the preset anchor point position in the correct portion.

[0010] In some embodiments, the method further includes: Before or during the generation of candidate content using the large language model, supporting materials are obtained by calling knowledge base retrieval tools or web retrieval tools based on the description of the chapter scope. Large language models are required to use standardized citation formats to mark the sources of supporting materials when generating candidate content; When the search tool returns empty results or cannot obtain valid supporting materials, the large language model is instructed to generate an explicit placeholder at the corresponding candidate content position to prompt the user to supplement the content later, and to prohibit the fabrication of content.

[0011] In some embodiments, initializing the task configuration file, progress log file, and final document file includes: Create a read-only task configuration file; Create a readable and writable progress log file and a final document file; Configure a write interception middleware, which is used to intercept all write operations to the final document file and prevent multiple write tool calls from being executed in parallel in the same round of dialogue.

[0012] Secondly, the present invention also provides a document progressive generation apparatus with dual constraints of theme and template, the apparatus comprising: The constraint acquisition module is used to acquire the topic constraints and template constraints input by the user. The topic constraints include writing requirements, and the template constraints define the preset chapter structure of the document. The constraint parsing module is used to parse template constraints and generate a structured template representation that includes chapter hierarchy relationships and order; The file initialization module is used to initialize the task configuration file, progress log file, and final document file. The task configuration file records the topic constraints, and the progress log file is used to track the completed chapters and the next chapter to be written. The file reading module is used to read task configuration files, template constraints, progress log files, and final document files. The scope generation module is used to plan the scope of the chapters to be generated this time based on the next chapter to be written in the progress log file and in combination with the structured template representation. The content generation module is used to call the large language model to generate candidate content corresponding to the chapter range; The content insertion module is used to perform progressive validation and pruning insertion on candidate content, including: comparing the chapter titles in the candidate content with the structured template representation; when multiple consecutive chapters in the candidate content starting from the next chapter to be written are completely consistent with the template representation, the multiple consecutive chapters are written as the correct part into the final document file; and the incorrect parts in the candidate content that are after the correct parts are truncated and discarded. The loop execution module is used to update the progress log file and reread the task configuration file, template constraints, progress log file and final document file after the correct part is successfully written, until all chapters are generated.

[0013] Thirdly, the present invention also provides an electronic device, including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the computer program to implement the progressive document generation method with dual constraints of theme and template provided in the first aspect.

[0014] Fourthly, the present invention also provides a computer-readable storage medium storing a computer program, which, when executed by a processor, implements the progressive document generation method with dual constraints of theme and template provided in the first aspect.

[0015] Fifthly, the present invention also provides a computer program product, including a computer program that, when executed by a processor, implements the progressive document generation method with dual constraints of theme and template provided in the first aspect.

[0016] The beneficial effects of this invention are as follows: The progressive document generation method with dual constraints of theme and template provided by this invention generates a structured template representation by acquiring and parsing template constraints, and uses a progress log file to track completed chapters and the next chapter to be written. In each generation step, the chapter range is planned according to the current progress, and progressive verification and trimming insertion are performed on the candidate content generated by the model. Only consecutive correct chapters starting from the next chapter to be written are written into the final document file, while erroneous parts are discarded. Therefore, this invention can achieve strict adherence to the template structure and precise control of the progress in the process of generating long documents, avoiding chapter omissions, disordered order, and logical breaks. It effectively solves the problems of structural loss of control, theme drift, and lack of connection in step-by-step generation in the prior art, and significantly improves the correctness and continuity of document generation.

[0017] The above description is merely an overview of the technical solution of the present invention. In order to better understand the technical means of the present invention and to implement it in accordance with the contents of the specification, the preferred embodiments of the present invention are described in detail below with reference to the accompanying drawings. Attached Figure Description

[0018] Figure 1 This is a flowchart illustrating a progressive document generation method with dual constraints of theme and template, as shown in an embodiment of the present invention. Figure 2 This is a schematic diagram of an electronic device structure provided in an embodiment of this application. Detailed Implementation

[0019] The technical solution of the present invention will now be clearly and completely described with reference to the accompanying drawings. Obviously, the described embodiments are only some, not all, of the embodiments of the present invention. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0020] It should be noted that references to "an embodiment," "embodiment," "example embodiment," etc., in this specification refer to the described embodiment including specific features, structures, or characteristics; however, not every embodiment must include these specific features, structures, or characteristics. Furthermore, such expressions do not refer to the same embodiment. Moreover, when describing specific features, structures, or characteristics in conjunction with embodiments, whether or not explicitly described, it is indicated that incorporating such features, structures, or characteristics into other embodiments is within the knowledge of those skilled in the art.

[0021] Furthermore, the technical features involved in the different embodiments of the present invention described below can be combined with each other as long as they do not conflict with each other.

[0022] In some embodiments, such as Figure 1 As shown, a progressive document generation method with dual constraints of theme and template is provided. The specific method includes: S101, Obtain the topic constraints and template constraints input by the user.

[0023] The topic constraints include writing requirements, while the template constraints define the document's preset chapter structure.

[0024] Specifically, this method obtains user-inputted topic constraints and template constraints. Topic constraints refer to the user's writing requirements for the document, such as the document's title, expected total word count, language style (e.g., professional or accessible), or the core viewpoints to be emphasized. Template constraints are a predefined document structure framework, usually described in Markdown format, which includes the document's preset chapter structure, such as headings and their hierarchical relationships, and content descriptions for each chapter. For example, a user might input the topic constraint: "Write a review report on new energy vehicle battery technology, with a word count of around 5000 words, in the style of a technical white paper"; simultaneously, they might input a template defining Chapter 1 as an introduction, Chapter 2 as battery types (divided into 2.1 lithium-ion batteries and 2.2 solid-state batteries), and Chapter 3 as future trends. By simultaneously obtaining these two types of constraints, this method provides a clear writing goal and structural basis for subsequent generation. Therefore, this method avoids the topic drift and structural instability problems that can easily occur when relying on a single prompt.

[0025] S102, parse the template constraints and generate a structured template representation that includes chapter hierarchy relationships and order.

[0026] Specifically, the system invokes a template parsing module. This module can extract structured data from the user-provided Markdown template using either a large language model combined with Pydantic output parsing or regular expression rules. The extraction result is a document template object containing a list of chapters. Each chapter entry records its chapter index (e.g., 1, 1.1, 2), title text (e.g., "Introduction"), hierarchy depth (e.g., first-level heading, second-level heading), and the chapter's order within the document. Simultaneously, the parsing module identifies the constraints each chapter places on multimodal elements; for example, a chapter might require a flowchart or statistical chart. This information is also recorded in the structured template representation. This structured template representation serves as the standard reference for all subsequent write operations, ensuring the unique authority of the chapter order and title format. Thus, this method transforms ambiguous template text into a programmable, precisely comparable data structure, laying the foundation for strong constraint validation.

[0027] S103 initializes the task configuration file, progress log file, and final document file.

[0028] The task configuration file records the theme constraints, while the progress log file is used to track completed chapters and the next chapter to be written.

[0029] Specifically, a read-only task configuration file (e.g., named task.md) is created to record the aforementioned topic constraints (such as writing requirements, word count range, etc.). This file is only read and not modified throughout the generation process. A read-write progress log file (e.g., named progress.md) is created to track the chapters that have been written and the next chapter to be written. Initially, the next chapter to be written is the first chapter in the template. A read-write final document file (e.g., named document.md) is created to store the gradually generated complete document content. In addition, the initialization steps also include configuring a write interception middleware. This middleware is a software module deployed between the document generation agent and the underlying file system. Its function is to intercept all write operations on the final document file (such as write_file, append_file, modify_file, etc. tool calls) and prevent multiple write tool calls from executing in parallel within the same round of communication, thereby avoiding file content corruption or inconsistent state caused by concurrent writes. For example, when the agent simultaneously requests to append content to document.md and modify a paragraph that has already been written in a single response, the middleware will queue these requests and process them sequentially. Through the above initialization, the system establishes a clear division of file responsibilities and a concurrency control mechanism, providing a reliable environment for the stable, step-by-step generation of long documents. Therefore, this method solves the problems of lack of state management and write order guarantees in existing step-by-step generation technologies, effectively preventing error accumulation and content conflicts.

[0030] S104 reads the task configuration file, template constraints, progress log file, and final document file.

[0031] After initialization, the system enters the main loop. First, it reads the task configuration file, template constraints, progress log file, and final document file. Specifically, before each round of execution, the document generation agent retrieves the latest content of these files using a reading tool to obtain the current writing topic, template structure, which chapter has been written, and the generated document text. These files form the core of persistent storage and state management, ensuring that the agent makes decisions based on the latest global state. For example, in a typical loop, the agent reads the progress log file and finds that Chapter 1 is complete, and the next chapter to be written is Section 1 of Chapter 2.

[0032] S105. Based on the next chapter to be written in the progress log file and combined with the structured template representation, plan the scope of chapters to be generated this time.

[0033] For example, suppose the progress log file shows that Chapter 1 is complete, and the next chapter to be written is Chapter 2. In the structured template representation, Chapter 2 contains two subsections, 2.1 and 2.2. The system can plan to generate the entire Chapter 2 (including 2.1 and 2.2) in this iteration, or it can plan to generate only Section 2.1 based on a preset step size (e.g., generating all content under a first-level heading each time) or a word count limit. The planning result is passed to subsequent steps by calling a chapter range retrieval tool, which returns the start and end indices of the chapter to be generated. This dynamic planning approach allows for flexible control of the workload in each round of long document generation, avoiding exceeding the model context window.

[0034] S106, call the large language model to generate candidate content corresponding to the chapter range.

[0035] Specifically, the system constructs a dynamic system prompt, which injects the current progress (list of written chapters, total number of words generated), the scope of chapters to be generated (title and description), topic constraints, and template constraints. The agent calls the large language model based on this prompt, requesting the model to output body content that conforms to the template title format and topic requirements. This content can include text, tables, and instructions to generate images or flowcharts (such as using Mermaid syntax). The candidate content returned by the model is typically a Markdown-formatted text block, which may contain the complete content of one or more chapters. For example, for Section 2.1 "Lithium-ion Batteries," the model might output the title "## 2.1 Lithium-ion Batteries" and several paragraphs, and might even include a Mermaid diagram representing the battery structure.

[0036] S107 performs progressive validation and trimming / insertion on candidate content.

[0037] This step includes: comparing the chapter titles in the candidate content with the structured template representation; when multiple consecutive chapters in the candidate content, starting from the next chapter to be written, are completely consistent with the template representation, the multiple consecutive chapters are written as the correct part into the final document file; and the incorrect parts in the candidate content that are after the correct parts are truncated and discarded.

[0038] Optionally, this step also includes: extracting chapter titles and corresponding heading level markers from the candidate content; comparing the extracted chapter titles and heading level markers with the chapter index, heading text, and hierarchical relationship in the structured template representation one by one; when the comparison finds that the starting chapter of the candidate content is inconsistent with the next chapter to be written recorded in the progress log file, rejecting the writing and returning an error message; when the comparison finds that the heading level or heading text of any chapter in the candidate content is inconsistent with the template representation, using that chapter as the starting point of the erroneous part for truncation.

[0039] Specifically, let's first explain the meaning of progressive validation: it doesn't simply judge the overall correctness of the candidate content, but rather compares it chapter by chapter and title by title with the structured template representation, identifying the continuously correct parts starting from the next chapter to be written, and only writing these parts into the final document. In its implementation, the validation module first extracts all chapter titles and their corresponding heading level markers (such as "#" and "##" symbols in Markdown). Then, it compares these extracted titles and levels one by one with the chapter index, title text, and hierarchical relationships in the structured template representation, while also referring to the next chapter to be written in the progress log file.

[0040] If the comparison reveals that the starting chapter of the candidate content is inconsistent with the next chapter to be written recorded in the progress log file, for example, the next chapter to be written should be section 2.1, but the candidate content starts with section 2.2, the verification module will refuse to write any content and return a tool message containing detailed error information to the agent, prompting the model to regenerate from the correct chapter.

[0041] If the starting chapter of the candidate content is correct, but the title level or title text of a subsequent chapter is inconsistent with the template representation, for example, the template requires the title of Section 2.2 to be "Solid-State Battery", while the model output is "Section 2.2 Novel Battery", then the truncation will be based on the incorrect chapter: all consecutive correct chapters from the next chapter to be written to the incorrect chapter will be retained as the correct part, and the incorrect part and all content thereafter will be discarded.

[0042] For example, if the candidate content includes Section 2.1 (both the title and content are correct) and Section 2.2 (the title is incorrect), the system will write the correct part of Section 2.1 into the final document file, while returning an error message to inform the agent that the title of Section 2.2 does not conform to the template, requiring Section 2.2 to be regenerated. This progressive pruning and insertion mechanism preserves the correct content of the model output to the greatest extent possible, avoiding the inefficient behavior of discarding the entire document or retrying everything due to local errors. Figure 1 The timing process of a single write and progressive verification is shown: the agent initiates an append file call, the middleware forwards the content to the verification module, the verification module performs progressive verification and truncation, returns the correct parts and the error list, and the middleware decides whether to actually write to the file system based on the results. Figure 2 The detailed logic of the verification and judgment steps in the main process is shown. Therefore, this method achieves strong constraint verification before writing, completely solving the problems of weak template constraints and error accumulation in existing technologies. Furthermore, by allowing partially correct content to be written first, it significantly reduces the requirement for large language models to output completely correct results in one go, making it particularly suitable for scenarios involving private deployments or models with small to medium parameter counts.

[0043] S108. Once the correct part has been successfully written, update the progress log file and reread the task configuration file, template constraints, progress log file, and final document file until all chapters have been generated.

[0044] Specifically, after each successful write operation, the system modifies the progress log file, marking the written chapters as completed and updating the next chapter to be written to the subsequent chapters in the template. Then, the main loop jumps to the file reading step to begin a new round of generation. The system continuously repeats the process of planning, generating, verifying, and updating the progress until the progress log file shows that all chapters are completed, at which point the task completion tool is invoked to end the entire task. Through this closed-loop, sustainable generation mechanism, this method can stably generate long documents with rigorous structure and coherent logic.

[0045] In another embodiment, the above method further includes the following process: monitoring state variables during the document generation process, including the number of words generated in the current chapter, the number of chapters completed since the last reflection, and whether the current chapter contains preset complex elements; when any state variable meets a preset trigger threshold, calling the reflection tool, which guides the large language model to read the most recently generated content in the final document file, evaluates it from the dimensions of length, logical coherence, and boundary clarity, and decides whether to correct the generated content based on the evaluation results.

[0046] Specifically, the system monitors state variables during the document generation process. These state variables include: the word count of the current chapter, the number of chapters completed and written since the last reflection, and whether the currently generated chapter contains preset complex elements. Preset complex elements refer to content types that require special handling or are prone to errors, such as images, tables, formulas, and flowcharts. For example, after successfully writing a chapter, the system records the word count for that chapter; it also maintains a counter to record how many chapters have been completed since the last reflection operation; and it checks whether the template description for the current chapter includes requirements such as "Insert flowchart here" or "Contains data table."

[0047] When any state variable meets a preset trigger threshold, the system automatically invokes the reflection tool. The trigger threshold can be pre-configured based on the actual application scenario, such as: the current chapter generates more than 500 words, or the number of chapters completed since the last reflection reaches three, or the current chapter contains complex elements such as images and tables. These thresholds are designed to balance generation quality and computational cost—avoiding excessively frequent reflections that lead to efficiency degradation, while intervening and correcting at critical points. When any of the above conditions are met, for example, if the system detects that the third chapter has been completed and contains a flowchart, the reflection tool is triggered.

[0048] When the reflection tool is invoked, it guides the large language model to read the most recently generated content in the final document file and evaluate it from the dimensions of length, logical coherence, and boundary clarity. Specifically, the reflection tool first obtains the full text of one or more recently written chapters in the final document file through a reading tool. Then, the reflection tool constructs a reflection prompt, requiring the large language model to analyze from three dimensions: first, the length dimension, judging whether the generated content is too long or too short, and whether it meets the word count requirements preset in the task configuration file; second, the logical coherence dimension, checking whether the transitions between chapters are natural, whether the arguments are consistent, and whether there is any repetition or contradiction; and third, the boundary clarity dimension, evaluating whether each chapter focuses on its theme and whether the division of responsibilities with adjacent chapters is clear. For example, when writing a report on battery technology, the reflection tool may find a duplicate discussion on "battery safety performance" between Chapter 2 "Lithium-ion Batteries" and Chapter 3 "Solid-State Batteries," and the large language model will suggest deleting or merging the duplicate content based on the evaluation results.

[0049] Based on the evaluation results, the reflection tool decides whether to revise the generated content. If the evaluation deems the content quality acceptable, no modifications are made, and the system continues the subsequent process. If the evaluation identifies problems, the file editing tool is invoked to fine-tune the corresponding chapters in the final document file, such as deleting redundant paragraphs, adding missing transition sentences, and adjusting the internal structure of chapters. After the revisions are completed, the system updates the relevant information in the progress log file and continues the main loop. Through this condition-triggered reflection mechanism, this method introduces a low-cost, high-efficiency quality closed loop in the long document generation process, avoiding the waste of computational resources caused by reflecting on each generation, while effectively preventing the accumulation of errors and redundancy, and significantly improving the logical coherence and content accuracy of the final document.

[0050] In another embodiment, the method further includes: when parsing template constraints, further identifying and recording the constraint requirements of each chapter for multimodal elements, wherein the multimodal elements include at least one or more of images, statistical charts, flowcharts, and formulas; after planning the scope of the chapters to be generated, calling one or more multimodal generation tools to generate the corresponding multimodal content according to the constraint requirements of the multimodal elements corresponding to the chapter; and when writing the correct part into the final document file, synchronously inserting the generated multimodal content into the preset anchor point position in the correct part.

[0051] Specifically, when processing user-provided Markdown templates, the template parsing module not only extracts chapter titles and hierarchical relationships but also detects whether each chapter description contains special tags or keywords, such as "insert flowchart here," "include battery structure diagram," "generate installation statistics chart for the past five years," or "add formula." The parsing module records these requirements in the structured template representation, attaching a multimodal requirement list to each chapter. Each element in the list includes its type (e.g., image, chart, flowchart, formula), purpose description, and expected insertion position (e.g., after a paragraph or a specific anchor point). For example, if the description of Chapter 2, "Lithium-ion Battery," in the user template includes "insert schematic diagram of lithium-ion battery working principle," the parsing module will recognize this requirement and add a multimodal constraint of type "image" and description "schematic diagram of lithium-ion battery working principle" to Chapter 2 in the structured representation. Thus, this method transforms the requirements of multimodal elements from unstructured text descriptions into programmable structured data, laying the foundation for subsequent automatic generation and insertion.

[0052] Next, after planning the scope of the chapters to be generated, the system calls one or more multimodal generation tools to generate the corresponding multimodal content based on the constraints of the multimodal elements corresponding to that chapter. Specifically, after the agent plans the scope of the chapters to be generated this time (e.g., Chapter 2) based on the progress log file, before or simultaneously calling the large language model to generate candidate text content, the agent checks the multimodal requirement list of that chapter in the structured template representation. If the list is not empty, the agent calls the corresponding multimodal generation tools in sequence. For example, for image requirements, an image generation model (such as a diffusion-based drawing tool) can be called to generate image files based on the chapter description and requirement description; for statistical chart requirements, a data visualization tool (such as generating bar charts or line charts from retrieved numerical data) can be called; for flowchart requirements, a Mermaid code generator or flowchart drawing tool can be called to generate corresponding chart code or images; for formula requirements, a formula generation tool can be called to generate LaTeX format formulas. All generated multimodal content is saved as independent files or code blocks, and its storage path and associated chapter anchor points are recorded. For example, when generating Chapter 2, "Lithium-ion Batteries," the system detects that this chapter requires a schematic diagram of its working principle. Therefore, it uses an image generation tool, inputting the prompt "Lithium-ion battery working principle, positive electrode, negative electrode, electrolyte, separator, charging and discharging process," to generate an image and save it as "figure_2_1.png." Simultaneously, the system can also use a chart generation tool to generate a "2018-2025 Lithium-ion Battery Installation Trend Chart" based on retrieved installed capacity data and save it. In this way, this method achieves automatic matching of multimodal content with chapter semantics, avoiding the tedious manual addition of each section later.

[0053] Then, while writing the correct portion to the final document file, the system synchronously inserts the generated multimodal content into the preset anchor positions within the correct portion. An anchor position is an insertion point pre-marked during the template parsing or text generation phase; it can be a special placeholder (e.g., [Illustration: Working Principle Diagram]) or a specific paragraph mark. During the progressive validation and trimming insertion process, when the validation module confirms that the correct portion of the candidate content (e.g., the complete text of Chapter 2) is ready to be written to the final document file, the agent simultaneously retrieves the multimodal content list corresponding to that chapter and embeds references to images, charts, flowcharts, or formulas into the corresponding positions in the text according to the anchor positions. Embedding methods can include Markdown-formatted image links (e.g., ![Working Principle Diagram](figures / figure_2_1.png)), Mermaid code blocks, LaTeX formula blocks, or HTML chart tags. The final content written to document.md is a complete chapter with both text and images. For example, in Chapter 2, a diagram of the working principle of a lithium-ion battery (figures / figure_2_1.png) is automatically inserted after the paragraph describing the working principle, and statistical charts are inserted after the paragraph describing market trends. Thus, this method ensures consistency between multimodal content and chapter content in terms of contextual semantics, positional order, and formatting, avoiding discrepancies between text and images or incorrect insertion positions.

[0054] Through the aforementioned multimodal content collaborative generation and insertion mechanism, this method expands the final generated document from simple text into a rich media document containing images, charts, flowcharts, and formulas, significantly enhancing the richness and readability of information expression. At the same time, it maintains strict alignment with the template structure and chapter logic, solving the problem in existing technologies where multimodal content is difficult to uniformly arrange into the structure of long documents.

[0055] In another embodiment, the method further includes: before or during the generation of candidate content by calling the large language model, calling a knowledge base retrieval tool or a web retrieval tool to obtain supporting materials according to the description of the chapter scope; requiring the large language model to use a standardized citation format to mark the source of the supporting materials when generating candidate content; and instructing the large language model to generate an explicit placeholder at the corresponding candidate content position to prompt the user for subsequent supplementation when the retrieval tool returns an empty result or cannot obtain valid supporting materials, thereby prohibiting the fabrication of content.

[0056] Specifically, before or during the generation of candidate content using the large language model, the system retrieves supporting materials by calling knowledge base retrieval tools or web retrieval tools based on the description of the chapter scope. Knowledge base retrieval tools refer to the query interface of a pre-built private knowledge base (such as internal enterprise technical documents, patent databases, product manuals, etc.), capable of returning relevant document fragments based on keywords or semantic similarity; web retrieval tools refer to interfaces that obtain publicly available information from the internet in real time through search engines (such as Bing, Google, etc. APIs). After planning the chapter scope to be generated (e.g., Chapter 2, "Lithium-ion Batteries"), the agent extracts key information from the chapter's title and template description, combining them into a search query. This retrieval operation can be performed before the large language model generates candidate content, providing the search results as additional context to the model; alternatively, it can be triggered by the model during the generation process when insufficient information is detected. For example, when generating a paragraph about "Lithium-ion Battery Energy Density" in Chapter 2, the agent automatically calls the knowledge base retrieval tool to query relevant technical information on "Lithium-ion Battery Energy Density 2025," and optionally calls a web retrieval tool to obtain the latest industry report data. The supporting materials returned by the search tool are usually several relevant text snippets, data tables, or literature abstracts. In this way, this method provides verifiable factual evidence for the model, reducing the possibility of fabrication from the outset.

[0057] Meanwhile, the system requires the large language model to use standardized citation formats to mark the sources of supporting materials when generating candidate content. Specifically, when constructing dynamic system prompts, the system will explicitly instruct the model: when you cite a piece of information returned by the retrieval tool, you must add a numerical superscript at the end of the information, such as using the format [1], [2], etc., and correspond one-to-one with the serial number in the retrieval results. When generating candidate content, the model will attach corresponding citation marks to factual statements from knowledge bases or networks. For example, the model generates a sentence such as "According to market research data, the global lithium-ion battery market size will reach US$50 billion in 2025 [2]", where [2] corresponds to the second piece of information in the retrieval results. The system can also automatically generate a list of references at the end of the document based on these citation marks in subsequent processing. Thus, this method ensures the traceability of the generated content, making it easier for users or reviewers to verify the source of information, and further enhancing the credibility and professionalism of the document.

[0058] Furthermore, when the search tool returns empty results or fails to provide valid supporting materials, the system instructs the large language model to generate explicit placeholders at the corresponding candidate content positions to prompt the user for subsequent supplementation, prohibiting the fabrication of content. An explicit placeholder is a text fragment clearly marked as "to be supplemented." In actual implementation, the agent checks the returned result set after calling the search tool. If the result set is empty, or the relevance score of all results is below a preset threshold (i.e., no valid supporting materials can be obtained), the agent adds the instruction to the prompt sent to the large language model: "For the parts of this chapter where supporting materials cannot be found, please do not fabricate content yourself, but instead output a placeholder starting with '[To be supplemented]' in the corresponding position, briefly explaining the type of information that needs to be supplemented." The model follows this instruction, generating placeholders at the corresponding positions of the candidate content instead of fabricating facts. For example, when there are no results for the search for "2026 installation volume of solid-state batteries," the model will output "[To be supplemented: Specific data on the installation volume of solid-state batteries in 2026 has not yet been found in currently available public information]" instead of fabricating a false number. Through this mechanism, this method systematically eliminates the risk of model illusions, ensuring that the generated content is either verifiable or clearly marked as missing and to be supplemented, thereby significantly improving the reliability and controllability of long documents in engineering applications.

[0059] In summary, this method, through retrieval enhancement and explicit placeholder mechanisms, binds the generation of factual information to verifiable external knowledge sources, and enforces citation annotation and prohibits fabrication. It effectively solves the problems of illusion and unreliable content in the generation of long documents in the prior art, and is particularly suitable for scenarios such as technical documents, research reports and patent specifications that require high factual accuracy.

[0060] Based on the same inventive concept, this application also provides a document progressive generation apparatus for implementing the document progressive generation method with dual constraints of theme and template as described above. The solution provided by this apparatus is similar to the implementation described in the above method. Therefore, the specific limitations of one or more embodiments of the document progressive generation apparatus with dual constraints of theme and template provided below can be found in the limitations of the document progressive generation method with dual constraints of theme and template described above, and will not be repeated here.

[0061] In one embodiment, a progressive document generation apparatus with dual constraints of theme and template is provided, the apparatus comprising: The constraint acquisition module is used to acquire the topic constraints and template constraints input by the user. The topic constraints include writing requirements, and the template constraints define the preset chapter structure of the document. The constraint parsing module is used to parse template constraints and generate a structured template representation that includes chapter hierarchy relationships and order; The file initialization module is used to initialize the task configuration file, progress log file, and final document file. The task configuration file records the topic constraints, and the progress log file is used to track the completed chapters and the next chapter to be written. The file reading module is used to read task configuration files, template constraints, progress log files, and final document files. The scope generation module is used to plan the scope of the chapters to be generated this time based on the next chapter to be written in the progress log file and in combination with the structured template representation. The content generation module is used to call the large language model to generate candidate content corresponding to the chapter range; The content insertion module is used to perform progressive validation and pruning insertion on candidate content, including: comparing the chapter titles in the candidate content with the structured template representation; when multiple consecutive chapters in the candidate content starting from the next chapter to be written are completely consistent with the template representation, the multiple consecutive chapters are written as the correct part into the final document file; and the incorrect parts in the candidate content that are after the correct parts are truncated and discarded. The loop execution module is used to update the progress log file and reread the task configuration file, template constraints, progress log file and final document file after the correct part is successfully written, until all chapters are generated.

[0062] This application also provides an electronic device, in some embodiments, referring to... Figure 2 As shown, the electronic device 700 includes an input unit 710, a memory 720, a processor 730, and an output unit 740. The memory 720 stores program instructions that can be executed on the processor 730. The processor 730 can execute the progressive document generation method and / or technical solution based on the dual constraints of theme and template in the foregoing embodiments by calling the program instructions. The electronic device 700 can be a mobile terminal device such as a mobile phone or a computer.

[0063] Furthermore, embodiments of this application also provide a computer-readable storage medium for storing a computer program that performs a progressive document generation method with dual constraints of subject and template. For example, computer program instructions, when executed by a computer, can invoke or provide the methods and / or technical solutions according to this application through the operation of the computer. The program instructions that invoke the methods of this application may be stored in a fixed or removable storage medium, and / or transmitted via data streams in broadcast or other signal carrying media, and / or stored in a storage medium that operates according to the program instructions.

[0064] Obviously, those skilled in the art should understand that the modules or steps of this application described above can be implemented using general-purpose computing devices. They can be centralized on a single computing device or distributed across a network of multiple computing devices. Optionally, they can be implemented using computer-executable program code, thereby storing them in a storage device for execution by a computing device, or fabricating them separately as individual integrated circuit modules, or fabricating multiple modules or steps as a single integrated circuit module. Thus, this application is not limited to any particular combination of hardware and software.

[0065] The technical features of the above embodiments can be arbitrarily integrated. For the sake of brevity, not all possible integrations of the technical features in the above embodiments are described. However, as long as the integration of these technical features does not contradict each other, they should be considered to be within the scope of this specification.

[0066] The above embodiments merely illustrate several implementation methods of the present invention, and their descriptions are relatively specific and detailed, but they should not be construed as limiting the scope of the invention patent. It should be noted that those skilled in the art can make various modifications and improvements without departing from the concept of the present invention, and these all fall within the protection scope of the present invention. Therefore, the protection scope of this invention patent should be determined by the appended claims.

Claims

1. A progressive document generation method with dual constraints of theme and template, characterized in that, The method includes: Obtain the topic constraints and template constraints input by the user. The topic constraints include writing requirements, and the template constraints define the preset chapter structure of the document. Parse the template constraints to generate a structured template representation that includes chapter hierarchy and order; Initialize the task configuration file, progress log file, and final document file, wherein the task configuration file records the topic constraints, and the progress log file is used to track completed chapters and the next chapter to be written; Read the task configuration file, the template constraints, the progress record file, and the final document file; Based on the next chapter to be written in the progress record file, and in conjunction with the structured template representation, the scope of chapters to be generated this time is planned; The large language model is invoked to generate candidate content corresponding to the specified chapter range; The candidate content is subjected to progressive verification and pruning insertion, including: comparing the chapter titles in the candidate content with the structured template representation; when multiple consecutive chapters in the candidate content starting from the next chapter to be written are completely consistent with the template representation, the multiple consecutive chapters are written as the correct part into the final document file, and the incorrect parts in the candidate content that are located after the correct part are truncated and discarded. Once the correct portion is successfully written, update the progress log file and reread the task configuration file, template constraints, progress log file, and final document file until all chapters are generated.

2. The document progressive generation method with dual constraints of theme and template as described in claim 1, characterized in that, Performing progressive validation and pruning insertion on the candidate content also includes: Extract the chapter titles and corresponding title level tags from the candidate content; The extracted chapter titles and title level markers are compared one by one with the chapter index, title text, and hierarchical relationship in the structured template representation; If the comparison reveals that the starting chapter of the candidate content is inconsistent with the next chapter to be written recorded in the progress log file, the writing is rejected and an error message is returned; When the comparison reveals that the title level or title text of any chapter in the candidate content is inconsistent with the template representation, the chapter is used as the starting point for truncation of the erroneous part.

3. The document progressive generation method with dual constraints of theme and template as described in claim 1 or 2, characterized in that, The method further includes: Monitor the status variables during the document generation process. The status variables include the number of words generated in the current chapter, the number of chapters completed since the last reflection, and whether the current chapter contains preset complex elements. When any of the aforementioned state variables meets the preset trigger threshold, the reflection tool is invoked. The reflection tool guides the large language model to read the most recently generated content in the final document file, evaluates it from the dimensions of length, logical coherence, and boundary clarity, and decides whether to correct the generated content based on the evaluation results.

4. The document progressive generation method with dual constraints of theme and template as described in claim 1, characterized in that, The method further includes: When parsing the template constraints, the constraint requirements of each chapter on multimodal elements are further identified and recorded. The multimodal elements include at least one or more of the following: images, statistical charts, flowcharts, and formulas. After planning the scope of the chapters to be generated, one or more multimodal generation tools are invoked to generate the corresponding multimodal content based on the constraint requirements of the multimodal elements corresponding to the chapters. When writing the correct portion into the final document file, the generated multimodal content is simultaneously inserted into the preset anchor point position in the correct portion.

5. The document progressive generation method with dual constraints of theme and template as described in claim 1 or 4, characterized in that, The method further includes: Before or during the generation of the candidate content by calling the large language model, supporting materials are obtained by calling knowledge base retrieval tools or web retrieval tools according to the description of the chapter scope; The large language model is required to use a standardized citation format to mark the source of the supporting materials when generating the candidate content; When the retrieval tool returns an empty result or cannot obtain valid supporting materials, it instructs the large language model to generate an explicit placeholder at the corresponding candidate content position to prompt the user to supplement the content later, and prohibits the fabrication of content.

6. The document progressive generation method with dual constraints of theme and template as described in claim 1, characterized in that, Initialize the task configuration file, progress log file, and final document file, including: Create a read-only configuration file for the task; Create a readable and writable progress log file and a final document file; Configure a write interception middleware, which is used to intercept all write operations on the final document file and prevent multiple write tool calls from being executed in parallel during the same round of dialogue.

7. A progressive document generation device with dual constraints of theme and template, characterized in that, The device includes: The constraint acquisition module is used to acquire the topic constraints and template constraints input by the user. The topic constraints include writing requirements, and the template constraints define the preset chapter structure of the document. The constraint parsing module is used to parse the template constraints and generate a structured template representation containing chapter hierarchy relationships and order; The file initialization module is used to initialize the task configuration file, progress log file and final document file, wherein the task configuration file records the topic constraints and the progress log file is used to track the completed chapters and the next chapter to be written. The file reading module is used to read the task configuration file, the template constraints, the progress record file, and the final document file. The scope generation module is used to plan the scope of the chapter to be generated this time based on the next chapter to be written in the progress record file and the structured template representation. The content generation module is used to call the large language model to generate candidate content corresponding to the chapter range; The content insertion module is used to perform progressive verification and pruning insertion on the candidate content, including: comparing the chapter titles in the candidate content with the structured template representation; when multiple consecutive chapters in the candidate content starting from the next chapter to be written are completely consistent with the template representation, the multiple consecutive chapters are written as the correct part into the final document file, and the incorrect parts in the candidate content that are located after the correct part are truncated and discarded. The loop execution module is used to update the progress record file and reread the task configuration file, the template constraints, the progress record file and the final document file after the correct part is successfully written, until all chapters are generated.

8. An electronic device comprising a memory, a processor, and a computer program stored in the memory and running on the processor, characterized in that, When the processor executes the computer program, it implements the progressive document generation method with dual constraints of theme and template as described in any one of claims 1 to 6.

9. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores a computer program that, when executed by a processor, implements the progressive document generation method with dual constraints of theme and template as described in any one of claims 1 to 6.

10. A computer program product, comprising a computer program, characterized in that, When executed by a processor, the computer program implements the progressive document generation method with dual constraints of theme and template as described in any one of claims 1 to 6.

Citation Information

Patent Citations

  • Question and answer generation method and device based on reference verification and similarity constraint, medium and program product

    CN120611032A

  • System and method for applying dynamic contextual grammars and language models to improve automatic speech recognition accuracy

    US20070233488A1