Intelligent official document writing method and system based on large language model and multi-agent collaboration

The intelligent document writing system, which utilizes a large language model and multi-agent collaboration, solves the problems of logical coherence, factual accuracy, and automated rendering of national standard formats in document generation. It achieves high-quality, fully automated standardized document generation and improves the system's controllability and interpretability.

CN121859873APending Publication Date: 2026-04-14BEIJING FANGCUN WUYOU TECH DEV CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-12-29
Publication Date
2026-04-14

AI Technical Summary

Technical Problem

Existing intelligent document writing technologies are insufficient in terms of logical coherence of long texts, factual accuracy, and automated rendering of national standard formats. They also lack dynamic interaction and feedback mechanisms among multiple agents, making it difficult to generate high-quality, fully automated standardized documents.

Method used

We construct an intelligent document writing system based on a large language model and multi-agent collaboration, which includes planning, retrieval, writing, review and typesetting agents. It adopts a thought chain-driven outline generation, fine-grained evidence injection, structured negative feedback correction mechanism and abstract syntax tree mapping to achieve an adversarial collaborative architecture.

Benefits of technology

It has achieved high-quality, highly reliable, and fully automated standardized document generation, which has improved the factual credibility and compliance of the content, ensured the logical coherence of the whole text, and achieved fully automated rendering of the GB/T 9704 standard format, reducing manual intervention and time costs.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121859873A_ABST
    Figure CN121859873A_ABST
Patent Text Reader

Abstract

The invention relates to the technical field of artificial intelligence and official document processing, in particular to an official document intelligent writing method and system based on cooperation of a large language model and multiple agents. Through thinking chain driving outline generation, fine-grained evidence injection, structured negative feedback correction and AST mapping national standard typesetting, automatic official document generation with logic coherence, accurate facts and compliant formats is realized.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the fields of artificial intelligence and natural language processing technology, specifically to an intelligent document writing method and system based on a large language model and multi-agent collaboration. Background Technology

[0002] The demand for automation in government and enterprise offices continues to rise in today's society. Official documents, as a crucial vehicle for government agencies and enterprises to fulfill their functions, possess a high degree of political significance, standardization, and mandatory formatting. With the development of artificial intelligence and natural language processing technologies, intelligent writing systems based on Large Language Models (LLM) have achieved initial applications in various professional text generation scenarios, such as financial research reports and news articles. However, when faced with writing tasks like official documents—characterized by rigorous structure, precise and compliant content, and strict adherence to national standards (such as GB / T 9704)—existing technologies still face several key challenges.

[0003] Existing technical solutions mainly fall into three categories: First, rule-based template-based fill-in generation methods, which pre-set the document structure and fill in the key fields input by the user. While this can ensure basic format consistency, it lacks the ability to understand and logically organize complex semantic materials, making it difficult to meet non-standardized writing needs. Second, end-to-end generation methods based on general large language models, where the model directly outputs the full text after the user inputs natural language commands. This approach improves content flexibility, but it is prone to problems such as logical drift and contextual forgetting in long text generation. Furthermore, the model's internal knowledge has limitations in timeliness and accuracy, which may produce statements that do not conform to the facts. Third, basic retrieval-enhanced generation (RAG) methods, which introduce external knowledge fragments to assist in generation. While this alleviates the "illusion" problem to some extent, it usually does not perform global planning of the full text structure, resulting in loose content organization, repetition, or a lack of in-depth analysis.

[0004] Furthermore, some multi-agent collaborative writing solutions attempt to break down tasks into steps such as information extraction, outline generation, segmented writing, and format conversion, employing a linear workflow to schedule each module. While this approach improves the efficiency of task division, it lacks dynamic interaction and feedback mechanisms between agents, particularly an independent review process for adversarial verification of the factual consistency and logical compliance of the generated content. Additionally, their typesetting modules often only support basic style conversions, failing to establish precise mappings to national standards for elements specific to official documents, such as the position of the official header, document number, imprint, specific font size, and line spacing. The generated results often still require manual intervention to meet the requirements of formal document issuance.

[0005] In summary, current intelligent document writing technologies either focus on end-to-end output of a single model while neglecting process controllability, or, although they introduce multi-agent architectures, are limited to unidirectional task flows. They fail to build a collaborative mechanism that deeply integrates planning, retrieval, writing, review, and typesetting, and also fail to effectively address core issues such as the logical coherence of long texts, constraints on factual accuracy, and automated rendering of national standard formats. Therefore, there is an urgent need for a new intelligent document writing method and system based on a large language model and multi-agent collaboration. This system should introduce thought chain-driven outline planning, fine-grained evidence injection, a structured negative feedback correction mechanism, and national standard typesetting mapping based on Abstract Syntax Trees (ASTs) to achieve high-quality, highly reliable, and fully automated standardized document generation. Summary of the Invention

[0006] The purpose of this invention is to provide an intelligent document writing method and system based on a large language model and multi-agent collaboration. Addressing the shortcomings of existing document generation technologies in areas such as logical coherence of long texts, factual accuracy constraints, automated rendering of national standard formats, and dynamic feedback mechanisms for multi-agents, this invention constructs an adversarial collaborative architecture comprising five specialized agents: planning, retrieval, writing, review, and typesetting. It also introduces a thought chain-driven outline generation, fine-grained evidence injection, a structured negative feedback correction mechanism, and a national standard typesetting mapping strategy based on Abstract Syntax Trees (ASTs). This solves the problem of automatically generating highly structured, strictly formatted, and precisely compliant documents.

[0007] To achieve the above objectives, the present invention provides an intelligent document writing method based on a large language model and multi-agent collaboration, specifically comprising: receiving natural language instructions and reference materials input by the user; parsing to obtain the document type, core theme, issuing unit, urgency, and length requirements; calling a pre-set outline template library according to the document type, generating a hierarchical outline tree in combination with the reference materials, and storing it in JSON format; traversing each leaf node of the outline tree, generating an independent query vector for each node, performing a hybrid search in the global policy library and temporary task knowledge base, marking the search results as evidence blocks and attaching them to the corresponding outline nodes; and based on the large language model and multi-agent collaboration, the method further comprises: receiving natural language instructions and reference materials input by the user, parsing to obtain the document type, core theme, issuing unit, urgency, and length requirements; calling a pre-set outline template library according to the document type, generating a hierarchical outline tree in combination with the reference materials, and storing it in JSON format; traversing each leaf node of the outline tree, generating an independent query vector for each node, performing a hybrid search in the global policy library and temporary task knowledge base, marking the search results as evidence blocks and attaching them to the corresponding outline nodes; and, based on the large language model and multi-agent collaboration, performing a hybrid search in the global policy library and temporary task knowledge base, generating a hierarchical outline tree according to the reference materials; and, based on the large language model and multi-agent collaboration, performing a hierarchical outline tree in combination with the reference materials. The framework tree and the attached evidence blocks call the writing agent node by node to generate paragraph content. Each paragraph generation uses a sliding window mechanism to introduce a summary of the preceding paragraph as context input. The generated full text is input into the review agent, which extracts key entities and compares them with the evidence blocks using triples. If an inconsistency is detected, a structured feedback instruction containing error location coordinates, error type, and modification suggestion (Prompt) is constructed and sent back to the writing agent, triggering local regeneration. After the review is approved, the final text is parsed into an abstract syntax tree, identifying title nodes, body nodes, and signature nodes. Based on the preset node type and style definition mapping table, GB / T 9704 standard format attributes are injected, and the node stream with style attributes is encapsulated into a Word XML document.

[0008] In the above-mentioned intelligent document writing method based on large language model and multi-agent collaboration, the generation of hierarchical outline tree can optionally include: activating the planning agent, which loads a pre-set outline template matching the document type, vectorizing the user-provided reference materials after OCR recognition, cleaning and segmentation, and inputting them into the large language model to generate a tree-like outline that conforms to the logical structure of the document, wherein each non-leaf node represents a chapter title and each leaf node carries a description of the content intent.

[0009] In the above-mentioned intelligent document writing method based on large language model and multi-agent collaboration, optionally, the hybrid retrieval includes: for the content intent description of each outline leaf node, the retrieval agent generates a keyword sequence and semantic vector, performs retrieval in the inverted index and vector database respectively, and selects the Top-K segments as evidence blocks after merging the two results by weighted score. The evidence blocks include the original text, source identifier and confidence score.

[0010] In the above-mentioned intelligent document writing method based on a large language model and multi-agent collaboration, optionally, the step-by-step invocation of the writing agent to generate paragraph content includes: assembling prompt words, wherein the prompt words are composed of system-level document style definitions, current node intent descriptions and attached evidence blocks; invoking the large language model to generate corresponding paragraphs; for documents whose total length exceeds a preset threshold, when generating the Nth paragraph, the summary of the N-1th paragraph is embedded as additional context prompt words, wherein the summary is generated by a fixed-length extraction-based summary model.

[0011] In the above-mentioned intelligent document writing method based on large language models and multi-agent collaboration, optionally, the structured feedback instructions constructed by the review agent include: running the named entity recognition module to extract the time, data, legal name, and document number from the generated text; comparing the extracted results with the evidence block attached to the corresponding outline node at the field level; if the difference confidence exceeds the threshold, recording the error position offset, error category code, and rewrite guidance prompt, and encapsulating it into a feedback instruction in JSON format; the master control scheduling layer sends this instruction to the writing agent to trigger the local regeneration of the specified text block, while retaining the remaining approved content unchanged.

[0012] In the above-mentioned intelligent document writing method based on large language model and multi-agent collaboration, optionally, the parsing into an abstract syntax tree includes: inputting the Markdown intermediate text into the syntax parser, constructing a tree structure containing node types, hierarchical depth and original text content, where the first-level heading corresponds to the Header1 node, the second-level heading corresponds to the Header2 node, the body paragraph corresponds to the Paragraph node, and the closing line corresponds to the Signature node.

[0013] In the above-mentioned intelligent document writing method based on large language model and multi-agent collaboration, the optional injection of GB / T 9704 standard format attributes includes: establishing a mapping table, wherein the mapping table defines the Header1 node as "Small Song typeface, 22 points, centered", the Paragraph node as "Fangsong_GB2312, size 3, 28 points line spacing", and the Signature node as "right aligned, Fangsong_GB2312, size 3"; traversing each node of the abstract syntax tree, looking up the style definition in the table according to its type, and appending the style attributes to the node metadata in the form of key-value pairs.

[0014] In the aforementioned intelligent document writing method based on a large language model and multi-agent collaboration, optionally, it can be encapsulated as a Word XML document containing: converting the abstract syntax tree with styled metadata into an OpenXML-compatible stream of paragraph objects, each paragraph object containing <w:p>Tags and their child elements <w:ppr>Used to declare styles, <w:r>Used to carry text content; it writes the paragraph object stream sequentially to the document.xml path of the .docx file, and simultaneously generates styles.xml and settings.xml to solidify the national standard format specifications.

[0015] This invention also provides an intelligent document writing system based on a large language model and multi-agent collaboration. The system includes: an intent parsing module for receiving user instructions and reference materials, extracting document type, core theme, issuing unit, urgency, and length requirements; an outline generation module for calling a preset template and combining it with the materials to generate a hierarchical outline tree in JSON format; an evidence mounting module for traversing the outline leaf nodes, performing mixed retrieval, and marking the results as evidence blocks to the corresponding nodes; a segmented writing module for generating paragraph content node by node and introducing a preceding summary as a sliding context in long document scenarios; a review feedback module for performing factual consistency comparison and generating structured feedback instructions to drive local rewriting when errors are detected; and a format rendering module for parsing the final text into an abstract syntax tree, injecting national standard style attributes, and outputting a Word XML document conforming to GB / T 9704.

[0016] 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 above-described method.

[0017] The present invention also provides a computer-readable storage medium storing a computer program for performing the above-described method.

[0018] The present invention also provides a computer program product, including a computer program / instructions that, when executed by a processor, implement the steps of the above-described method.

[0019] The beneficial effects of this invention include:

[0020] This invention constructs an adversarial collaborative architecture for five intelligent agents: planning, retrieval, writing, review, and typesetting. It integrates core technologies such as hierarchical outline generation driven by thought chains, precise mounting of outline leaf nodes and evidence blocks, sliding window context maintenance mechanism, structured negative feedback local regeneration, and abstract syntax tree (AST) mapping to national standard formats. This effectively addresses key pain points in existing intelligent document writing technologies, including long text logic drift, insufficient factual accuracy, inaccurate automated rendering of national standard formats, and lack of dynamic feedback among multiple agents. It significantly improves the factual credibility and compliance of document content through hybrid retrieval of a global policy base and a temporary task knowledge base, as well as key entity triple comparison. The hierarchical outline tree and preceding paragraph summary embedding mechanism ensure the logical coherence of the entire text. Furthermore, it implements GB / T 9704 based on node type-style mapping tables and Word XML encapsulation. The system features fully automatic and accurate rendering in standard format, eliminating the need for manual secondary typesetting. Simultaneously, a partial regeneration mechanism avoids the resource waste and efficiency loss caused by full-text rewriting. A multi-agent closed-loop collaborative architecture enhances the controllability and flexibility of the writing process, supporting free input of user natural language commands and various types of reference materials. Furthermore, each paragraph includes evidence source identifiers and confidence scores, improving the system's interpretability and traceability. Ultimately, this achieves high-quality, highly reliable, fully automatic, and standardized document generation, significantly reducing the time cost and professional threshold for government and enterprise office work, and providing efficient and reliable technical support for office automation upgrades. Attached Figure Description

[0021] The accompanying drawings are provided to further illustrate the present application and form part of the specification. They are used together with the embodiments of the present application to explain the application and do not constitute a limitation thereof. In the drawings:

[0022] Figure 1 This is a schematic diagram of the overall process of the intelligent document writing method based on a large language model and multi-agent collaboration of the present invention.

[0023] Figure 2 This is a schematic diagram of the interaction relationship of the multi-agent collaborative architecture in this invention, showing the data flow and control flow between five types of agents: planning, retrieval, writing, reviewing, and typesetting.

[0024] Figure 3 This is a schematic diagram of the conversion process from generated text to national standard format official documents in this invention, including the steps of abstract syntax tree construction and style attribute injection.

[0025] Figure 4 This is a schematic diagram of the partial regeneration process of the review feedback mechanism in this invention, illustrating the error detection, structured feedback instruction generation, and targeted correction process. Detailed Implementation

[0026] This invention provides a method and system for intelligent official document writing based on a large language model and multi-agent collaboration, the specific implementation process of which is as follows. Figure 1 As shown, the entire process begins with user input, which includes natural language instructions (e.g., "Draft a notice on strengthening urban waste sorting management") and optional reference materials (e.g., policy documents in PDF format, scanned copies, or web links). After receiving the input, the intent parsing module first performs semantic parsing on the natural language instructions, extracting the document type (e.g., "notice," "request," "report"), core theme (e.g., "waste sorting management"), issuing unit (e.g., "XX City Urban Management Committee"), urgency level (e.g., "urgent," "critical," "normal"), and length requirement (e.g., "approximately 1500 words"). For reference materials, the intent parsing module calls the OCR engine to perform text recognition on image-type materials and uses the text cleaning module to remove noise characters, headers, footers, and irrelevant advertising content. The cleaned text is then segmented and stored in a temporary task knowledge base for subsequent retrieval.

[0027] After intent parsing is completed, the process enters the outline generation module. This module activates the planning agent (see...). Figure 2 The system loads a structured template matching the current document type from a pre-set outline template library. For example, if the document type is "notice," a standard template containing four parts—"Reason for Issuance—Work Requirements—Safeguard Measures—Contact Information"—is loaded. The planning agent vectorizes the user-provided reference materials and inputs them, along with the template structure, into the large language model, guiding it to generate a hierarchical outline tree that conforms to the logical structure of official documents. This outline tree is organized in JSON format, where non-leaf nodes represent chapter titles (e.g., "I. General Requirements"), and leaf nodes carry a description of the content intent (e.g., "Explaining the policy basis and practical necessity of garbage classification work"). The generated outline tree is then passed to the evidence mounting module.

[0028] The evidence mounting module traverses each leaf node in the outline tree, and for each node's content intent description, it is handled by the retrieval agent ( Figure 2 The system generates keyword sequences and semantic vectors. Keyword sequences are used to perform Boolean searches in the inverted index, while semantic vectors are used to perform near nearest neighbor (ANN) searches in the vector database. The global policy repository contains the latest national and local laws, regulations, policy documents, and their metadata, while the temporary task knowledge base stores reference materials provided by users in this task. The two search results are fused using a weighted score (e.g., keyword matching weight 0.4, semantic similarity weight 0.6), and the top-3 segments are selected as evidence blocks. Each evidence block contains the original text, a source identifier (e.g., "Article 5 of Document No. 12 of the State Council

[2023] "), and a confidence score (between 0 and 1), and is attached to the corresponding outline leaf node in key-value pairs to form an enhanced outline structure supported by evidence.

[0029] The hybrid retrieval strategy combines keyword-based sparse retrieval and vector-based semantic retrieval. The specific steps are as follows: 1) Sparse Retrieval: Extract keywords from the outline node intent, perform a Boolean query in an inverted index database built on Elasticsearch, and calculate the relevance score S_k using the BM25 algorithm. 2) Semantic Retrieval: Perform an approximate nearest neighbor search on the semantic vector of the node intent in a vector database built on FAISS or Milvus, and calculate the cosine similarity score S_v. 3) Result Fusion: For the same document fragment, its final score S_final = α * S_k + (1-α) * S_v, where α is the fusion weight (e.g., α=0.4). The system sorts the fragments in descending order of S_final and selects the Top-K (e.g., K=3) fragments as evidence blocks.

[0030] The vectorization operation is implemented through a text embedding model. Specifically, optimized Chinese text embedding models such as Sentence-BERT, BGE (BAAI General Embedding), or text2vec are used. This model converts the input text fragment (such as cleaned material blocks or outline node intent descriptions) into a fixed-dimensional semantic vector (e.g., a 768-dimensional or 1024-dimensional floating-point vector). This vector represents the semantic information of the text in a high-dimensional space; texts with similar semantics have high cosine similarity between their vectors. This semantic vector is used for subsequent approximate nearest neighbor (ANN) retrieval in a vector database.

[0031] The process then proceeds to the segmented writing module. This module calls the writing agent node by node ( Figure 2 The system generates corresponding paragraph content for each outline leaf node. The writing agent assembles prompt words, which consist of three parts: a system-level official document style definition (e.g., "use formal, solemn, and concise official written language, avoiding colloquial expressions"), a description of the content intent of the current node, and all evidence blocks attached to that node. The prompt words are input into the large language model to generate paragraph text that meets the requirements. For long documents exceeding 2000 characters, the system uses a sliding window mechanism: when generating the Nth paragraph, a fixed-length extractive summarization model (e.g., based on the TextRank algorithm) is called to generate a summary of no more than 50 characters for the N-1th paragraph, and this summary is embedded as additional context into the current prompt word to maintain the logical coherence of the entire text. All generated paragraphs are assembled in outline order to form the initial full text. Figure 4 (and then forwarded to the review feedback module.)

[0032] To maintain contextual coherence during long document generation, the system employs an extractive summarization model to generate fixed-length summaries for preceding paragraphs. This model can use a graph ranking algorithm based on TextRank or a sequence labeling method based on a pre-trained model (such as BERT) to determine whether each sentence should be extracted. For example, for paragraphs no longer than 500 characters, the system sets a maximum summary length of 50 characters. The model receives the preceding paragraph text, outputs the 1-3 sentences with the highest importance scores, and concatenates them in their original order to form a summary. This summary is then embedded as "contextual memory" into the prompts for the next paragraph generation.

[0033] The review feedback module starts the review agent ( Figure 2 The generated full text undergoes factual consistency verification. First, the named entity recognition module ( Figure 4 The algorithm runs on the entire text, extracting key entities such as time (e.g., "June 1, 2024"), data (e.g., "coverage increased to 90%)", regulation names (e.g., "Regulations on the Management of Household Waste Classification"), and document numbers (e.g., "Jiancheng

[2022] No. 88"). Subsequently, the evidence block comparison module ( Figure 4 These entities are compared at the field level with the evidence blocks mounted on the corresponding outline nodes.

[0034] The evidence block comparison logic employs a tiered matching strategy. For entities like DOC_NUM (document number) and TIME (precise date), a complete match with the corresponding field in the evidence block is required. For LAW_REG (regulatory name), DATA (data description), and general factual statements, semantic similarity matching is used. Specifically, entities or statements extracted from the generated text are converted into semantic vectors along with the original text of the evidence block (or the pre-extracted entity list from the evidence block), and cosine similarity is calculated. If the similarity is below a threshold (e.g., 0.75), and exceeds an error threshold after the above-mentioned difference confidence calculation, an inconsistency alert is triggered. This process can be fine-tuned using a sentence pair classification model to improve comparison accuracy.

[0035] It should be noted that the overall score S_final in the retrieval stage aims to measure the relevance of evidence to the writing intent; a higher value indicates greater relevance. Conversely, the difference confidence score in the review stage aims to measure the inconsistency between the generated text and the established evidence; a higher value indicates a greater difference. These two scores serve different purposes, yet together they constitute a closed loop of quality assurance, from 'based on evidence' to 'accuracy'.

[0036] For example, if the generated text mentions "according to Article 10 of the 'Regulations on Garbage Classification of XX Province'", but the evidence block only contains "Document No. 12 of the State Council

[2023] ", it is judged as a citation error. When the difference confidence (calculated by combining edit distance and semantic similarity) exceeds a preset threshold (e.g., 0.85), the system records the error location offset (in characters), the error category code (e.g., E01 indicates a citation error in regulations, E02 indicates data inconsistency), and the rewrite prompt (e.g., "Please restate the policy basis according to 'Document No. 12 of the State Council

[2023] ' in the evidence block"), and encapsulates the above information into a structured feedback instruction in JSON format. Figure 4 Main control and scheduling layer ( Figure 2 Upon receiving the instruction, it is directed to the writing agent, triggering a local regeneration trigger. Figure 4 Only specified text blocks (such as paragraphs containing errors) are rewritten; the rest of the approved content remains unchanged. (The corrected paragraph...) Figure 4 Replace the corresponding positions in the original text with the updated full text. This review-feedback-regeneration loop will execute a maximum of three times. If uncorrected errors still exist, it will be marked as manually reviewed; otherwise, the final text will be generated. Figure 3 Output to the format rendering module.

[0037] The formatting and rendering module is responsible for converting the final text into a Word document that conforms to the GB / T 9704—2012 national standard. First, the final text, represented in Markdown intermediate mode (e.g., first-level headings begin with #, and body text is a regular paragraph), is input to the syntax parser ( Figure 3 The parser constructs an abstract syntax tree based on regularity rules and a recursive descent algorithm. Figure 3 Each node in the hierarchy contains a node type (e.g., Header1, Header2, Paragraph, Signature), a hierarchy depth (e.g., Header1 has a depth of 1), and the original text content. For example, the line "# Notice on Strengthening Urban Waste Classification Management" is parsed as a Header1 node, with the content "Notice on Strengthening Urban Waste Classification Management"; the closing line "XX City Urban Management Committee, June 1, 2024" is identified as a Signature node.

[0038] Abstract Syntax Tree (AST) parsers are built based on predefined Markdown syntax rules and can be implemented using compilers such as ANTLR or custom recursive descent parsers. Parser rules explicitly define the mapping from document elements to AST nodes. For example, lines starting with # are parsed as Header1 nodes, lines starting with ## are parsed as Header2 nodes; consecutive non-empty lines are parsed as Paragraph nodes; and paragraphs conforming to specific regular expressions (such as those containing "year", "month", and "day" and right-aligned) are parsed as Signature nodes. Each node object contains attributes such as type, depth, rawText, and children, forming a complete tree structure.

[0039] Subsequently, the system traverses each node of the abstract syntax tree, querying the node type-style mapping table based on its node type. Figure 3 The mapping table predefines the national standard format attributes corresponding to various nodes: Header1 node corresponds to "Fangzheng Xiaobiao Song Simplified, 22pt, centered"; Header2 node corresponds to "Heiti, size 3, 2-character left indent"; Paragraph node corresponds to "Fangsong_GB2312, size 3, 28pt line spacing, 2-character first-line indent"; Signature node corresponds to "Right aligned, Fangsong_GB2312, size 3". Style attributes are appended to the node's metadata in key-value pairs (e.g., {"font_family": "FZXSBSJW", "font_size": 22, "alignment": "center"}), forming a node stream with style metadata. Figure 3 ).

[0040] For example, the node type-style mapping table is the key to connecting the document structure with the national standard (GB / T 9704-2012) format. This mapping table is stored in dictionary form and defines the set of typesetting attributes corresponding to each AST node type. According to the national standard, an example of the mapping table is as follows:

[0041] "Header1 (First-level heading): {"font_type”: "Xiaobiao Song typeface", "font_size_pt”: 22,"alignment”: "center", "space_after_pt”: 28}

[0042] Header2 (Second-level heading): {"font_type”: "Boldface", "font_size_pt”: 16,"alignment”: "left", "indent_first_line_chars”: 2}

[0043] Paragraph (Main text): {"font_type”: "Fang Song typeface", "font_size_pt”: 16,"alignment”: "Justified", "line_spacing_pt”: 28, "indent_first_line_chars”: 2}

[0044] Signature (Signature line): {"font_type”: "Fang Song typeface", "font_size_pt”: 16,"alignment”: "right”}”

[0045] The system traverses the AST, queries this table according to the node type, and injects the style attributes into the node metadata in key-value pair form. At the final rendering, font_type will be mapped to the corresponding specific font file in the operating system or font library (such as Xiaobiao Song typeface corresponding to "Founder Xiaobiao Song_GBK" or "STXiaobiaoSong").

[0046] Finally, the node stream with style metadata is converted into an OpenXML-compatible paragraph object stream. Each paragraph object contains <w:p>The tag, its child elements <w:ppr>Used to declare paragraph styles (such as line spacing, alignment, indentation). <w:r>Tags are used to carry text content, and their internal... <w:rpr>Declare the font family and font size. The system writes the paragraph object stream sequentially to the word / document.xml path of the .docx file, and simultaneously generates word / styles.xml (defining global styles) and word / settings.xml (fixing page margins, paper size, and other national standard parameters), finally outputting official document output conforming to the GB / T 9704 standard. Figure 1 ).

[0047] Throughout the entire process, the master control scheduling layer ( Figure 2 This mechanism coordinates the data and control flows between the planning, retrieval, writing, reviewing, and layout agents. Each agent communicates via message queues or a RESTful API, sharing data from the global policy repository and temporary task knowledge base. For example, after the writing agent generates a paragraph, it sends a "paragraph ready" event to the master control and scheduling layer. The master control and scheduling layer then notifies the reviewing agent to initiate verification. If the reviewing agent returns a structured feedback instruction, the master control and scheduling layer pauses subsequent processes and prioritizes scheduling the writing agent to perform partial regeneration. This adversarial collaborative architecture ensures tight coupling between content generation and quality control.

[0048] In a practical application scenario, suppose a staff member of a municipal government office needs to draft a "Notice on Carrying Out a Special Rectification of Safety Hazards of Electric Bicycles in the City." They input instructions through the user interface and upload relevant documents from the State Council's Safety Production Committee as reference material. The system's intent parsing module identifies the document type as "Notice," the subject as "Electric Bicycle Safety Rectification," and the issuing unit as "XX City Safety Production Committee Office." The outline generation module calls the "Notice" template and, combined with the reference material, generates an outline containing five parts: "Background of Rectification, Scope of Rectification, Key Tasks, Time Schedule, and Work Requirements." The evidence mounting module retrieves the "Electric Bicycle Safety Technical Specifications" (GB 17761-2018) and accident statistics for the city over the past three years for the "Key Tasks" node and mounts them as evidence blocks. The segmented writing module generates the content for each paragraph accordingly. When generating the "Time Schedule" paragraph, because the preceding "Key Tasks" paragraph is quite long, the system automatically injects its summary, "Focusing on the three major risk points of illegal modification, illegal charging, and old vehicles," as context. The review feedback module discovered a discrepancy between the initial draft's statement "rectification period from May to August 2024" and the evidence block's statement "rectification period from June 1 to September 30, 2024." Therefore, a structured feedback instruction was constructed, triggering a partial regeneration to correct the dates. The format rendering module ultimately parses the final text into an abstract syntax tree, injects national standard styles, and outputs it as a standard Word document, ready for direct use in official document issuance.

[0049] All modules and agents described above are deployed on the same electronic device, which includes a central processing unit (CPU), memory, a solid-state drive (SSD), and a network interface. The operating system runs a Linux distribution, and the software environment includes Python 3.9, PyTorch 2.0, Elasticsearch 8.5, and the Apache POI library. The code for modules such as intent parsing and outline generation is stored on the SSD and loaded into memory by the CPU for execution. The global policy database resides in memory as an Elasticsearch index, while the temporary task knowledge base is dynamically created as an SQLite database each time a task starts. Each agent communicates with the master scheduling layer via the gRPC protocol, ensuring low latency and high throughput. The entire system can also be deployed on a cloud server cluster, using Kubernetes for container orchestration to achieve elastic scaling and high availability.

[0050] To enable those skilled in the art to fully understand and implement this invention, the specific implementation principles of this invention are further supplemented below with a specific application scenario.

[0051] Step 1: The user submits the natural language command "Please draft a 'Notice on Carrying Out a Special Rectification of Safety Hazards of Electric Bicycles in the City'" to the system through the terminal device, and simultaneously uploads the PDF file of the "Notice on Strengthening the Safety Supervision of the Entire Electric Bicycle Chain" (Guo An Wei

[2023] No. 8) issued by the State Council Safety Committee as reference material. This input constitutes... Figure 1 The user input is displayed in the document. Upon receiving this input, the intent parsing module first calls a document type classification model fine-tuned based on a pre-trained language model (such as BERT) to identify the document type as "notice." Then, using a joint model of named entity recognition and dependency parsing, it extracts the core theme "rectification of safety hazards in electric bicycles," the issuing unit "XX City Safety Production Committee Office," the urgency level "normal / urgent," and the length requirement "approximately 1200 words" from the instruction. For the attached PDF file, the intent parsing module activates the OCR engine to complete image text recognition, and filters headers, footers, stamp areas, and scanning noise using regular expressions. The cleaned text is then segmented into text blocks of no more than 512 characters according to semantic boundaries and stored. Figure 2 The temporary task knowledge base shown is for subsequent retrieval and use.

[0052] Step 2: Activate the outline generation module Figure 2 The planning agent in the system loads a standard structure template for "notice" type official documents from a pre-set template library. This template defines five mandatory sections: "Background Basis," "Scope of Rectification," "Key Tasks," "Timeline," and "Organizational Support." The planning agent encodes text blocks from a temporary task knowledge base into 768-dimensional vectors using Sentence-BERT and, together with the template structure, constructs prompt words, which are then input into a large language model (such as ChatGLM3-6B) to guide the generation of a hierarchical outline tree that conforms to government logic. For example, for the "Key Tasks" node, the model output intent is "Clearly define three core measures: cracking down on illegal modifications, regulating charging behavior, and phasing out old and non-compliant vehicles." This outline tree is serialized in JSON format, containing the non-leaf node "III. Key Tasks" and its subordinate leaf nodes, and is then passed to the evidence mounting module.

[0053] Step 3: The evidence mounting module traverses all leaf nodes in the outline tree, performs semantic parsing on the content intent description of the "Key Tasks" node, "Clearly crack down on illegal modifications...", and... Figure 2 The retrieval agent generates a keyword sequence ["electric bicycle", "illegal modification", "charging safety", "old vehicles"] and its corresponding 768-dimensional semantic vector. The keyword sequence... Figure 2 Boolean retrieval is performed on the Elasticsearch inverted index of the global policy repository, while semantic vectors are retrieved using an Approximate Nearest Neighbor (ANN) algorithm in the FAISS vector database. Sparse retrieval score calculation: Using the generated keyword sequence, retrieval is performed in the global policy repository and temporary task knowledge base built on the inverted index. The BM25 algorithm is used to calculate the relevance score between each retrieval result fragment and the query keyword sequence, denoted as Skeyword. The BM25 algorithm comprehensively considers term frequency, inverse document frequency, and document length normalization, and is a common algorithm in the field of information retrieval. Semantic retrieval score calculation: The semantic vector describing the intent of the current node is compared with the semantic vectors of document fragments stored in the vector database, and cosine similarity is calculated, denoted as Ssemantic. The cosine similarity ranges from [-1, 1], and in text semantic similarity calculation, it is usually mapped to the [0, 1] interval as the relevance score. Score Normalization and Fusion: Due to the different numerical ranges and distributions of Skeyword and Ssemantic, to ensure fair weighting, the min-max normalization method is first used to normalize the two scores to the [0, 1] interval, resulting in Skeyword and Ssemantic. Subsequently, the normalized scores are linearly weighted and fused to calculate the comprehensive relevance score Sfinal for each document fragment.

[0054] Sfinal=α⋅Skeyword+β⋅Ssemantic

[0055] Wherein, α and β are weighting coefficients, and α + β = 1. The weighting coefficients can be adjusted according to the retrieval task to emphasize exact matching and semantic matching. In a preferred embodiment, α = 0.4 and β = 0.6 are set to place greater emphasis on semantic relevance. Result selection: All retrieved document fragments are sorted in descending order of their comprehensive score Sfinal, and the K highest-ranking fragments (e.g., K = 3, Top-3) are selected as evidence blocks for the current outline node. Each evidence block records its original text, source identifier, and its comprehensive score Sfinal (as a confidence score).

[0056] For example, one piece of evidence comes from Article 4.2 of the "Safety Technical Specifications for Electric Bicycles" (GB 17761-2018): "The total weight of the vehicle should not exceed 55kg, and the maximum design speed should not exceed 25km / h." Another piece of evidence comes from paragraph 3 of a user-uploaded file: "It is strictly forbidden to remove the speed limiter or replace the battery with a high-power one without authorization." Each piece of evidence is accompanied by the source identifier "GB 17761-2018 Article 4.2" and a confidence level of 0.92, and is attached to the "Key Tasks" leaf node in the form of key-value pairs to form an enhanced outline structure.

[0057] Step 4: Node-by-node scheduling of the segmented writing module Figure 2 The writing agent in the system. When processing the "Schedule" node, the writing agent assembles a prompt word, which includes three parts: system-level stylistic constraints "use formal, concise, and unambiguous official document language", the current node intent "clearly define the start and end dates and phase divisions of the special rectification campaign", and attached evidence blocks (including "the rectification period is from June 1 to September 30, 2024"). After the prompt word is input into the large language model, a first draft paragraph is generated: "This rectification campaign will run from May to August 2024, and will be carried out in three phases: investigation, rectification, and acceptance." At the same time, because the preceding "Key Tasks" paragraph is 320 characters long, the system triggers a sliding window mechanism: it calls a TextRank-based extractive summarization model to generate a summary of no more than 50 characters: "Focusing on the three major risk points of illegal modification, illegal charging, and old vehicles", and embeds this summary into the context of the current prompt word to maintain logical consistency across paragraphs.

[0058] The writing agent assembles prompts following a specific template structure to ensure the generated content meets requirements. A typical example of a prompt is as follows:

[0059] "

[0060] [System Instruction] You are a government document writing expert. Please use formal, solemn, and concise official written language, strictly follow the provided evidence materials, and avoid subjective assumptions and colloquial expressions.

[0061] [Current Chapter Intent] Please write the "Work Objectives" section, clearly stating the specific quantitative indicators that this special rectification campaign is expected to achieve.

[0062] [Relevant Evidence]

[0063] 1. Source: Item 3 of the "Key Points of Work of XX City Safety Production Committee in 2024": ...Strive to reduce the incidence of electric bicycle fire accidents by 20% by the end of 2024.

[0064] 2. Source: Statistics from the Municipal Fire Department: ...The safety qualification rate of existing charging facilities is approximately 85%.

[0065] [Writing Requirements] Based on the above material, please state the work objective in one paragraph, citing specific data.

[0066] This structured prompt clearly separates task instructions, context, constraints, and knowledge input, effectively guiding the large language model to generate accurate and reliable paragraph content.

[0067] Step 5: Start the review feedback module Figure 2 The intelligent review agent in the middle is responsible for generating the full text ( Figure 4 Perform verification. Named entity recognition module ( Figure 4 The time entity "May to August 2024" was extracted using the BiLSTM-CRF model, and the evidence block comparison module ( Figure 4 The system compared this with the attached evidence "June 1, 2024 to September 30, 2024". The system calculated an edit distance of 67, a semantic similarity of 0.32, and a comprehensive difference confidence level of 0.89, exceeding the preset threshold of 0.85, and thus classifying it as an E02 type error (data inconsistency). The review agent then generated a structured feedback instruction ( Figure 4 The content is {"offset": 1280, "error_code": "E02", "prompt": "Please correct the time statement according to the evidence block 'The rectification period is from June 1, 2024 to September 30, 2024'"}, and is processed through the main control scheduling layer ( Figure 2 Send to the writing agent. Local regeneration trigger ( Figure 4 Based on this, only rewrite the sentences containing errors, and output the corrected paragraph. Figure 4 "The rectification work will be carried out in three phases from June 1, 2024 to September 30, 2024."

[0068] The named entity recognition module in the review agent is built upon a structure combining a pre-trained language model (such as RoBERTa-wwm-ext) and a Conditional Random Field (CRF). This module is specifically designed for official documents and can identify and extract the following entity types from text: TIME (time, e.g., "June 1, 2024"), DATA (data, e.g., "90%)", LAW_REG (regulation name, e.g., "Regulations on the Management of Household Waste Classification"), DOC_NUM (document number, e.g., "State Council Document No. 12

[2023] "), ORG (organization name), LOC (location), etc. The model is trained on a manually labeled dataset of official document entities, achieving an F1 score of 95% to ensure accuracy.

[0069] Step Six: The format rendering module receives the final draft text. Figure 3 The text is in Markdown format and contains a first-level heading "# Notice on Carrying Out a Special Rectification Campaign for Safety Hazards of Electric Bicycles in the City" and a closing line "XX City Safety Production Committee Office, May 20, 2024". The syntax parser ( Figure 3 An abstract syntax tree is constructed based on regular expressions and a recursive descent algorithm. Figure 3 The title line is parsed as a Header1 node, and the signature line is identified as a Signature node. The system traverses this tree to query... Figure 3 The node type-style mapping table injects {"font_family": "FZXSBSJW", "font_size": 22, "alignment": "center"} into the Header1 node and {"alignment": "right", "font_family": "FangSong_GB2312", "font_size": 16} into the Signature node, forming a node stream with style metadata. Figure 3 Finally, the node is converted into an OpenXML paragraph object by the Apache POI library, written to word / document.xml, and simultaneously generates word / settings.xml with parameters such as A4 paper size, top 37mm / bottom 35mm margins, etc., outputting official document output conforming to GB / T 9704—2012 standard. Figure 1 (This can be used directly for printing official documents with red headers).

[0070] Additionally, the Large Language Model (LLM) used in this invention can employ a pre-trained model based on the Transformer architecture, such as ChatGLM3, the GPT series, ERNIE, or LLaMA, or other open-source or commercial models. To adapt to the specific style (formal, solemn, concise) and domain knowledge (policy and regulatory terminology) of official document writing, the Large Language Model undergoes supervised fine-tuning (SFT) before deployment using compliant official documents collected from publicly available government websites and standard document repositories at all levels. The fine-tuning instruction data format is (system instruction, user input, standard document output), for example, the system instruction is "You are a government document writing assistant," the user input is "Write the reason for issuing this document based on the following materials…", and the standard output is the corresponding standardized paragraph. Through fine-tuning, the model can stably generate text that conforms to the official document format and style.

[0071] All content not described in detail in the specification belongs to the prior art known to those skilled in the art, and the version parameters of each software component are not specifically limited. They can be implemented using conventional open source or commercial tools. The intermediate data structures and communication protocols not mentioned in this technical solution are not shown in the figure because they belong to the prior art, and will not be described here.

[0072] Although the present invention has been described in detail above with general descriptions and specific embodiments, modifications or improvements can be made to it, which will be obvious to those skilled in the art. Therefore, all such modifications or improvements made without departing from the spirit of the present invention fall within the scope of protection claimed by the present invention.< / w:rpr> < / w:r> < / w:ppr> < / w:p> < / w:r> < / w:ppr> < / w:p>

Claims

1. A method for intelligent official document writing based on a large language model and multi-agent collaboration, characterized in that, The method includes: It receives natural language commands and reference materials from users, and parses them to obtain the document type, core theme, issuing unit, urgency level, and length requirements; Based on the document type, a pre-set outline template library is invoked, and a hierarchical outline tree is generated by combining reference materials and stored in JSON format. Traverse each leaf node of the outline tree, generate an independent query vector for each node, perform a hybrid search in the global policy base and the temporary task knowledge base, mark the search results as evidence blocks and attach them to the corresponding outline nodes; Based on the outline tree and the attached evidence blocks, the writing agent is called node by node to generate paragraph content. When each paragraph is generated, a sliding window mechanism is used to introduce the previous paragraph summary as context input. The full text will be generated and input into the review agent, which will extract key entities and compare them with the evidence blocks in triplets. If an inconsistency is detected, a structured feedback instruction containing error location coordinates, error type, and modification suggestion Prompt will be constructed and sent back to the writing agent to trigger local regeneration. Once approved, the final text is parsed into an abstract syntax tree, identifying title nodes, body nodes, and signature nodes. Based on the preset node type and style definition mapping table, GB / T 9704 standard format attributes are injected, and the node stream with style attributes is encapsulated into a Word XML document.

2. The intelligent document writing method based on a large language model and multi-agent collaboration as described in claim 1, characterized in that, Generating a hierarchical outline tree involves: activating the planning agent, which loads a pre-set outline template matching the document type; vectorizing the user-provided reference materials after OCR recognition, cleaning, and segmentation; inputting the vectorized materials into a large language model to generate a tree-like outline that conforms to the logical structure of official documents; where each non-leaf node represents a chapter title, and each leaf node carries a description of the content intent.

3. The intelligent document writing method based on a large language model and multi-agent collaboration as described in claim 1, characterized in that, Performing a hybrid search involves: for each outline leaf node's content intent description, the search agent generates a keyword sequence and semantic vector, performs searches in the inverted index and vector database respectively, and selects the Top-K segments as evidence blocks after merging the two results by weighted scores. The evidence blocks include the original text, source identifier, and confidence score.

4. The intelligent document writing method based on a large language model and multi-agent collaboration as described in claim 1, characterized in that, The process of calling the writing agent node by node to generate paragraph content includes: assembling prompt words, which are composed of system-level official document style definitions, current node intent descriptions, and attached evidence blocks; calling a large language model to generate corresponding paragraphs; for documents with a total word length exceeding a preset threshold, when generating the Nth paragraph, the summary of the N-1th paragraph is embedded as additional context prompt words, and the summary is generated by a fixed-length extraction-based summarization model.

5. The intelligent document writing method based on a large language model and multi-agent collaboration as described in claim 1, characterized in that, The structured feedback instructions constructed by the review agent include: running the named entity recognition module to extract the time, data, regulation name, and document number from the generated text; comparing the extracted results with the evidence block attached to the corresponding outline node at the field level; if the difference confidence exceeds the threshold, recording the error position offset, error category code, and rewrite guidance prompt, and encapsulating it into a JSON format feedback instruction; the master control scheduling layer sends this instruction to the writing agent, triggering a partial regeneration of the specified text block, while retaining the rest of the approved content unchanged.

6. The intelligent document writing method based on a large language model and multi-agent collaboration as described in claim 1, characterized in that, Parsing into an abstract syntax tree involves: inputting the Markdown intermediate text into the syntax parser, constructing a tree structure that includes node types, hierarchical depth, and original text content, where first-level headings correspond to Header1 nodes, second-level headings correspond to Header2 nodes, body paragraphs correspond to Paragraph nodes, and the signature line corresponds to Signature nodes.

7. The intelligent document writing method based on a large language model and multi-agent collaboration as described in claim 1, characterized in that, Injecting GB / T 9704 standard format attributes includes: establishing a mapping table, wherein the mapping table defines the Header1 node as "Small Song typeface, 22 points, centered", the Paragraph node as "Fangsong_GB2312, size 3, 28 points line spacing", and the Signature node as "Right aligned, Fangsong_GB2312, size 3"; traversing each node of the abstract syntax tree, looking up the style definition in the table according to its type, and appending the style attributes to the node metadata in the form of key-value pairs.

8. The intelligent document writing method based on a large language model and multi-agent collaboration as described in claim 1, characterized in that, Encapsulated as a Word XML document, it includes: converting an abstract syntax tree with styled metadata into a stream of OpenXML-compatible paragraph objects, each paragraph object containing... <w:p>Tags and their child elements <w:ppr>Used to declare styles, <w:r> Used to carry text content; it writes the paragraph object stream sequentially to the document.xml path of the .docx file, and simultaneously generates styles.xml and settings.xml to solidify the national standard format specifications.< / w:r> < / w:ppr> < / w:p> 9. A document intelligent writing system based on a large language model and multi-agent collaboration, characterized in that, The system includes: The intent parsing module is used to receive user input and reference materials, and extract the document type, core theme, issuing unit, urgency level, and length requirements. The outline generation module is used to call preset templates and combine them with materials to generate a hierarchical outline tree in JSON format; The evidence mounting module is used to traverse the outline leaf nodes, perform mixed searches, and mark the results as evidence blocks to the corresponding nodes. The segmented writing module is used to generate paragraph content node by node and introduce a preceding summary as a sliding context in long document scenarios; The audit feedback module is used to perform fact consistency comparisons and generate structured feedback instructions to drive local rewriting when errors are detected. The format rendering module is used to parse the final text into an abstract syntax tree, inject GB / T 9704 standard format attributes, and output a Word XML document that conforms to GB / T 9704.

10. An electronic device 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 the method of any one of claims 1 to 8.