Document generation method and system for anti-model hallucination

By extracting text feature vectors to match target style templates and performing anti-illusion cleaning, the structural distortion problem caused by large language models in document generation is solved, realizing automatic adaptation of style templates and data content and improving the quality of document generation.

CN123050382APending Publication Date: 2026-11-06FUJIAN TQ DIGITAL
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202610980732.4
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-07-02
Publication Date
2026-11-06

AI Technical Summary

Technical Problem

Existing technologies are prone to structural distortions and style loss caused by large language model typesetting illusions when converting unstructured text into complex enterprise-level structured documents. Existing converters cannot effectively repair these issues, resulting in a decline in document generation quality.

Method used

By extracting the text feature vectors from the initial data, the target style template is obtained from the preset structured template library. Unstructured text is generated by combining the initial data and preset layout isolation rules, and anti-model illusion cleaning is performed. The initial document is generated and a directory structure is added to ensure automatic adaptation between the style template and the data content.

Benefits of technology

It effectively suppresses the typesetting illusion of large language models, avoids non-standard extended tags and tag symbol distortion, ensures document generation quality, and guarantees the consistency of directory field document structure and the clarity of document generation hierarchy.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123050382A_ABST
    Figure CN123050382A_ABST
Patent Text Reader

Abstract

This application provides a document generation method and system to resist model illusion. The method receives initial data input by a user, extracts text feature vectors from the initial data, and obtains a target style template from a preset structured template library based on the text feature vectors. Based on the initial data, the target style template, and preset layout isolation rules, a large language model is invoked to generate a first unstructured text. The first unstructured text undergoes anti-model illusion cleaning processing to obtain a second unstructured text. An initial document is generated based on the second unstructured text and the target style template. A final document is generated based on the initial document and preset table of contents generation rules. This method enables automatic adaptation of style templates during document generation and avoids structural distortions caused by large language model layout illusions, thus ensuring document generation quality.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of document generation technology, and in particular to a document generation method and system that combats model illusion. Background Technology

[0002] In existing automated document generation processes, large language models are typically used to generate unstructured text (such as Markdown format), which is then converted into OOXML format (.docx files) conforming to enterprise office standards using basic document converters (such as standard Pandoc or common Markdown-to-Word open-source libraries). To enable the model to learn specific formatting styles, existing technologies often employ a few-sample prompting method, allowing the large language model to imitate a given reference template.

[0003] However, this technology suffers from a fatal flaw when processing the conversion from unstructured text to complex enterprise-level structured documents: the "typography illusion" generated by the large language model leads to the failure of the underlying abstract syntax tree construction and the loss of styles. Specifically, when the model attempts to mimic complex reference templates, it is prone to fabricating non-standard extended tags (such as {.underline}) out of thin air, or inserting tabs or spaces inside the tags to forcibly align column widths in plain text (such as splitting bold `` into ``). Existing document converters can only perform mechanical grammatical translation and cannot understand and repair these structural distortions caused by the illusion. When these contaminated text input conversion engines are used, the underlying abstract syntax tree parser cannot identify the distorted nodes, causing the tags to leak as garbled text into the final document, while the underlying style mapping of the target document (such as heading levels, dynamic table of contents codes, etc.) breaks. Summary of the Invention

[0004] The technical problem to be solved by this invention is to provide a document generation method and system that is resistant to model illusion, which can realize automatic adaptation of style templates during the document generation process, avoid structural distortion caused by large language model typesetting illusion, and ensure the quality of document generation.

[0005] To solve the above-mentioned technical problems, the technical solution adopted by the present invention is as follows: A document generation method to combat model illusion includes: Receive initial data input by the user, extract the text feature vector of the initial data, and obtain the target style template of the initial data from a preset structured template library based on the text feature vector; Based on the initial data, the target style template, and the preset layout isolation rules, the large language model is called to generate the first unstructured text, and the first unstructured text is subjected to anti-model illusion cleaning processing to obtain the second unstructured text. An initial document is generated based on the second unstructured text and the target style template, and a final document is generated based on the initial document and preset directory generation rules.

[0006] To solve the above-mentioned technical problems, another technical solution adopted by the present invention is as follows: A document generation system for resisting model illusion includes 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 various steps of the aforementioned document generation method for resisting model illusion.

[0007] The beneficial effects of this invention are as follows: By extracting the text feature vector of the initial data and obtaining the target style template from the preset structured template library based on the feature vector, the automatic adaptation of the style template and the data content is achieved; based on the initial data, the target style template, and the preset typesetting isolation rules, the large language model is called to generate the first unstructured text, and the first unstructured text is subjected to anti-model illusion cleaning processing to obtain the second unstructured text, which effectively suppresses the typesetting illusion of the large language model and avoids the generation of non-standard extended tags and tag symbol distortion; based on the second unstructured text and the target style template, the initial document is generated, and the final document is generated in combination with the preset directory generation rules, which can automatically construct a document with clear hierarchy and regular structure, ensure the consistency of the document structure in the directory field, and improve the quality of document generation. Attached Figure Description

[0008] Figure 1 A flowchart illustrating a document generation method for combating model illusion according to an embodiment of the present invention; Figure 2 This is a schematic diagram of a document generation system for resisting model illusion according to an embodiment of the present invention. Detailed Implementation

[0009] Definitions:

[0010] To explain in detail the technical content, objectives, and effects of the present invention, the following description is provided in conjunction with the embodiments and accompanying drawings.

[0011] In existing technologies, automated generation solutions for enterprise-level office documents (such as .docx files) typically involve first outputting unstructured text through a large language model, and then calling a document conversion tool to directly convert it into a .doc file conforming to the OOXML specification. Furthermore, to ensure the generated result conforms to a specific formatting, existing technologies guide the large language model to mimic a given reference template through a few example prompts. However, this method has certain limitations: when "mimicking" complex layouts, the large language model generates numerous unpredictable formatting illusions. For example, the model may spontaneously create non-standard extended tags, or intentionally embed invisible cells or tabs within tags to achieve visual alignment at the plain text level. Because existing converters can only perform mechanical grammatical translation, they cannot understand and correct these structural distortions caused by these illusions, resulting in messy document styles and garbled content, thus reducing document generation quality.

[0012] To at least address the aforementioned issues, textual features are extracted from the initial user input data. These features are then used to match the target style template from a pre-defined structured template library. Combining the initial data, the target style template, and pre-defined layout isolation rules, a large language model is invoked to generate a first unstructured text. This unstructured text is then cleaned against type illusions to obtain a second unstructured text. An initial document is generated based on this second unstructured text and the target style template. A table of contents is then added to the initial document according to pre-defined table of contents generation rules, resulting in the final document. This approach enables automatic style template adaptation during document generation and avoids structural distortions caused by type illusions in the large language model, thus ensuring document generation quality.

[0013] The following details a document generation method for combating model hallucinations according to the present invention. Please refer to [link / reference]. Figure 1 The method 100 includes steps 101 to 103: Step 101: Receive initial data input by the user, extract the text feature vector of the initial data, and obtain the target style template of the initial data from a preset structured template library based on the text feature vector.

[0014] Specifically, the system receives initial data input by the user and extracts its text feature vector. This text feature vector is a composite vector, including the TF-IDF weights of business keywords (such as "development" and "level") and the distribution of structural features (such as the estimated number of tables). The system has a pre-built structured template library containing multiple pre-configured 'styles.xml' files (defining underlying styles such as titles and body text), i.e., style templates. The system uses a cosine similarity algorithm to calculate the matching degree between the text feature vector and each style template in the template library, automatically routing and locking the style template with the highest matching degree as the target style template. In this way, the problem of "uniformly applying a single template" in traditional conversion is solved, ensuring that the subsequently generated text is strictly aligned in its underlying structure with the layout specifications of the specific business scenario described by the initial data.

[0015] Step 102: Based on the initial data, the target style template, and the preset layout isolation rules, call the large language model to generate the first unstructured text, and perform anti-model illusion cleaning processing on the first unstructured text to obtain the second unstructured text.

[0016] Specifically, the system parses the target style template into plain text, and together with the initial input data, constructs a system prompt (i.e., a text generation instruction). Pre-defined layout isolation rules are forcibly injected into the prompt (e.g., explicitly prohibiting the use of grid table algorithms and mandating the use of standard vertical line table algorithms). The system calls the large language model, outputs the first unstructured text, and performs anti-model illusion cleaning processing on the first unstructured text according to the regularity rules in the pre-defined regularity library list, resulting in the second unstructured text. In this way, the layout illusion of the large language model can be effectively suppressed, avoiding the generation of non-standard extended tags and tag distortion, thus ensuring the quality of document generation.

[0017] Step 103: Generate an initial document based on the second unstructured text and the target style template, and generate a final document based on the initial document and the preset directory generation rules.

[0018] Specifically, the second unstructured text is parsed into an abstract syntax tree, and this abstract syntax tree is mapped to the target style template to generate the initial document. This ensures consistency between the style and the underlying syntax tree during the conversion of unstructured text to structured document, avoiding markup leakage and style mapping breakage. Based on the abstract syntax tree and preset directory generation rules, directory field codes are generated, and combined with the initial document to generate the final document. This achieves automatic construction of dynamic directory field codes, ensuring consistency between dynamic directory field codes and document structure, and improving document generation quality.

[0019] In one embodiment of the present invention, step 101 includes steps 1011 and 1012: Step 1011: Extract the structural and semantic features of the initial data, generate a text feature vector of the initial data based on the structural and semantic features, and normalize each dimension of the text feature vector.

[0020] Specifically, the initial data might be a requirement description or a semi-structured draft. Structural features include document length, heading hierarchy distribution, table density, list item density, number of code blocks, bold / emphasis density, and link density. The extraction methods for each structural and semantic feature are as follows: Document length is determined by directly counting the number of characters in the text, used to distinguish between short documents (such as weekly reports) and long documents (such as architecture design documents); Heading hierarchy distribution is determined by counting the number of #, ##, and ### characters in the Markdown / text, forming a 3D vector [h1_count, h2_count, ...]. [h3_count] reflects the depth and complexity of the document skeleton; table density, calculated as "number of tables / total number of characters in the document × 10000", is used to determine whether the document is a data dictionary or comparative analysis; list item density, calculated as "number of unordered and ordered list items / total number of characters × 10000", is used to determine whether the document is an operation procedure or checklist; code block count, counts the number of ``` pairs, where ``` are the start and end markers of code blocks in Markdown syntax, used to determine whether the document is a technical design or API document; bold / emphasis density, calculated as "number of occurrences of ** and __ / total number of characters × 10000", is used to help determine the emphasis style of the document; link density, calculated as "number of [text](url) patterns / total number of characters × 10000", is used to determine whether the document is a summary of references; semantic feature vector, extracts the TF-IDF word frequency vector of the document and reduces the dimensionality to a fixed length, such as 64 dimensions, to match the document content theme, such as "architecture", "database", "front-end", etc.

[0021] The above 8 types of features are concatenated into a fixed-length one-dimensional floating-point array (e.g., 1 length value + 3 title distribution values ​​+ 5 density values ​​+ N semantic values ​​= (9+N) dimensions, where N is configurable, for example, 64; semantic values ​​can come from TF-IDF dimensionality reduction vectors or sentence vector embeddings), and each dimension of the text feature vector is normalized (Min-Max normalization or Z-score normalization), such as the Min-Max normalization process: v norm =(v-min template (v)) / (max template (v) -min template (v)), where v norm The value represents the normalized eigenvalue of this dimension, v represents the original eigenvalue, and min represents the eigenvalue.template (v) represents the minimum value of all templates in the template library in this dimension, max template (v) represents the maximum value of all templates in the template library in this dimension, in order to eliminate the influence of dimensions, ensure that the features of each dimension contribute equally to the similarity calculation, and avoid the dominance of large numerical features such as length in the results.

[0022] By integrating structural and semantic features into a single vector, the subsequent similarity calculations can simultaneously reflect both "content theme similarity" and "layout style similarity." For example, a technical document about "database design" will not only match templates that semantically contain the keyword "database," but will also prioritize matching templates with more table and code block styles, thus improving the compatibility between style templates and data content.

[0023] Step 1012: Obtain the pre-stored feature vector of each style template in the preset structured template library, calculate the cosine similarity between each pre-stored feature vector and the text feature vector, and select the style template corresponding to the highest cosine similarity as the target style template of the initial data.

[0024] Specifically, each style template in the module library (such as System_Template_A.docx) has its corresponding feature vector (i.e., pre-stored feature vector) pre-calculated using the same feature extraction method as the initial data when it is added to the library, and stored in the template library's index file. The template library is then traversed, and the pre-stored feature vector of each template is read sequentially. Calculate the relationship between each pre-stored feature vector and the text feature vector V. input Cosine similarity between them: ; In the formula, the numerator is the dot product of the two vectors, the denominator is the product of the magnitudes of the two vectors, and the range of the result is [-1, 1]. In the positive vector space, the actual range is [0, 1]. The closer it is to 1, the more similar the vectors are.

[0025] Select the style template with the highest similarity: j*=argmax j sim j If the highest cosine similarity is lower than a preset similarity threshold (e.g., 0.6), the default general template will be used as the target style template for the initial data. In this way, the best template can be matched first, and the general template can be automatically downgraded when the similarity is low, thus balancing accuracy and system robustness.

[0026] In another embodiment of the invention, it is supported to assign weights w to different feature dimensions. i This forms a weighted cosine similarity: ; In the formula, sim weighted w represents the weighted cosine similarity. i V represents the weight of feature dimension i. i,input v represents the feature value of feature dimension i in the text feature vector. i,template This represents the feature value of feature dimension i in the pre-stored feature vector. The weights can be preset according to the business scenario (e.g., the weight of title hierarchy distribution is greater than the weight of document length). This weight table can be adjusted by the system administrator through the configuration file.

[0027] In another embodiment of the present invention, when the number of templates in the template library is large (e.g., more than 100), the system will first use low-computational-cost features such as document length and title hierarchy distribution to perform a coarse screening, select the top 10% of the most similar templates, and then calculate the complete 73-dimensional cosine similarity for the remaining templates.

[0028] In one embodiment of the present invention, step 102 includes steps 1021 and 1022: Step 1021: Parse the target style template into a text string, construct a text generation instruction based on the text string and the initial data, inject the preset layout isolation rule into the text generation instruction, input the text generation instruction with the preset layout isolation rule injected into the large language model, and output the first unstructured text by the large language model.

[0029] Specifically, the target style template is parsed into a text string. Based on this text string and initial data, the generated text quality is constructed. By including role definitions, task descriptions, and output format constraints, pre-defined layout isolation rules are injected into the text generation instructions using structured instruction templates and string formatting. These pre-defined layout isolation rules are placed at the beginning of the text generation instructions, using bolding, parentheses, and emphasis words (such as "strictly prohibited" and "mandatory requirement") to increase the priority of the instructions. Furthermore, structured encoding of rules is supported, such as using a JSON-formatted constraint language (e.g., JSON Schema) to restrict the output format. However, this requires the large model to support the `response_format` parameter (currently supported by mainstream models such as GPT-5 and Claude). Using this method, rules can be directly encoded into JSON Schema and passed into API requests for more rigid constraints. Simultaneously, parameters such as `temperature=0` can be set for the large language model during API calls to reduce model randomness. This approach ensures that the output format strictly conforms to the pre-defined rules, reduces the probability of non-standard tags and grammatical distortions, and improves the consistency and reliability of document generation.

[0030] Furthermore, in one embodiment of the present invention, the process of parsing the target style template into a text string is as follows: decompress the target style template, read the document structure file of the target style template, traverse the XML tree corresponding to the document structure file, extract the text content corresponding to all text tags in the XML tree, parse the paragraph tags and table tags, convert the paragraph tags and table tags into corresponding structural tags and insert them into the corresponding positions of the text content to generate a text string.

[0031] Specifically, the target style template is a .docx file (i.e., OOXML format), and the parsing process is as follows: 1. Unzip the OOXML package: The .docx file is essentially a zip archive. Use system libraries (such as Python's zipfile or Java's ZipInputStream) to unzip it to a temporary directory.

[0032] 2. Read the main document XML (i.e., the document structure file): Locate the word / document.xml file, which contains the XML representation of the document body.

[0033] 3. Recursively extract text nodes: Traverse the XML tree and extract all <w:t>The text content within the tag ( <w:t>This is where the actual text is saved in Word, ignoring style tags (such as...). <w:rpr>) and layout tags.

[0034] 4. Preserve paragraph separators and table structure: To ensure that the target style template provides not only text content examples but also style / structural constraints, the system will synchronously parse the style tags of paragraphs / tables (e.g., ...). <w:pstyle w:val="Heading2" / > The structure information (heading levels, list levels, table placeholders and positions) is expressed in the output plain text using structural tags (such as Heading2 placeholders, Table placeholders, etc.), thereby imposing calculable layout constraints on the generated results in the subsequent System Prompt, i.e., whenever a formatting constraint is encountered... <w:p>When a paragraph ends, add a newline character \n after the extracted text. <w:tbl>At that time, extract the contents of the table. <w:t>The text is then modified by adding tabs (\t) and newlines between rows and columns to simulate the plain text representation of a Markdown table (optional, for easier understanding by larger models).

[0035] 5. Generate plain text string: Concatenate the extracted content into a long string template_plain_text.

[0036] Step 1022: Obtain a preset regular expression library list, and perform anti-model illusion cleaning processing on the first unstructured text according to the preset execution order based on the preset regular expression library list to obtain the second unstructured text.

[0037] Specifically, the system feeds unstructured text into a multi-level regular expression processing module. This pipeline strictly follows a pre-defined execution order: "first strip external distortion attributes -> then repair internal broken syntax -> finally clean up residual orphaned tags," executing a pre-defined regular expression library list to prevent regular expression conflicts. The pre-defined regular expression library list is a set of regular expressions and their repair rules manually compiled and solidified before system deployment by analyzing common "typographical illusion" patterns in large models. It is stored in a configuration file (e.g., regex_rules.json) and loaded when the system starts. When a new illusion pattern is detected, new rules can be dynamically added or the order adjusted without modifying the core code. The pre-defined regular expression library list includes: 1. Distorted Attribute Label Stripping: For the labels `[text content]{attribute label}` with internal spaces caused by forced alignment in the model, the regular expression `\[([^\]]+)\]\{[^\}]+\}` is executed to extract the valid text nodes within the square brackets and discard the entire curly brace part and its content. For example, if the polluted text output by the large model is `[core energy]{.underline}`, after executing the regular expression, we get `core energy`. This regular expression can preserve the clean text, and the distorted attribute label (`.underline`) is completely removed. For the illusion of broken hyperlinks `[text](broken link)`, where the link part contains keywords such as `error`, `404`, or `null` indicating "broken link", the regular expression `\[(.?)\]\([^\)]?(?:error|404|null)[^\)]?\)` is executed. This replaces the entire hyperlink syntax with the text content within the square brackets, thus restoring it to plain text and discarding the broken link part. For example, the corrupted text output by the large model is `[click to view details](error)`. After executing the regular expression, we get `click to view details`. This regular expression can identify and remove broken links, keeping only meaningful link text. Furthermore, normal links (such as `[normal link](https: / / example.com)`) will not be matched by this regular expression and are therefore preserved.

[0038] 2. Broken Syntax Tree Repair: For interrupted emphasis symbols, execute the regular expression `\s+\` to repair it to ``; for interrupted underscores or strikethroughs, execute the regular expression `_\s+_` to repair it to `__`, and execute `~~\s+~~` to repair it to `~~~~`.

[0039] 3. Isolated Tag Removal: For isolated tags `{...}`, where the curly braces can contain dots, alphanumeric characters, underscores and whitespace characters, execute the regular expression `\{[\.\w\s]+\}` to replace the entire tag with an empty string (i.e., delete it). For example, if the polluted text output by the large model is `This is the body text{.class}`, after executing the regular expression, `This is the body text` is obtained. Through this regular expression, all remaining isolated curly brace tags can be removed, ensuring that the output text no longer contains any structural distorted nodes. Moreover, for normal curly braces or curly braces in code blocks, such as `{Normal curly braces}`, `{literal braces in code block}`, the inside of which does not contain characteristic characters such as dots or underscores will not be matched by this regular expression and remain unchanged, ensuring that the cleaning process will not mistakenly delete legitimate punctuation marks.

[0040] The rigor of the pipeline sequence ensures that the cleaning process will not damage the originally correct syntax structure, and a deterministic regular algorithm is used to forcibly "reduce the dimension" and "purify" the non-standard distorted text into standard text nodes, ensuring the reliability of subsequent syntax tree parsing.

[0041] In an embodiment of the present invention, step 103 includes step 1031 and step 1032: In step 1031, a style mapping table is constructed by parsing the target style template; the second unstructured text is parsed into an abstract syntax tree, the abstract syntax tree is traversed, and for each node in the abstract syntax tree, a corresponding style identifier is obtained from the style mapping table according to the node type of the node, and a document element is created based on the content of the node and the style identifier; a document object is constructed, and all the document elements are written into the document object to generate an initial document.

[0042] Specifically, the target style template is a .docx file, and various styles (such as Heading1, Heading2, Normal, TableGrid) are defined in the underlying styles.xml, each style has a unique identifier (such as Heading1) and specific format attributes (font, font size, color, spacing, etc.); the AST (Abstract Syntax Tree) is generated by the document conversion engine, and the node types include Header, Para, Table, CodeBlock, Strong, Emph, etc.

[0043] Use an OOXML SDK (such as python-docx for Python or DocumentFormat.OpenXml for C#) to parse the target style template, extract all styles from the target style template, and build a style mapping table {AST node type: style ID}, for example: Header level 1 → Heading1; Header level 2 → Heading2; Table → TableGrid; CodeBlock → SourceCode (custom style), to implement the binding of AST nodes to any custom style name.

[0044] The system calls the underlying document conversion engine (such as one based on the Pandoc AST architecture) to parse the second unstructured text into a standard JSON-formatted abstract syntax tree (AST). For example, it parses the Markdown second-level heading into an AST node `{"t":"Header", "c": [2, ["id", [], []], [{"t": "Str", "c": "Heading text"}]]}`. The abstract syntax tree (AST) is traversed, and each AST node is forcibly bound to the corresponding style defined in the template through the style mapping table: if the node type is Header, the corresponding style identifier is retrieved from the style mapping table according to its level, and document.add_heading(ast_node.text(node ​​content), level(node ​​level), style_id(style identifier)) is called to create a heading element; if the node type is Para node, document.add_paragraph() is called, and the style defaults to Normal; if the node type is Table, the table style identifier is retrieved from the style mapping table, document.add_table(rows, cols) is called to create a table, and the table style is set to TableGrid; for Strong or Emph nodes, when adding text, the bold=True or italic=True attribute of Run is directly set. The entire mapping process does not rely on the default style name of the transformation engine, but dynamically reads the actual style identifiers existing in the template, so even if the style in the template is modified based on the standard style (such as Heading1 having its font modified), it can be fully inherited. If a corresponding entry does not exist in the style mapping table (e.g., the template lacks a certain level of heading style), the system executes a fallback strategy: finding the closest style from the template (e.g., mapping Header2 to the existing Heading1 and adjusting the level), or creating a base style to ensure that document elements do not lose formatting. Finally, all created document elements are sequentially written into the document object to generate an initial document that conforms to the target template's style definition. By directly mapping AST to the underlying XML of OOXML, "lossless inheritance" of styles is achieved, dynamically adapting to custom style names of any target template. This allows AI-generated documents to directly conform to the company's image and document specifications without manual secondary formatting, ensuring the reliability of automated inheritance of formatting standards.

[0045] Step 1032: Generate directory field code based on the abstract syntax tree and preset directory generation rules, create a structured document tag block in the initial document, write the directory field code into the structured document tag block, and generate the final document.

[0046] Specifically, the system traverses the abstract syntax tree to determine the scope of the directory and dynamically generates corresponding directory field codes based on preset directory generation rules. The format can be: TOC \o "1-3" \h \z \u, where \o "1-3": includes headings of outline levels 1 to 3; \h: hyperlink; \z: hides tab leader; \u: uses paragraph outline levels. A structured document tag block is created at the specified insertion point (usually an empty paragraph) in the initial document. <w:sdt>), write directory field codes into structured document tag blocks, and write them into an XML tree by manipulating OOXML: create <w:sdt>The element has its w:alias set to "directory"; in <w:sdtcontent>Add one <w:p>(Paragraph), the paragraph contains a <w:r>(operation), in operation comprising <w:instrtext> Tags, whose text content is the field code (e.g., TOC \o "1-4" \h \z \u); finally add< / w:instrtext> < / w:r> < / w:p> < / w:sdtcontent> < / w:sdt> The closing tag. When a user opens the document with Word, the Word engine automatically parses this field code and renders a clickable, correctly hierarchical, dynamic table of contents. This method dynamically generates matching table of contents field codes based on the document's actual heading hierarchy, avoiding blank or invalid table of contents entries due to pre-set fixed levels (such as hardcoded "1-3") that result in missing headings. It also supports flexible table of contents strategy configuration, ensuring the final document's table of contents is always accurate, neat, and requires no manual correction.

[0047] Furthermore, in one embodiment of the present invention, generating directory field code based on an abstract syntax tree and preset directory generation rules includes: traversing the abstract syntax tree, identifying the highest and lowest levels of the head nodes in the abstract syntax tree, and determining the level range; determining the activation status of each preset configuration parameter based on the preset directory generation rules, and generating directory field code based on the level range and the activation status of each preset configuration parameter.

[0048] Specifically, the system determines the directory level range by scanning the highest level (max_level) and lowest level (min_level) of all Header nodes in the AST. For example, if a document contains #, ##, and ###, then min_level=1 and max_level=3. This range is calculated from min_level to max_level, but can be adjusted according to configuration (e.g., "generate only levels 1-3"). Preset directory generation rules are defined in the system configuration file, such as always generating levels 1-3, excluding appendix titles, and generating hyperlinked directories. The system reads these preset rules, determines whether to enable hyperlinks, hide leader characters, and configure paragraph outline levels, and appends the corresponding identifiers to the field code base TOC \o "{min_level}-{max_level}". For example, if the configuration mandates a range of 1-3 and enables hyperlinks, then TOC \o "1-3" \h is generated, resulting in the directory field code. In this way, the directory hierarchy can be automatically adapted to the actual document structure, and the presentation behavior of the directory can be flexibly controlled through preset rules (such as whether to include links, whether to hide the leader character, etc.), ensuring the dynamic generation of the document directory.

[0049] Furthermore, in one embodiment of the present invention, the following specific application scenarios are also provided: The system receives a request for a "new Explorer System". After extracting features, it automatically routes and locks the underlying style template named `System_Template_A.docx` in the background template library. A Markdown draft is generated from the large model. Due to model illusion, the draft outputs non-standard tags contaminated with spaces, such as `[Core Energy]{.underline}` and `~ ~deprecated settings~ ~`. The system sends the draft to the cleaning pipeline, executing the regular expression library list sequentially to automatically restore the distorted tags to clean, standard nodes `Core Energy` and `~~deprecated settings~~`. The system parses the cleaned text into an AST and maps it to the underlying XML of `System_Template_A.docx`. The engine perfectly maps the `##` node to "Heading 2 (Founder Variety Simplified, 12pt font)" defined in the Word template and injects `...` into the document header. <w:sdt>The domain code block generates a native directory, ultimately outputting a highly standardized enterprise-level document.

[0050] Please refer to Figure 2 The present invention also provides a document generation system 200 for resisting model illusion, including a memory 201, a processor 202, and a computer program stored in the memory and executable on the processor. When the processor executes the computer program, it implements the various steps of a document generation method for resisting model illusion as described above.

[0051] The above description is merely an embodiment of the present invention and does not limit the patent scope of the present invention. Any equivalent modifications made based on the content of the present invention specification and drawings, or direct or indirect applications in related technical fields, are similarly included within the patent protection scope of the present invention.< / w:sdt> < / w:sdt> < / w:t> < / w:tbl> < / w:p> < / w:rpr> < / w:t> < / w:t>

Claims

1. A document generation method to combat model illusion, characterized in that, include: Receive initial data input by the user, extract the text feature vector of the initial data, and obtain the target style template of the initial data from a preset structured template library based on the text feature vector; Based on the initial data, the target style template, and the preset layout isolation rules, the large language model is called to generate the first unstructured text, and the first unstructured text is subjected to anti-model illusion cleaning processing to obtain the second unstructured text. An initial document is generated based on the second unstructured text and the target style template, and a final document is generated based on the initial document and preset directory generation rules.

2. The document generation method for combating model hallucinations according to claim 1, characterized in that, Extracting text feature vectors from the initial data, and obtaining target style templates for the initial data from a preset structured template library based on the text feature vectors, including: Extract the structural and semantic features of the initial data, generate a text feature vector of the initial data based on the structural and semantic features, and normalize each dimension of the text feature vector. Obtain the pre-stored feature vector of each style template in the preset structured template library, calculate the cosine similarity between each pre-stored feature vector and the text feature vector, and select the style template corresponding to the highest cosine similarity as the target style template of the initial data.

3. The document generation method for combating model hallucinations according to claim 2, characterized in that, Select the style template corresponding to the highest cosine similarity as the target style template for the initial data, which includes the following: If the highest cosine similarity is lower than the preset similarity threshold, then the default general template will be used as the target style template for the initial data.

4. The document generation method for combating model hallucinations according to claim 1, characterized in that, Based on the initial data, the target style template, and the preset layout isolation rules, the large language model is invoked to generate the first unstructured text, including: The target style template is parsed into a text string, a text generation instruction is constructed based on the text string and the initial data, and the preset layout isolation rule is injected into the text generation instruction. The text generation instruction with the preset layout isolation rule injected is input into the large language model, and the large language model outputs the first unstructured text.

5. The document generation method for combating model hallucinations according to claim 4, characterized in that, The target style template is parsed into a text string, including: Unzip the target style template, read the document structure file of the target style template, traverse the XML tree corresponding to the document structure file, extract the text content corresponding to all text tags in the XML tree, parse the paragraph tags and table tags, convert the paragraph tags and table tags into corresponding structural tags and insert them into the corresponding positions of the text content to generate a text string.

6. The document generation method for combating model hallucinations according to claim 1, characterized in that, The first unstructured text is subjected to anti-model hallucination cleaning processing to obtain the second unstructured text, including: Obtain a preset list of regular expressions, and perform anti-model illusion cleaning on the first unstructured text according to a preset execution order based on the preset list of regular expressions to obtain the second unstructured text.

7. The document generation method for combating model hallucinations according to claim 1, characterized in that, Generate an initial document based on the second unstructured text and the target style template, including: A style mapping table is constructed by parsing the target style template; The second unstructured text is parsed into an abstract syntax tree. The abstract syntax tree is traversed. For each node in the abstract syntax tree, the corresponding style identifier is obtained from the style mapping table according to the node type of the node. A document element is created based on the content of the node and the style identifier. Construct a document object and write all the document elements into the document object to generate the initial document.

8. The document generation method for combating model hallucinations according to claim 7, characterized in that, The final document is generated based on the initial document and the preset table of contents generation rules, including: Based on the abstract syntax tree and preset directory generation rules, directory field codes are generated. A structured document tag block is created in the initial document, and the directory field codes are written into the structured document tag block to generate the final document.

9. A document generation method for combating model hallucinations according to claim 8, characterized in that, Generate directory field codes based on the abstract syntax tree and preset directory generation rules, including: Traverse the abstract syntax tree, identify the highest and lowest levels of the head nodes in the abstract syntax tree, and determine the level range; The activation status of each preset configuration parameter is determined based on the preset directory generation rules, and directory domain codes are generated based on the hierarchical range and the activation status of each preset configuration parameter.

10. A document generation system for resisting model illusion, comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, characterized in that, When the processor executes the computer program, it implements each step of the document generation method for resisting model illusion as described in any one of claims 1 to 9.