Large language model driven report generation agent method, system, equipment and medium

By constructing an autonomous intelligent agent execution framework and a structured intermediate file mechanism, the problems of autonomy and format standardization in report generation in existing technologies have been solved, realizing full-process automation from multi-source heterogeneous data to standard reports, and improving generation efficiency and content accuracy.

CN121859853APending Publication Date: 2026-04-14XIDIAN UNIV

Patent Information

Application Number
CN202511968868.5
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-12-24
Publication Date
2026-04-14

AI Technical Summary

Technical Problem

Existing technologies lack autonomy and flexibility in generating complex reports, and cannot achieve full-process automation, resulting in low generation efficiency and non-standard formats, failing to meet the end-to-end automated delivery requirements of modern office scenarios.

Method used

We construct an intelligent agent execution framework that does not rely on the native function call interface of a large language model. We use structured intermediate files as persistent intermediate representations throughout the entire process, and combine parent-child association dual-granularity retrieval, concurrency control and format mapping technology to achieve autonomous planning and task execution.

Benefits of technology

It achieves an end-to-end fully automated closed loop from multi-source heterogeneous data parsing to standard report generation, generating accurate and logically rigorous content that can be directly delivered as standard format documents without manual intervention, thus improving generation efficiency and system robustness.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121859853A_ABST
    Figure CN121859853A_ABST
Patent Text Reader

Abstract

The invention discloses a report generation agent method, system and device driven by a large language model and a medium, and the method comprises the steps: constructing an agent execution framework independent of a native interface, outputting a decision through a cue word constraint model in a JSON structure, and scheduling a local tool function; analyzing the reference data and constructing a local vector knowledge base supporting semantic retrieval; the intelligent agent autonomously plans and generates a report directory structure based on a local vector knowledge base, stores the report directory structure as a structured intermediate file as a persistent intermediate representation, generates chapter content in parallel by utilizing a concurrent flow control and exponential backoff retry mechanism and combining a mixed retrieval strategy, and serializes and updates the chapter content to the intermediate file in real time; and finally, converting the intermediate file into a target format report according to a mapping rule. The system, the equipment and the medium are used for implementing the method. According to the method, the efficiency and the accuracy of complex report generation are remarkably improved through agent whole-process autonomous driving and combination of persistent intermediate representation, retrieval enhancement and concurrency control technologies.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the fields of natural language processing and artificial intelligence, and more specifically, to a method, system, device, and medium for a report generation agent driven by a large language model. Background Technology

[0002] With the rapid development of deep learning technology, large language models have demonstrated powerful text understanding and generation capabilities, gradually evolving from simple question-and-answer dialogues to intelligent agents with autonomous planning and execution capabilities. In the fields of office automation and digital transformation, automatically generating long professional documents such as software requirements specifications, technical reports, and bidding documents using large language models has become an important direction for improving productivity. Several document generation solutions based on large models have emerged in the industry, attempting to automate the tedious workflow of data collection, outline planning, and content writing, thereby reducing the cost and error rate of manual writing.

[0003] In existing technologies, the generation of complex reports mainly adopts the following technical approaches: First, a template-based generation path based on "classification-fill-in," which involves first using a classifier to pre-classify user needs, and then guiding the model to fill in the content according to a fixed industry template; second, a linear workflow orchestration, which involves pre-coding fixed "outline generation-content filling-review" steps, or heavily relying on native function call interfaces provided by specific closed-source large models to achieve tool scheduling; and third, the use of general search-enhanced generation techniques, which assist the model in generating content by performing simple segmentation and vector retrieval of reference materials. Meanwhile, in the document preprocessing stage, a general framework or a single OCR engine is typically used to handle heterogeneous file formats.

[0004] Zhejiang Jinhui Digital Technology Co., Ltd. disclosed a fully intelligent method based on a large model in its patented technology "Automatic Generation and Multi-dimensional Review Method and System for Standard Documents Based on Large Models" (Application No.: CN202511093418.6, Authorization Publication No.: CN120597846A). This method includes knowledge network construction (collecting multi-source heterogeneous documents to form a distributed database and constructing a standardized knowledge network through NLP analysis), structured parameter extraction (automatically extracting quantitative indicators and eliminating conflicts through validation and cross-validation), automatic document outline generation (generating standardized outlines based on template libraries and semantic matching), document draft content writing (retrieving similar fragments and recombining content), multi-dimensional intelligent review (converting key data into 3D point cloud data and constructing an arc detection path based on industry indicators to analyze path curvature recognition problems), and knowledge feedback and system self-optimization (dynamically adjusting weights through machine learning analysis of error distribution). The drawback of this method is that the complexity of the review dimensions may lead to low computational efficiency, and point cloud data processing places high demands on hardware.

[0005] Hunan University disclosed a "classify first, then generate" technical approach in its patented technology "An Automatic Generation Method for Software Requirements Specification Documents Based on a Large Language Model" (Application No.: CN202510580895.9, Authorization Publication No.: CN120524932A). This approach includes text preprocessing (segmentation, deduplication, and cleaning using the simhash algorithm), training a requirements classifier (designing a BERT-GCN model combining BERT semantic understanding and GCN structural capture capabilities), a multi-classification task (inputting the classifier and outputting labeled text), generating a standard requirements document (formatted according to the ISO / IEC / IEEE 29148 template, using a Prompt template to guide the large language model to generate Markdown format documents), and instruction evaluation and verification (combining anonymous expert scoring and automated scoring to evaluate the scope of requirements and the document scope). The shortcomings of this method are that classification accuracy depends on the quality of the training data, the "classify first, then generate" mode may lead to classification errors and generation bias under complex requirements, and it lacks real-time interactive optimization.

[0006] The aforementioned existing technologies still have many shortcomings in practical applications, generally exhibiting limitations in intelligence, flexibility, and engineering capabilities. This prevents a fundamental change from the traditional, time-consuming, and error-prone nature of document writing methods. Specifically, in task planning, most existing solutions are static linear pipelines, lacking true agent autonomy, relying on specific APIs, and unable to perform thought chain reasoning and self-correction. In data processing, parsing schemes struggle to balance accuracy and contextual integrity, leading to fragmented information retrieval. Particularly significant is the inability of existing technologies to truly achieve a fully automated closed loop from uploading reference files and inputting task descriptions to the agent autonomously planning and generating structured reports. Due to the lack of a persistence mechanism for intermediate states and precise format mapping capabilities, heterogeneous content generated by the model cannot be directly converted into standard Word format files. This necessitates significant manual intervention in key intermediate steps and final formatting, severely restricting the overall efficiency and delivery quality of report generation, and failing to meet the stringent requirements of end-to-end automated delivery in modern office scenarios. Summary of the Invention

[0007] To overcome the shortcomings of the prior art, the present invention aims to provide a method, system, device, and medium for generating reports driven by a large language model. By constructing an autonomous intelligent agent execution framework that does not rely on the native function call interface of the large language model, utilizing structured intermediate files as persistent intermediate representations throughout the entire process, and combining parent-child association dual-granularity retrieval, exponential backoff-based concurrency control, and automated format mapping technology, it can achieve an end-to-end fully automated closed loop from multi-source heterogeneous reference material parsing, autonomous task planning, deep context fusion to complex format standard report generation. It has the advantages of high degree of automation throughout the process, accurate and logically rigorous generated content, strong system execution robustness, and the ability to directly deliver standard official document format documents without manual intervention.

[0008] To achieve the above objectives, the technical solution adopted by the present invention is as follows: A report generation agent method driven by a large language model includes the following steps: Step 1, Construct the agent execution framework: The design incorporates prompt word templates that include thought chain reasoning content and action instructions. The output of the large language model is formatted and constrained to obtain a preset JSON structure to generate decision information. After parsing, the local utility function is scheduled, enabling the large language model to complete autonomous planning and task execution in the "perception-reasoning-execution-feedback" loop, forming an independently running report generation agent. Step 2, Preprocessing Reference Materials: The system parses the reference files provided by the user, extracts the text content and document structure information, preprocesses the extraction results, and saves the processed data as a structured file of the references. Step 3, Build a local vector knowledge base: The structured reference files obtained in step 2 are semantically segmented and vectorized to generate a searchable document vector index, which is then persistently stored. Step 4, generate the report directory structure: The intelligent agent execution framework built in step 1 autonomously plans based on the task description generated by the user's report, retrieves the local vector knowledge base built in step 3 based on the task description generated by the report to obtain relevant reference materials, calls the report directory generation tool to create a report directory structure containing chapter levels, and saves the report directory structure as a structured intermediate file. Step 5, and generate chapter content: The intelligent agent execution framework built in step 1, based on the report directory structure in the structured intermediate file obtained in step 4, generates specific requirements or retrieves the local vector knowledge base built in step 3 using the chapters input by the user. It can also optionally trigger network search, call the report content generation tool, and drive the generation of chapter content using concurrent flow control and exponential backoff retry mechanism. The generated chapter content is updated to the document structure object in memory, and the complete document structure object is serialized and overwritten and saved to the structured intermediate file to complete the persistent storage of data. Step 6: Based on the structured intermediate file updated in Step 5, the intelligent agent execution framework built in Step 1 calls the format conversion tool to convert it into a target format report file according to the preset mapping rules.

[0009] The specific method of step 1 includes: Step 110: Based on the reasoning and action collaboration paradigm, design a structured prompt word template that includes thought chain reasoning content and action instructions, set dynamic slots for describing task objectives, behavioral constraints, executable actions and resource information, and configure unified response format rules to format and constrain the reasoning content and action instructions of the large language model to obtain a preset JSON structure to generate decision information. Step 111: Build a custom tool library, establish a mapping relationship between action identifiers and tool functions, and generate natural language text of tool names, function descriptions, and parameter definitions; Step 112: Construct a task state management and context compression mechanism to record the inference content and execution feedback of the model in each round, and perform summary compression on the historical records when the context length exceeds a preset threshold to ensure the continuity of long-term task execution and inference stability, forming an independently run report generation agent; Step 113: Establish a collaborative closed-loop control process for inference and execution, assemble the context, trigger model inference, parse action instructions, schedule local utility functions, and return execution observations to perform continuous iteration between model inference and utility function execution results.

[0010] The specific method for step 2 includes: Step 220, File Format Recognition and Verification: Receive the file stream uploaded by the user, parse the file extension, and identify the document type, including DOCX or PDF file format documents; Step 221, DOM traversal and structure restoration of DOCX documents: For DOCX documents, the document object model traversal technique is used to extract text while simultaneously parsing style attributes to preserve chapter hierarchy and reconstructing the two-dimensional structure of tables. Step 222, Adaptive dual-channel extraction of PDF documents: The underlying native text stream is directly extracted using the PyMuPDF library, and text density detection is performed to evaluate the effective character ratio. When the page is determined to be a scanned document or low-density text, a degradation mechanism is automatically triggered, and the PaddleOCR library is called to perform deep recognition on the high-resolution rendered image to achieve full coverage analysis of both native and scanned PDFs. Step 223, Standardization and serialization of multi-source heterogeneous data: The content parsed from the corresponding documents is uniformly converted into a structured key-value pair sequence containing metadata and saved as a structured file of reference materials.

[0011] The specific method for step 3 includes: Step 330, Structured text objectification processing: Convert the key-value pair data of the reference material structured file obtained in Step 2 into a standardized document object containing content fields and metadata fields; Step 331, Dual-granularity semantic segmentation and parent-child association construction: A dual-layer segmentation strategy is performed on the standardized document object obtained in step 330. First, the standardized document object is segmented into parent semantic blocks with complete semantic logic, and a globally unique identifier is generated for each parent semantic block. Then, the parent semantic blocks are recursively refined into child fine-grained blocks, and the parent unique identifier is injected into the metadata of all corresponding child fine-grained blocks to establish a traceable parent-child mapping relationship. Step 332, High-dimensional vectorized embedding generation: The local embedding model is called to generate dense vector representations only for fine-grained sub-blocks, and vector normalization and feature dimension configuration are handled uniformly; Step 333, Hierarchical Vector Retrieval Structure Construction: Construct a separate storage architecture consisting of a vector storage layer and a document storage layer. After associating the dense vectors of the child-level fine-grained blocks generated in Step 332 with their corresponding metadata containing the parent's unique identifier, store them in the vector storage layer configured with an approximate nearest neighbor index. At the same time, using the parent's unique identifier generated in Step 331 as the key, store the complete text of the parent semantic block in the key-value document storage layer. Based on this, configure a retrieval-recall logic based on the association of the parent's unique identifier. That is, first perform similarity retrieval on the dense vectors of the child-level fine-grained blocks to obtain the dense vectors of the child-level fine-grained blocks with their corresponding metadata containing the parent's unique identifier. Then, based on the parent's unique identifier in the metadata of the hit child-level fine-grained blocks, retrieve the corresponding parent text blocks from the document storage layer and remove duplicates. This realizes a combined retrieval strategy of "retrieving high-precision child blocks and returning the full context parent block" and persists it as a local vector knowledge base.

[0012] The specific method for step 4 includes: Step 440, triggering retrieval enhancement and multi-source information fusion: The agent execution framework built in step 1 parses the user's report to generate a task description, triggers a hybrid retrieval and network enhancement mechanism, recalls relevant reference materials from the local vector knowledge base built in step 3, and optionally performs network search, fuses and summarizes the obtained multi-source information, and forms reference materials for catalog generation; Step 441, Construct directory generation prompts and execution planning reasoning: Inject the user's report generation task description, the reference materials obtained in step 440, the list of executable tools, and the forced model with predefined output format constraints into the directory generation prompt template, and send the prompt template to the large language model for reasoning to generate a report directory structure containing chapter levels; Step 442, Persistent storage of structured intermediate files: Write the report directory structure generated in step 411 into a structured intermediate file and save it as a local file as a persistent intermediate representation throughout the entire process.

[0013] The specific method for step 5 includes: Step 550, Initialize persistent intermediate representation and context retrieval: Load the structured intermediate file obtained in step 4 into memory, build a document object tree, traverse the report directory structure of the content to be generated, execute the intelligent agent framework built in step 1, and trigger the context retrieval of the local vector knowledge base built in step 3 based on the chapter titles of the directory structure. Step 551, concurrent flow control scheduling based on thread pool: Instantiate the thread pool executor, combine the semaphore mechanism to limit the number of concurrent requests, and submit the encapsulated chapter generation task to the scheduling queue; Step 552, Content generation based on exponential backoff retry mechanism: Integrate exponential backoff strategy into model call layer, and perform dynamic delayed retry when generation request fails due to network or service fluctuations to ensure the robustness of task; Step 553, Memory State Update and Atomic Persistent Storage: A mutex-based memory synchronization and full serialization overwrite strategy is adopted. After the generated chapter content is safely updated to the document structure object in memory through the mutex, the complete document structure object is serialized and overwritten to the disk, maintaining the persistent intermediate representation of the entire process and completing the persistent storage of data.

[0014] The specific method for step 6 includes: Step 660, Document object initialization and global layout configuration: The intelligent agent execution framework built in step 1 calls the format conversion tool to deserialize the structured intermediate file, instantiate the target document object, and configure the global font, line spacing and alignment in accordance with Chinese official document standards; Step 661, Dynamic mapping of multi-level heading styles: Traverse the document node tree, dynamically match and apply preset heading styles according to the node's hierarchy attributes, including switching between bold and SimSun fonts, and forcibly applying East Asian font settings. Step 662, Composite Content Parsing and Dual-Channel Table Rendering: Perform DOM parsing and cell merging restoration on HTML format tables, and perform regular matrix parsing on Markdown tables to achieve accurate reconstruction of complex layouts; Step 663, Multimedia resource embedding and target document interaction: Parse image paths and perform embedded insertion and automatic caption formatting. Finally, the format conversion tool serializes the fully constructed in-memory document stream and saves it as a target format report file, completing the delivery.

[0015] This invention also provides a large language model-driven report generation intelligent agent system, comprising: The intelligent agent engine module is used to build the intelligent agent execution framework. It designs prompt word templates that include thought chain reasoning content and action instructions, formats and constrains the output of the large language model, obtains the preset JSON structure to generate decision information, and then parses and schedules local utility functions. This enables the large language model to complete autonomous planning and task execution in the "perception-reasoning-execution-feedback" loop, forming an independently run report generation intelligent agent. The data processing module is used to parse the reference files provided by the user, extract the text content and document structure information, preprocess the extraction results, and save the processed data as a structured file of the references. The knowledge base construction module is used to perform semantic segmentation and vectorization processing on the structured files of reference materials, generate a searchable document vector index, and persist it for storage. The report catalog generation module is used to enable the intelligent agent to execute the framework, autonomously plan according to the user's report generation task description, retrieve the local vector knowledge base based on the report generation task description to obtain relevant reference materials, call the report catalog generation tool to create a report catalog structure containing chapter levels, and save the report catalog structure as a structured intermediate file; The report content generation module is used to enable the intelligent agent to execute the framework, generate specific requirements or chapter titles based on the report directory structure in the structured intermediate file, retrieve local vector knowledge base, and optionally trigger network search, call the report content generation tool, drive the generation of chapter content using concurrent flow control and exponential backoff retry mechanism, update the generated chapter content to the document structure object in memory, and serialize the complete document structure object and overwrite and save it to the structured intermediate file to complete the persistent storage of data; The format conversion module is used to convert the updated structured intermediate file into a target format report file by having the intelligent agent execute the framework to call the format conversion tool and convert it according to preset mapping rules.

[0016] The present invention also provides a large language model-driven report generation agent device, comprising: Memory: A computer program that stores the above-mentioned method for generating a report agent driven by a large language model, and is a computer-readable device; Processor: Used to implement the large language model-driven report generation agent method when executing the computer program.

[0017] The present invention also provides a computer-readable storage medium storing a computer program that, when executed by a processor, enables the implementation of the aforementioned large language model-driven report generation agent method.

[0018] Compared with the prior art, the beneficial effects of the present invention are as follows: 1. This invention constructs an intelligent agent execution framework that does not rely on the native function call interface of a large language model. It employs structured prompt word templates containing thought chain reasoning content and action instructions to format and constrain the model output, enabling the large language model to achieve complete autonomous planning and task execution in a "perception-reasoning-execution-feedback" loop. This mechanism overcomes the shortcomings of existing technologies, such as the lack of autonomy in static linear pipelines and poor scalability due to excessive reliance on specific model APIs, achieving an end-to-end intelligent closed loop from task description to action execution.

[0019] 2. This invention constructs a hierarchical vector retrieval structure based on parent-child relationships and implements a combined retrieval strategy of "retrieving high-precision child blocks and returning the full context of the parent block." This effectively solves the problem of balancing retrieval granularity and semantic integrity in traditional RAG technology. By generating dense vectors for retrieval only at the fine-grained child level and using the unique parent identifier in the metadata to recall the complete parent text block, it ensures retrieval accuracy and provides semantically coherent and logically complete contextual basis for model generation, significantly improving the accuracy and traceability of report content.

[0020] 3. This invention utilizes structured intermediate files as a persistent intermediate representation throughout the entire process. Combined with thread pool-based concurrent flow control, an exponential backoff retry mechanism, and a mutex-based memory synchronization and full serialization overwrite strategy, it significantly improves the efficiency and robustness of generating complex long documents. This mechanism breaks through the efficiency bottleneck of traditional serial generation, ensures data consistency and security under network fluctuations or service anomalies, supports seamless task resumption, and solves the problem of task interruption and difficulty in recovery caused by the lack of intermediate state management in existing technologies.

[0021] 4. This invention achieves accurate reconstruction of complex layouts by performing DOM parsing and cell merging restoration on HTML format tables and regular matrix parsing on Markdown tables. It also implements dynamic mapping of multi-level heading styles and automatic embedding of multimedia resources, enabling the automatic conversion of heterogeneous content generated from large models into target format report files conforming to Chinese official document standards. This mechanism solves the industry pain points of existing technologies, such as messy document formats, inability to handle complex layouts, and heavy reliance on manual post-layout formatting, achieving true end-to-end automated delivery.

[0022] In summary, compared with existing technologies, this invention comprehensively constructs an intelligent agent execution framework that does not rely on the native function call interface of a large language model, a hierarchical vector retrieval structure with parent-child association, a persistent intermediate representation of structured intermediate files, and composite content parsing and rendering technology. It effectively overcomes the shortcomings of existing technologies in terms of task planning autonomy, context retrieval completeness, long-process execution robustness, and document delivery standardization, and achieves end-to-end full-process automation from multi-source heterogeneous data input to target format report output conforming to Chinese official document standards. Attached Figure Description

[0023] Figure 1 This is a flowchart illustrating a report generation agent method driven by a large language model, provided in an embodiment of the present invention.

[0024] Figure 2 This is a schematic diagram of a large language model-driven report generation intelligent agent system provided by an embodiment of the present invention.

[0025] Figure 3 This is a schematic diagram of a structured intermediate file fragment representing the report directory structure generated in an embodiment of the present invention.

[0026] Figure 4 Based on the embodiments of the present invention Figure 3 This is a diagram illustrating the table of contents layout of a Word file generated from a structured intermediate file.

[0027] Figure 5This is a schematic diagram of a complete document structure object structured intermediate file fragment generated in an embodiment of the present invention.

[0028] Figure 6 Based on the embodiments of the present invention Figure 5 This is a diagram illustrating the text layout of a Word report file generated from a structured intermediate file conversion.

[0029] Figure 7 This is a schematic diagram of the original content fragment of an HTML table in a structured intermediate file in an embodiment of the present invention.

[0030] Figure 8 Based on the embodiments of the present invention Figure 7 This is a diagram illustrating the restoration effect of the original content of an HTML table. Detailed Implementation

[0031] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Although exemplary embodiments of the present disclosure are shown in the drawings, it should be understood that those skilled in the art can obtain other drawings based on these drawings without creative effort.

[0032] like Figure 1 As shown in the figure, this invention proposes a report generation agent method driven by a large language model, which includes the following steps: Step 1, Construct the agent execution framework: This framework does not rely on the native function call interface of the large language model. Instead, it designs prompt word templates that contain thought chain reasoning content and action instructions to format and constrain the output of the large language model, obtains a preset JSON structure to generate decision information, and then parses it to schedule local utility functions. This allows the large language model to complete autonomous planning and task execution in the "perception-reasoning-execution-feedback" loop, forming an independently running report generation agent. In a preferred embodiment of the present invention, the specific method of step 1 includes: Step 110: Based on the reasoning and action collaboration paradigm, design a structured prompt word template that includes thought chain reasoning content and action instructions, set dynamic slots for describing task objectives, behavioral constraints, executable actions and resource information, and configure unified response format rules to format and constrain the reasoning content and action instructions of the large language model to obtain a preset JSON structure to generate decision information. Step 111: Build a custom tool library, establish a mapping relationship between action identifiers and tool functions, and generate natural language text of tool names, function descriptions and parameter definitions so that the large language model can understand the capabilities and calling methods of each tool. Step 112: Construct a task state management and context compression mechanism to record the inference content and execution feedback of the model in each round, and perform summary compression on the historical records when the context length exceeds a preset threshold to ensure the continuity of long-term task execution and inference stability, forming an independently run report generation agent; Step 113: Establish a collaborative closed-loop control process for inference and execution, assemble the context, trigger model inference, parse action instructions, schedule local utility functions, and return execution observations to perform continuous iteration between model inference and utility function execution results.

[0033] In this embodiment of the invention, in step 110, a structured prompt word generation logic is first configured. Specifically, a basic prompt word template is defined, which contains four key dynamic injection slots: {query} for receiving the user's specific task goal; {constraints} for injecting the system's behavioral constraints; {actions} for injecting descriptions of available tools; and {resources} for injecting descriptions of available resources. To guide the model in structured reasoning, this embodiment designs a response format constraint template, which mandates that the model output in JSON format. This JSON structure contains two core fields: the action identifier field, which contains name (action name) and args (parameter dictionary), used to explicitly indicate the specific operation to be performed next and the required parameters, for example, {"name": "write_to_file", "args": {"filename": "...", "content": "..."}}. The thoughts field contains plan (long-term and short-term plans), reasoning (reasoning logic), criticism (self-reflection), and observation (current progress observation). This design forces the model to generate the `thoughts` field before executing the utility function corresponding to the `actions` field, thus achieving explicit output of the thought chain. Furthermore, specific logical constraints are explicitly defined in the constraint list, such as "strictly prohibiting the execution of the same action multiple times, especially the file writing action can only be executed once." These constraint texts are directly appended to the prompt words, thereby providing hard control over the model's behavioral boundaries during the inference phase.

[0034] In step 111, a custom tool library is built and the function mapping logic is configured. First, a global tool mapping registry with a hash dictionary structure is established, mapping the string-form action identifier (actions) field to specific program function objects. For example, the key "search" is mapped to the search tool function, and the key "generate_report_catalogue" is mapped to the report catalog generation function. Second, the tool description generation logic is implemented. This logic traverses the predefined tool metadata list, extracts the name (tool name), description (function description), and args (parameter definition) of each tool, and formats this metadata into natural language text. This text is then injected into the action identifier (actions) field slot of the aforementioned prompt word template, enabling the large language model to understand the purpose and invocation method of each tool. In the specific tool implementation, such as the search tool function, a search engine interface (TavilySearchResults is used in this embodiment) is integrated internally. It receives query keyword parameters, performs network retrieval, and concatenates the returned list data (including content summaries and link addresses) into a single string and returns it as an external knowledge source for the agent.

[0035] In step 112, to maintain long-cycle task execution, this embodiment configures task state management logic to maintain session state. Before each round of agent execution, historical information summary compression logic is executed. This logic detects the length of the currently accumulated interaction history. When the content is too long, it automatically performs text summarization on past actions, thoughts, and observations, retaining only key information to obtain a historical summary. After the tool finishes execution, state update logic is executed, appending the observation descriptions generated by the model and the actual execution results returned by the tool to the state record and saving it to the current task state information. This mechanism ensures that in the next round of inference, the model can "see" the actual consequences of the previous round of operations, thereby making new plans based on the latest task state, realizing a complete closed loop from "planning" to "feedback".

[0036] In step 113, the core control flow logic of the agent is implemented. This control flow maintains the operation of the agent through a loop structure. The specific logic is as follows: Assemble the context: Obtain the historical record summary processed in step 112, and combine it with the current task state information, and concatenate it with the basic prompt word template in step 110 to generate the final prompt word containing complete context information; Trigger model inference: Call the large language model interaction interface, pass in the prompt word, and obtain the model's text response; Parse action instructions: After receiving the response, the system first verifies whether it is a valid dictionary format and contains the actions and thoughts fields; then, the parser extracts the name and args from the actions dictionary. Tool scheduling and execution: The system uses the parsed action name to search for the corresponding function object in the tool mapping registry. If the search is successful, the parameters are directly passed to the function for execution by unpacking the parameters. If the search fails, the system proceeds directly to the next iteration. Scheduling local tool functions and feedback of execution observations: The execution result of the tool function is captured as the execution result and broadcast using a message publishing mechanism. At the same time, the result is fed back to the agent as an "observation," completing a complete "perception-reasoning-execution-feedback" closed loop. Finally, the task state management logic defined in step 112 is called to concatenate the actions, thoughts, and observations generated in this round with the old prompt words to form a new prompt word, and the system proceeds to the next iteration.

[0037] Step 2, Preprocessing Reference Materials: The system parses user-provided reference files, extracts text content and document structure information, preprocesses the extraction results, and saves the processed data as a structured file of the reference materials as input for subsequent knowledge base construction. In a preferred embodiment of the present invention, step 2 specifically includes: Step 220, File Format Recognition and Verification: Receive the file stream uploaded by the user, parse the file extension, identify the document type, including DOCX or PDF file format documents, and determine the corresponding parsing method to be used subsequently; Step 221, DOM traversal and structure restoration of DOCX documents: For DOCX documents, the document object model traversal technique is used to extract text while simultaneously parsing style attributes to preserve chapter hierarchy and reconstructing the two-dimensional structure of tables. Step 222, Adaptive dual-channel extraction of PDF documents: The underlying native text stream is directly extracted using the PyMuPDF library, and text density detection is performed to evaluate the effective character ratio. When the page is determined to be a scanned document or low-density text, a degradation mechanism is automatically triggered, and the PaddleOCR library is called to perform deep recognition on the high-resolution rendered image to achieve full coverage analysis of both native and scanned PDFs. Step 223, Standardization and serialization of multi-source heterogeneous data: The content parsed from the corresponding documents is uniformly converted into a structured key-value pair sequence containing metadata and saved as a structured file (JSON) of the reference materials.

[0038] In step 220, after receiving the reference file uploaded by the user, its type is determined by reading the file extension (e.g., ".docx", ".pdf"). Based on this identification result, the file is automatically assigned to the corresponding parsing module. This process is the entry point for the entire preprocessing workflow, ensuring that DOCX format files are processed by the structured document parsing module, while PDF files enter the native text stream parsing or scanning recognition process, thus fundamentally avoiding reading failures or structural errors caused by formatting errors.

[0039] In step 221, for references identified as DOCX, the system loads the Document Object Model (DOM) using the python-docx library. The parsing module traverses the document structure segment by segment, starting from the Paragraphs node, extracting the text content and style of each paragraph, and automatically identifying the "Heading 1–Heading 9" hierarchy information to restore the original document's chapter structure. Based on this, the system simultaneously scans the Tables node in the document, extracting the table content row by row and cell by cell, and then rewriting it into a consistent text structure using pipes or tabs, ensuring that the logical layout of the tables is preserved in the plain text representation.

[0040] In step 222, for PDF documents, an adaptive dual-channel parsing strategy based on PyMuPDF (fitz) and PaddleOCR is adopted. Specifically, the PyMuPDF library is used to load the PDF document object, and the document's page indices are traversed. For each page, the `page.get_text("text")` method is called to directly access the underlying content stream of the PDF. This method bypasses the image rendering layer, directly decodes and extracts the raw text data stored in character encoding, and simultaneously records the original page number and text block coordinates of the current content. This process does not involve pixel-level processing, has extremely high execution efficiency, and is suitable for all non-scanned electronic raw PDF documents. After extracting the text of the current page, text density detection is performed, and the ratio of the number of extracted effective characters to the page size is calculated. If there are very few effective characters or the page content is mainly composed of "Image" objects (i.e., it is determined to be a scanned document or a pure image PDF), a degradation processing mechanism will be automatically triggered, switching to the OCR extraction strategy. When entering the OCR strategy, the `page.get_pixmap(matrix=fitz.Matrix(zoom, zoom))` method from the PyMuPDF library is used again to render the current PDF page as a high-resolution bitmap image (RGB format). The zoom factor is set between 2.0 and 3.0 to ensure the generated image DPI meets the requirements for high-precision recognition. Subsequently, the PaddleOCR library is called to stream the rendered image data. PaddleOCR loads the pre-trained lightweight Chinese detection and recognition model (PP-OCRv4), performs text detection (DBNet algorithm) and text recognition (CRNN algorithm) on the image, converts the image information into machine-encoded text, and marks it as the scanned content corresponding to the page number.

[0041] In step 223, the parsed DOCX or PDF content is integrated into a structured key-value pair sequence containing metadata. Unlike the traditional single string output, this embodiment uses a JSON key-value pair list for storage. Each list item contains: content (cleaned text fragment), type (type identifier, such as Title, Level, Paragraph, Table), and metadata (metadata dictionary, including source file name, original page number, chapter level, etc.). This structured file is saved to a local temporary storage area and directly serves as a high-quality input source for building the local vector knowledge base in step 3.

[0042] Step 3, Build a local vector knowledge base: The structured reference files obtained in step 2 are semantically segmented and vectorized to generate a searchable document vector index, which is then persistently stored. In a preferred embodiment of the present invention, step 3 specifically includes: Step 330, Structured text objectification processing: Convert the key-value pair data of the reference material structured file obtained in Step 2 into a standardized document object containing content fields and metadata fields, providing a unified data structure for subsequent segmentation and retrieval; Step 331, Dual-granularity semantic segmentation and parent-child association construction: A dual-layer segmentation strategy is performed on the standardized document object obtained in step 330. First, the standardized document object is segmented into parent semantic blocks with complete semantic logic, and a globally unique identifier is generated for each parent semantic block. Then, the parent semantic blocks are recursively refined into child fine-grained blocks, and the parent unique identifier is injected into the metadata of all corresponding child fine-grained blocks to establish a traceable parent-child mapping relationship. Step 332, High-dimensional vectorized embedding generation: The local embedding model is called to generate dense vector representations only for fine-grained sub-blocks, and vector normalization and feature dimension configuration are handled uniformly; Step 333, Hierarchical Vector Retrieval Structure Construction: Construct a separate storage architecture consisting of a vector storage layer and a document storage layer. After associating the dense vectors of the child-level fine-grained blocks generated in Step 332 with their corresponding metadata containing the parent's unique identifier, store them in the vector storage layer configured with an approximate nearest neighbor index. At the same time, using the parent's unique identifier generated in Step 331 as the key, store the complete text of the parent semantic block in the key-value document storage layer. Based on this, configure a retrieval-recall logic based on the association of the parent's unique identifier. That is, first perform similarity retrieval on the dense vectors of the child-level fine-grained blocks to obtain the dense vectors of the child-level fine-grained blocks with their corresponding metadata containing the parent's unique identifier. Then, based on the parent's unique identifier in the metadata of the hit child-level fine-grained blocks, retrieve the corresponding parent text blocks from the document storage layer and remove duplicates. This realizes a combined retrieval strategy of "retrieving high-precision child blocks and returning the full context parent block" and persists it as a local vector knowledge base.

[0043] In this embodiment, in step 330, the key-value pairs of the reference structured files obtained in step 2 are objectified using the LangChain framework. The system traverses the structured text items in memory and encapsulates them into LangChain standard Document objects. The text content is written to the `page_content` field; information such as the source file name, chapter title, heading level, and original page number is written to the `metadata` dictionary. In this way, the originally unstructured string data is transformed into a standardized document object containing content and metadata fields, providing a unified data format foundation for subsequent semantic segmentation, retrieval, and recall.

[0044] In step 331, the ParentDocumentRetriever component is invoked to perform a dual-granularity segmentation strategy on the Document object. First, a parent segmenter is defined to divide the standardized document object obtained in step 330 into large-granularity parent blocks (e.g., 2000 tokens) with complete semantic logic, ensuring content continuity in the subsequent response generation stage. Then, a child segmenter (e.g., RecursiveCharacterTextSplitter) is used to recursively refine the parent blocks, generating multiple child-level fine-grained blocks. The system generates a unique UUID for each parent block and injects this UUID into the metadata of all child-level fine-grained blocks, thus forming a strict parent-child mapping relationship. This mechanism balances the contradiction between "high retrieval granularity but poor context preservation" and "complete context but coarse vector granularity," providing structural support for subsequent recall strategies.

[0045] In step 332, the HuggingFaceEmbeddings interface is called to load the locally deployed language embedding model, and vector normalization and dimensionality parameters are configured according to task requirements. The system only performs vector mapping on child-level fine-grained blocks, converting them into high-dimensional dense vector representations. Parent semantic blocks do not participate in vectorization but are directly recalled as semantically complete original text context in subsequent retrieval stages. By vectorizing only child blocks, the vector storage size is reduced, and the retrieval efficiency based on the approximate nearest neighbor index is improved.

[0046] In step 333, a searchable local vector knowledge base is constructed using a separate storage architecture. On one hand, ChromaDB, which includes an HNSW vector index, is used as the vector storage layer to store high-dimensional vectors with fine-grained sub-blocks as vector indexes capable of millimeter-level similarity retrieval. On the other hand, the parent semantic blocks are stored in a key-value store (such as InMemoryStore or RedisStore) as a document storage layer, using the UUID generated by the parent block as the key. During retrieval, the system first performs a vector search on the user query to match the most similar sub-vector blocks; then, it automatically retrieves and deduplicates the corresponding parent text blocks using the UUID in the sub-block metadata, realizing a combined retrieval strategy of "retrieving high-precision sub-blocks and returning the full context parent block," and persistently stores it as a local vector knowledge base. This mechanism effectively balances retrieval accuracy and contextual completeness, significantly improving the effectiveness of semantic relevance retrieval.

[0047] Step 4, generate the report directory structure: The intelligent agent execution framework built in step 1 autonomously plans based on the user's report to generate task descriptions, retrieves the local vector knowledge base built in step 3 based on the report to generate task descriptions to obtain relevant reference materials, calls the report directory generation tool to create a report directory structure containing chapter levels, and saves the report directory structure as a structured intermediate file as a structured persistent intermediate representation throughout the entire generation process. In a preferred embodiment of the present invention, step 4 specifically includes: Step 440, triggering retrieval enhancement and multi-source information fusion: The agent execution framework built in step 1 parses the user's report to generate a task description, triggers a hybrid retrieval and network enhancement mechanism, recalls relevant reference materials from the local vector knowledge base built in step 3, and optionally performs network search, fuses and summarizes the obtained multi-source information, and forms reference materials for catalog generation; Step 441, Construct directory generation prompts and execution planning reasoning: Inject the user's report generation task description, the reference materials obtained in step 440, the list of executable tools, and the forced model with predefined output format constraints into the directory generation prompt template, and send the prompt template to the large language model for reasoning to generate a report directory structure containing chapter levels; Step 442, Persistent storage of structured intermediate files: Write the report directory structure generated in step 411 into a structured intermediate file and save it as a local file as a persistent intermediate representation throughout the entire process.

[0048] In this embodiment of the invention, step 440 triggers retrieval enhancement and multi-source information fusion. To ensure that the catalog planning has accurate factual basis and domain expertise, the agent first initiates the "Retrieval Enhancement (RAG)" strategy, constructing a hybrid retrieval architecture based on LangChain EnsembleRetriever. This aims to combine the advantages of sparse and dense retrieval and introduce online retrieval as a dynamic supplement. Specifically, LangChain's VectorStoreRetriever is instantiated and connected to the Chroma local vector database constructed in the previous step. Vector cosine similarity is used to capture the deep semantic relationship between the user task description and document blocks. At the same time, LangChain's BM25Retriever is instantiated, and the inverted index is constructed and the lexical matching degree is calculated using the pure text corpus extracted in the previous step to compensate for the problem that pure vector retrieval is not sensitive to precise terms or proper nouns (such as specific military models or parameter abbreviations). Furthermore, the agent makes autonomous decisions based on task requirements. When it detects insufficient information in the local vector knowledge base or involves the latest technological developments, it autonomously invokes the TavilySearchResults tool to crawl the latest technical documents or news from the internet in real time, and encapsulates the crawled results into a standard LangChain Document object and merges it with the local results. The retrieval module introduces a custom ternary weighted fusion strategy to score and rank the above multi-source recall results according to a preset weighting formula, and finally extracts the top-N document blocks and formats them as "References". The References not only contain core facts, but also retain source tags, serving as the knowledge foundation for the next step of constructing prompt words.

[0049] In step 441, the table of contents generation prompts and execution planning inference are performed. After obtaining sufficient reference materials, the prompt construction and model inference phase begins. The prompt construction module calls a specially configured table of contents generation template, which contains multiple dynamically injected slots. These slots are used to inject the user's task objectives (e.g., "Generate a software requirements specification for project XX"), the "reference materials" output in step 440, natural language descriptions of callable tools (e.g., report table of contents generation tool, report content generation tool, and format conversion tool), and behavioral constraints (e.g., "Prohibit the generation of more than four levels of hierarchy"). To ensure the table of contents' parsability and automatic processing capabilities, the template forces the model's response to strictly adhere to a preset JSON Schema. The response is defined as an array of JSON objects, where each element represents a chapter and must include title (chapter title), level (integer level), content (an empty placeholder list), image_path and image_caption (image resource placeholders), and optional metadata (e.g., suggested word count, priority labeling, etc.). The agent sends the completed prompts to the large language model. Based on the injected reference data and task objectives, the model performs structured planning and returns a draft directory following the JSON Schema. The template also requires the model to produce a "thoughts" field (thoughtful descriptions) before outputting the final JSON, recording its planning basis and reasoning chain (Chain of Thought) for system recording for end-to-end auditing and subsequent debugging.

[0050] Custom Triad Weighted Fusion Strategy: To address the difficulty of incorporating "source credibility" into the traditional Reciprocal Rank Fusion (RRF) algorithm, this embodiment inserts a custom reranker after the LangChain retrieval pipeline to perform a ternary normalized scoring of "vector similarity + keyword matching + source credibility": Vector dimension ( ): Get the similarity score (SimilarityScore) returned by VectorStoreRetriever. This value directly quantifies the semantic similarity (range 0-1).

[0051] Keyword dimensions ( ): Retrieves the matching score returned by BM25Retriever. Since the original BM25 score has no fixed upper limit, the system performs min-max normalization on the BM25 score of the current batch recall results, mapping it to the interval [0, 1].

[0052] Source credibility dimension ( The system reads the Source field from the Document object's metadata and quantifies it according to a predefined source weight dictionary. For example, official technical standard libraries (such as the GJB standard) are assigned a weight of 1.0, authoritative technical communities are assigned 0.8, and ordinary blogs are assigned 0.3. For local vector knowledge base content, a high-confidence benchmark score (such as 0.9) is assigned by default.

[0053] Weighted sorting and context injection: The system calculates the final total sort score based on a preset hyperparameter formula. ): In this embodiment, it is recommended to set =0.5, =0.2, =0.3. Based on the total score, all Document objects from all sources (local vectors, local keywords, web searches) are sorted in descending order and deduplicated (documents with the same content hash value are removed). Finally, the top-N document blocks are extracted and injected into the Prompt context generated by the large model. This mechanism effectively utilizes the context window and significantly improves the factual consistency and citation accuracy of the generated content.

[0054] In step 442, the generated directory data is serialized into a structured intermediate file, and a persistent write operation is performed. The storage path specified in the configuration file is read, and the JSON data is written to the local file system (e.g., catalogue.json). This file constitutes the core persistent intermediate representation of the entire process of this invention. In subsequent steps, this file will be read repeatedly, chapter nodes will be traversed, and the generated content will be populated back. This design ensures that the report generation process supports breakpoint resumption and process auditing; that is, after the task is interrupted, the context can be restored simply by reading this JSON file, without regenerating the directory.

[0055] Step 5, and generate chapter content: The intelligent agent execution framework built in step 1, based on the report directory structure in the structured intermediate file obtained in step 4, generates specific requirements or retrieves the local vector knowledge base built in step 3 using the chapters input by the user. It can also optionally trigger network search, call the report content generation tool, and drive the generation of chapter content using concurrent flow control and exponential backoff retry mechanism. The generated chapter content is updated to the document structure object in memory, and the complete document structure object is serialized and overwritten and saved to the structured intermediate file to complete the persistent storage of data. In a preferred embodiment of the present invention, step 5 specifically includes: Step 550, Initialize persistent intermediate representation and context retrieval: Load the structured intermediate file obtained in step 4 into memory, build a document object tree, traverse the report directory structure of the content to be generated, execute the intelligent agent framework built in step 1, and trigger the context retrieval of the local vector knowledge base built in step 3 based on the chapter titles of the directory structure. Step 551, concurrent flow control scheduling based on thread pool: Instantiate the thread pool executor, combine the semaphore mechanism to limit the number of concurrent requests, and submit the encapsulated chapter generation task to the scheduling queue; Step 552, Content generation based on exponential backoff retry mechanism: Integrate exponential backoff strategy into model call layer, and perform dynamic delayed retry when generation request fails due to network or service fluctuations to ensure the robustness of task; Step 553, Memory State Update and Atomic Persistent Storage: A mutex-based memory synchronization and full serialization overwrite strategy is adopted. After the generated chapter content is safely updated to the document structure object in memory through the mutex, the complete document structure object is immediately serialized and overwritten to the disk to maintain the persistent intermediate representation of the entire process and complete the persistent storage of data.

[0056] In this embodiment of the invention, for step 550, the report content generation tool first reads the configuration file and locates the paths of the previously generated and verified catalog structure file (catalogue.json) and target report work file (report_work.json). If the target report work file does not exist, the system copies the catalog structure file as the target report work file, which serves as the initial state of the current generation session. Subsequently, the target report work file is deserialized and loaded into a document structure object in memory. This object is a list or tree structure, where each item in the list represents a single chapter node and includes fields such as id, title, level, content (empty placeholder or historical content), and metadata (e.g., priority, recommended word count, retrieval evidence ID). At this stage, for each chapter node to be generated, the agent uses the "hybrid retrieval + network enhancement" strategy described in step 4, with the chapter title and hierarchical relationship as query conditions, to recall relevant technical parameters or background descriptions from the local vector knowledge base as factual basis for constructing the chapter prompt.

[0057] In step 551, to balance generation throughput and the stability of external model services, this embodiment uses a thread pool or asynchronous coroutine pool (asyncio.Semaphore + concurrent tasks) as a flow control at the task execution layer. The number of concurrent large language model requests is limited by the configuration parameter `max_workers` (example value 10). The task distribution logic pops tasks from the queue and submits them to the thread pool. Each worker thread in the pool is responsible for executing the complete lifecycle of the `generate_chapter_content` function: assembling the chapter-level Prompt (including chapter title, completed sibling summaries, global style constraints, retrieved injected reference summaries, etc.), calling the model provider interface, parsing and cleaning the returned results, updating the memory object, and triggering persistence operations. Through this parallel approach, the system can generate multiple chapters in parallel without overloading the external model service, thereby effectively reducing the overall generation latency.

[0058] In step 552, a robust fault-tolerance mechanism is integrated into the model layer (ModelProvider) during the execution of the specific model call (content_generate). The system enters a retry loop (for attempt in range(max_retries)). If a large model request fails, times out, or returns invalid data, the system does not immediately terminate the task. Instead, it catches the exception and executes an exponential backoff strategy: that is, it pauses execution before the next retry, and the pause time increases exponentially with the number of retries (time.sleep(2 ** attempt)). This mechanism effectively avoids the avalanche effect caused by frequent retries when the service is congested. After successfully obtaining the text, the system calls a cleaning function to remove redundant Markdown tags, ensuring the content is clean.

[0059] In step 553, this embodiment employs a strict data synchronization strategy to ensure data security. Once any thread successfully generates chapter content, it first updates the shared `document_structure` object in memory under the protection of a mutex lock, assigning the text to the `content` field of the corresponding node. Immediately afterwards, to prevent progress loss due to program crashes, the `save_json_file` function is called. This function reserializes the currently updated complete document structure object in memory into JSON format and saves it to a structured intermediate file on disk by overwriting the JSON. This mechanism ensures that the intermediate file is always a persistent intermediate representation throughout the entire process, supporting seamless resumption of the process after interruption at any time by reading this file upon restart.

[0060] Step 6: Based on the structured intermediate file updated in Step 5, the intelligent agent execution framework built in Step 1 calls the format conversion tool to convert it into a target format report file according to the preset mapping rules.

[0061] In a preferred embodiment of the present invention, step 6 specifically includes: Step 660, Document object initialization and global layout configuration: The intelligent agent execution framework built in step 1 calls the format conversion tool to deserialize the structured intermediate file, instantiate the target document object, and configure the global font, line spacing and alignment in accordance with Chinese official document standards; Step 661, Dynamic mapping of multi-level heading styles: Traverse the document node tree, dynamically match and apply preset heading styles according to the node's hierarchy attributes, including switching between bold and SimSun fonts, and forcibly applying East Asian font settings. Step 662, Composite Content Parsing and Dual-Channel Table Rendering: Perform DOM parsing and cell merging restoration on HTML format tables, and perform regular matrix parsing on Markdown tables to achieve accurate reconstruction of complex layouts; Step 663, Multimedia resource embedding and target document interaction: Parse image paths and perform embedded insertion and automatic caption formatting. Finally, the format conversion tool serializes the fully constructed in-memory document stream and saves it as a target format report file, completing the delivery.

[0062] In this embodiment of the invention, for step 660, the format conversion calling module first executes initialization logic, reads the structured intermediate file (JSON) throughout the entire process, and deserializes it into a list of document structures in memory. Then, it instantiates an empty Document object using the python-docx library as the rendering canvas. To ensure that the output document conforms to Chinese office standards, the system configures a global default style (Normal): setting the Chinese font to "SimSun", font size to 4 (14 points), font color to black, and paragraph alignment to justified. Simultaneously, the default line spacing is locked at a fixed value of 24 points, and the spacing before and after paragraphs is cleared, thus establishing a unified visual tone for subsequent content.

[0063] In step 661, this embodiment employs a tree-based traversal strategy to process the document structure, sequentially scanning each chapter node in the document data list to extract its title (heading text) and level (level depth). A built-in style rule engine dynamically maps heading styles based on the level value: Level 1 and 2 headings automatically apply the "SimHei" font, dynamically adjusting the font size to size 3 (16pt) or 4 (14pt), and removing bolding to conform to specific official document standards. Level 3 and lower headings apply the "SimSun" font to maintain hierarchical distinction. When inserting a heading, the underlying XML interface (qn('w:eastAsia')) is called to force the setting of East Asian font attributes, effectively solving the problem of Chinese fonts reverting to Western fonts in cross-platform environments.

[0064] In step 662, for the mixed-format content (plain text, Markdown, HTML) generated by the large language model, this embodiment implements a dual-channel composite parsing engine: Channel 1 (deep HTML table parsing) uses regular expressions to identify the content...

[0065]

[0066] Figure 2

[0067]

[0068]

[0069]

[0070] Figure 3 Figure 4 Figure 3

[0071] Figure 3

[0072]

[0073] Figure 3

[0074] Figure 4 Figure 3

[0075] Figure 3 Figure 4 Figure 3 Figure 4 Figure 3 Figure 4

[0076] Figure 4

[0077] Figure 4

[0078] Figure 5 Figure 6 Figure 5

[0079] Figure 5

[0080] Figure 3 Figure 5

[0081] Figure 5

[0082] Figure 6 Figure 5

[0083] Figure 6 Figure 5

[0084] Figure 6 Figure 5

[0085] Figure 5 Figure 3

[0086] Figure 5 Figure 6 Figure 5 Figure 6 Figure 5

[0087] Figure 7 Figure 8 Figure 7

[0088] Figure 7

[0089] Tag blocks. For captured HTML tables, the system calls the BeautifulSoup library to parse their DOM structure, extracting row (tr) and cell (td / th) data. The core is to accurately restore the merging relationship: the system recognizes the colspan (spanning columns) and rowspan (spanning rows) attributes of cells, dynamically creates table objects of the corresponding dimensions in the Word document, and performs physical cell merging operations, thus perfectly restoring complex nested or cross-row table layouts. Channel Two (Markdown Table Regular Expression Parsing) For Markdown syntax tables (text lines separated by |), regular expressions are also used to extract table content. The parser divides it into data matrices and creates a standard grid table in Word. For non-table plain text, it is cleaned and divided into independent paragraphs, with first-line indentation (28 points, i.e., the width of two Chinese characters) and fixed line spacing applied to ensure a good reading experience. In step 663, after the text and tables are processed, the embedding logic of multimedia resources is executed, and the image_path field in the chapter node is checked. If the path points to a valid local image file, a centered paragraph will be created at the end of the current chapter. The `add_picture` method will be called to insert the image in an "embedded" manner, and its width will be uniformly adjusted to fit the page size (e.g., 300 points). Immediately following the image, a caption paragraph containing `image_caption` will be automatically generated, applying a font style different from the body text (e.g., KaiTi or grayscale). Finally, the `save` method of the document object will be called to serialize the complete document stream built in memory and write it to disk, generating the final .docx format report file, completing the fully automated delivery process.As shown, this embodiment of the invention also provides a large language model-driven report generation intelligent agent system, including: an intelligent agent engine module, used to implement the intelligent agent execution framework construction in step 1, design prompt word templates containing thought chain reasoning content and action instructions, format constraints on the output of the large language model, and obtain preset JSON. The system generates decision information and, after parsing, schedules local tool functions, enabling the large language model to autonomously plan and execute tasks in a "perception-reasoning-execution-feedback" loop, forming an independently running report generation agent. The data processing module parses the user-provided reference files in step 2, extracts text content and document structure information, preprocesses the extracted results, and saves the processed data as a structured reference file. The knowledge base construction module performs semantic segmentation and vectorization on the structured reference files obtained in step 2, generating a searchable document vector index and persistently storing it. The report catalog generation module implements the agent execution framework built in step 1 in step 4, autonomously planning based on the user's report generation task description, retrieving relevant reference materials from the local vector knowledge base built in step 3, and calling the report catalog generation function. The tool creates a report directory structure with chapter levels and saves the report directory structure as a structured intermediate file. The report content generation module implements the agent execution framework built in step 1 (step 5). Based on the report directory structure in the structured intermediate file obtained in step 4, it generates specific requirements or retrieves chapter titles from the local vector knowledge base built in step 3 using user-inputted chapters. Optionally, it triggers a network search, calls the report content generation tool, and uses concurrent flow control and exponential backoff retry mechanisms to drive the generation of chapter content. The generated chapter content updates the document structure object in memory, and after serializing the complete document structure object, it overwrites and saves it to the structured intermediate file, completing the persistent storage of data. The format conversion module implements the format conversion tool called by the agent execution framework built in step 1 based on the structured intermediate file updated in step 5 (step 6), converting it into a target format report file according to preset mapping rules. This invention also provides a large language model-driven report generation agent device, including: a memory: storing a computer program for the above-mentioned large language model-driven report generation agent method, which is a computer-readable device; and a processor: used to execute the computer program to implement the above-mentioned large language model-driven report generation agent method. This invention also provides a computer-readable storage medium storing a computer program that, when executed by a processor, can implement the aforementioned large language model-driven report generation agent method. It should be noted that this system corresponds to the method described above, and all implementations in the above method embodiments are applicable to this embodiment and can achieve the same technical effects.The experimental analysis is shown in the following diagram: A fragment of a structured intermediate file (JSON format) showing the report directory structure autonomously planned and generated by the intelligent agent in this embodiment of the invention, illustrating the definitions of chapter titles, hierarchical depth, and content slots. Another diagram shows the layout effect of the table of contents of a Word target format report file automatically rendered by a format conversion tool based on the structured intermediate file shown in this embodiment of the invention. The specific data form of the persistently stored structured intermediate file (JSON) in step 442 is shown. This file is a standard list of objects, each representing a chapter node in the report. The explicitness of field definitions: Each node contains title (title text, such as "3.2.1 Domestic Hardware Adaptation Function"), level (hierarchical depth, such as an integer 3), and content (content slot, initialized as an empty list []). Decoupling of planning and execution: It clearly shows that this invention prioritizes the precise definition of the document skeleton before generating specific text content. For example, the node {"title": "3.2 CSCI Capability Requirements", "level": 2} explicitly specifies that this part is a second-level heading. This structured intermediate representation serves as the core carrier for maintaining data consistency, ensuring that subsequent content generation (step 5) and format conversion (step 6) strictly adhere to this pre-defined logical framework, avoiding logical confusion or hierarchical loss issues common in traditional end-to-end generation. The final deliverable—the table of contents of a Word document—rendered by the format conversion tool in step 6 based on the shown JSON data is shown. Precise mapping: A comparison reveals that the JSON data is mapped flawlessly to the table of contents fields in Word. The level 2 node "3.2 CSCI Capability Requirements" in the example is automatically recognized as a second-level directory style and indented accordingly; the level 3 node "3.2.1 Domestic Hardware Adaptation Function" in the example is accurately rendered as a third-level directory. Formatting conforming to official document standards: As shown, the generated table of contents automatically applies a format conforming to Chinese official document standards. The table of contents titles use a reasonable combination of "SimSun" or "HeiTi," page numbers are right-aligned, and filled with standard dotted guide characters. Verification of automated delivery capabilities: The generated page numbers (such as "16", "31", etc.) prove that the system not only restored the text but also successfully handled the pagination flow. This verifies the technical effect described in steps 660 to 663: that is, the system can read the structured intermediate file, instantiate the document object, and complete complex typesetting calculations in memory, ultimately outputting a standard Word document with a complete page number index that requires no manual adjustment.As shown, this is a schematic diagram of a structured intermediate file (JSON format) fragment containing complete text content and multimedia resource metadata after step 5 and generation of chapter content in an embodiment of the present invention; as shown, this is a schematic diagram of the text layout effect of the final target format report file (Word) after being parsed, rendered, and embedding image resources based on the structured intermediate file shown in the embodiment of the present invention. It demonstrates the state after step 5 is completed, when the document structure object in memory is serialized and overwritten to disk, i.e., the final form of the "full-process structured persistent intermediate representation". Atomic persistent storage verification of content generation: Compared with the previous directory structure, the content field is no longer empty, but filled with detailed text generated by the large language model (such as "This section describes the scope of requirements for auxiliary security operation and maintenance tool software based on the large model..."). This directly verifies the "memory state update and atomic persistent storage" strategy described in step 553, that is, the text generated for each chapter has been securely fixed in the JSON structure. Metadata Definition of Multimedia Resources: Of particular note is the addition of an `images` array field under node 1.2, which records detailed information such as `image_path` (absolute local path of the image), `image_caption`, and layout parameters like `width` and `position`. This indicates that during the intermediate file generation stage, the system has completed the planning and path parsing of illustration resources, providing accurate index credentials for image embedding in subsequent step 663, reflecting the decoupling design between the data layer and the presentation layer. The final Word document body page rendered from the JSON data based on step 6 is shown. Accurate Reproduction of Text and Style: The body content in the document (e.g., "This software is a 'large-model-based auxiliary security operation and maintenance tool'...") is completely consistent with the text in the `content` field, and the paragraphs apply the global layout of "SimSun, size 4, justified" configured in step 660. Automated Embedding of Multimedia Resources: As shown in the second half, the system reads the `image_path` recorded in the document and successfully inserts the local image (flowchart) into the specified position in the document in an "embedded" manner. Automatic caption formatting: Immediately below the image, the system automatically generates the caption "System Framework Diagram" based on the image_caption, and applies center alignment and a font style different from the body text. This result strongly demonstrates the effectiveness of the "multimedia resource embedding and target document interaction" function in step 663, realizing automated mapping from "JSON metadata" to "visualized text and image layout," without the need for manual image insertion or position adjustment. Combined, it can be seen that this invention achieves unified management of "text content" and "multimedia resources" by maintaining a structured intermediate file throughout the entire process.As the core carrier for maintaining data consistency, it stores all information to be rendered; as the delivery terminal, it is only responsible for "projecting" the data into a visual document format according to preset rules. This mechanism ensures that even when processing complex reports containing a large number of images and long texts, the system still maintains clear logic and will not experience image misalignment or content loss. As shown, this is a schematic diagram of the original table data fragment containing HTML tags output by the large language model stored in the structured intermediate file (JSON) after generating the chapter content in step 5 in this embodiment of the invention; as shown, this is a schematic diagram of the complex table restoration effect achieved in the final target format report file (Word) after the HTML original data shown is parsed and processed by the format conversion tool based on the HTML original data in this embodiment of the invention. It shows the underlying storage form of the chapter content generated in step 5 in the structured intermediate file. Persistence of mixed format content: As shown in Figure 7, the content field of the chapter node (such as "3.2.1 Domestic Hardware Adaptation Function") contains not only ordinary text, but also standard HTML markup language (e.g., generated by the large language model). 、 、 、 (e.g., tags).

[0090] Complete preservation of semantic structure: Figure 7 It is clearly shown that although the data currently exists as a string in JSON, the logical structure of the table (header, rows, columns, and border attribute border="1") has been fully preserved. This verifies that in step 5, the present invention can guide the model to output structured HTML code to express complex data, rather than just outputting plain text tabs that are difficult to parse. This intermediate representation provides a detailed basis for subsequent accurate rendering.

[0091] Figure 8 Step 6 (especially step 662) is shown to be based on Figure 7 The HTML data is ultimately rendered into a Word document page.

[0092] contrast Figure 7 and Figure 8 The "HTML Table Deep Parsing Channel" in the format conversion tool successfully identified the JSON string. The `<html>` tag block. Instead of printing the HTML code directly as text, it performs DOM parsing and extracts the table headers. ) and cell ( The data was processed, and the corresponding table object was reconstructed in the Word document object.

[0093] Precise reconstruction of complex layouts: such as Figure 8 As shown in "Table 15 Functional Requirements" and "Table 16 CSCI External Interface List", the system not only reproduces the content of the tables, but also accurately applies the layout details: Style mapping: The header text is automatically bolded and centered, conforming to the official document form specifications; Borders and width: The table uses a full grid border, and the column widths are adaptively adjusted according to the content; Cell logic: Figure 7 The row and column relationships defined in HTML are in Figure 8 The data is physically instantiated, ensuring that the data is not misplaced.

[0094] This result strongly demonstrates that the "composite content parsing and dual-channel table rendering" technology described in step 662 of this invention can effectively solve the pain point of chaotic table format in the generated content of large models, which cannot be directly delivered, and realizes lossless conversion from "code-level structure" to "document-level view".

Claims

1. A report generation agent method driven by a large language model, characterized in that, Includes the following steps: Step 1, Construct the agent execution framework: The design incorporates prompt word templates that include thought chain reasoning content and action instructions. The output of the large language model is formatted and constrained to obtain a preset JSON structure to generate decision information. After parsing, the local utility function is scheduled, enabling the large language model to complete autonomous planning and task execution in the "perception-reasoning-execution-feedback" loop, forming an independently running report generation agent. Step 2, Preprocessing Reference Materials: The system parses the reference files provided by the user, extracts the text content and document structure information, preprocesses the extraction results, and saves the processed data as a structured file of the references. Step 3, Build a local vector knowledge base: The structured reference files obtained in step 2 are semantically segmented and vectorized to generate a searchable document vector index, which is then persistently stored. Step 4, generate the report directory structure: The intelligent agent execution framework built in step 1 autonomously plans based on the task description generated by the user's report, retrieves the local vector knowledge base built in step 3 based on the task description generated by the report to obtain relevant reference materials, calls the report directory generation tool to create a report directory structure containing chapter levels, and saves the report directory structure as a structured intermediate file. Step 5, and generate chapter content: The intelligent agent execution framework built in step 1, based on the report directory structure in the structured intermediate file obtained in step 4, generates specific requirements or retrieves the local vector knowledge base built in step 3 using the chapters input by the user. It can also optionally trigger network search, call the report content generation tool, and drive the generation of chapter content using concurrent flow control and exponential backoff retry mechanism. The generated chapter content is updated to the document structure object in memory, and the complete document structure object is serialized and overwritten and saved to the structured intermediate file to complete the persistent storage of data. Step 6: Based on the structured intermediate file updated in Step 5, the intelligent agent execution framework built in Step 1 calls the format conversion tool to convert it into a target format report file according to the preset mapping rules.

2. The method for a report generation agent driven by a large language model according to claim 1, characterized in that, The specific method of step 1 includes: Step 110: Based on the reasoning and action collaboration paradigm, design a structured prompt word template that includes thought chain reasoning content and action instructions, set dynamic slots for describing task objectives, behavioral constraints, executable actions and resource information, and configure unified response format rules to format and constrain the reasoning content and action instructions of the large language model to obtain a preset JSON structure to generate decision information. Step 111: Build a custom tool library, establish a mapping relationship between action identifiers and tool functions, and generate natural language text of tool names, function descriptions, and parameter definitions; Step 112: Construct a task state management and context compression mechanism to record the inference content and execution feedback of the model in each round, and perform summary compression on the historical records when the context length exceeds a preset threshold to ensure the continuity of long-term task execution and inference stability, forming an independently run report generation agent; Step 113: Establish a collaborative closed-loop control process for inference and execution, assemble the context, trigger model inference, parse action instructions, schedule local utility functions, and return execution observations to perform continuous iteration between model inference and utility function execution results.

3. The method for a report generation agent driven by a large language model according to claim 1, characterized in that, The specific method for step 2 includes: Step 220, File Format Recognition and Verification: Receive the file stream uploaded by the user, parse the file extension, and identify the document type, including DOCX or PDF file format documents; Step 221, DOM traversal and structure restoration of DOCX documents: For DOCX documents, the document object model traversal technique is used to extract text while simultaneously parsing style attributes to preserve chapter hierarchy and reconstructing the two-dimensional structure of tables. Step 222, Adaptive dual-channel extraction of PDF documents: The underlying native text stream is directly extracted using the PyMuPDF library, and text density detection is performed to evaluate the effective character ratio. When the page is determined to be a scanned document or low-density text, a degradation mechanism is automatically triggered, and the PaddleOCR library is called to perform deep recognition on the high-resolution rendered image to achieve full coverage analysis of both native and scanned PDFs. Step 223, Standardization and serialization of multi-source heterogeneous data: The content parsed from the corresponding documents is uniformly converted into a structured key-value pair sequence containing metadata and saved as a structured file of reference materials.

4. The method for a report generation agent driven by a large language model according to claim 1, characterized in that, The specific method for step 3 includes: Step 330, Structured text objectification processing: Convert the key-value pair data of the reference material structured file obtained in Step 2 into a standardized document object containing content fields and metadata fields; Step 331, Dual-granularity semantic segmentation and parent-child association construction: A dual-layer segmentation strategy is performed on the standardized document object obtained in step 330. First, the standardized document object is segmented into parent semantic blocks with complete semantic logic, and a globally unique identifier is generated for each parent semantic block. Then, the parent semantic blocks are recursively refined into child fine-grained blocks, and the parent unique identifier is injected into the metadata of all corresponding child fine-grained blocks to establish a traceable parent-child mapping relationship. Step 332, High-dimensional vectorized embedding generation: The local embedding model is called to generate dense vector representations only for fine-grained sub-blocks, and vector normalization and feature dimension configuration are handled uniformly; Step 333, Hierarchical Vector Retrieval Structure Construction: Construct a separate storage architecture consisting of a vector storage layer and a document storage layer. After associating the dense vectors of the child-level fine-grained blocks generated in Step 332 with their corresponding metadata containing the parent's unique identifier, store them in the vector storage layer configured with an approximate nearest neighbor index. At the same time, using the parent's unique identifier generated in Step 331 as the key, store the complete text of the parent semantic block in the key-value document storage layer. Based on this, configure a retrieval-recall logic based on the association of the parent's unique identifier. That is, first perform similarity retrieval on the dense vectors of the child-level fine-grained blocks to obtain the dense vectors of the child-level fine-grained blocks with their corresponding metadata containing the parent's unique identifier. Then, based on the parent's unique identifier in the metadata of the hit child-level fine-grained blocks, recall the corresponding parent text blocks from the document storage layer and remove duplicates. This realizes a combined retrieval strategy of "retrieving high-precision child blocks and returning the full context parent block" and persists it as a local vector knowledge base.

5. The method for a report generation agent driven by a large language model according to claim 1, characterized in that, The specific method for step 4 includes: Step 440, triggering retrieval enhancement and multi-source information fusion: The agent execution framework built in step 1 parses the user's report to generate a task description, triggers a hybrid retrieval and network enhancement mechanism, recalls relevant reference materials from the local vector knowledge base built in step 3, and optionally performs network search, fuses and summarizes the obtained multi-source information, and forms reference materials for catalog generation; Step 441, Construct directory generation prompts and execution planning reasoning: Inject the user's report generation task description, the reference materials obtained in step 440, the list of executable tools, and the forced model with predefined output format constraints into the directory generation prompt template, and send the prompt template to the large language model for reasoning to generate a report directory structure containing chapter levels; Step 442, Persistent storage of structured intermediate files: Write the report directory structure generated in step 411 into a structured intermediate file and save it as a local file as a persistent intermediate representation throughout the entire process.

6. The method for a report generation agent driven by a large language model according to claim 1, characterized in that, The specific method for step 5 includes: Step 550, Initialize persistent intermediate representation and context retrieval: Load the structured intermediate file obtained in step 4 into memory, build a document object tree, traverse the report directory structure of the content to be generated, execute the intelligent agent framework built in step 1, and trigger the context retrieval of the local vector knowledge base built in step 3 based on the chapter titles of the directory structure. Step 551, concurrent flow control scheduling based on thread pool: Instantiate the thread pool executor, combine the semaphore mechanism to limit the number of concurrent requests, and submit the encapsulated chapter generation task to the scheduling queue; Step 552, Content generation based on exponential backoff retry mechanism: Integrate exponential backoff strategy into model call layer, and perform dynamic delayed retry when generation request fails due to network or service fluctuations to ensure the robustness of task; Step 553, Memory State Update and Atomic Persistent Storage: A mutex-based memory synchronization and full serialization overwrite strategy is adopted. After the generated chapter content is safely updated to the document structure object in memory through the mutex, the complete document structure object is serialized and overwritten to the disk, maintaining the persistent intermediate representation of the entire process and completing the persistent storage of data.

7. The method for a report generation agent driven by a large language model according to claim 1, characterized in that, The specific method for step 6 includes: Step 660, Document object initialization and global layout configuration: The intelligent agent execution framework built in step 1 calls the format conversion tool to deserialize the structured intermediate file, instantiate the target document object, and configure the global font, line spacing and alignment in accordance with Chinese official document standards; Step 661, Dynamic mapping of multi-level heading styles: Traverse the document node tree, dynamically match and apply preset heading styles according to the node's hierarchy attributes, including switching between bold and SimSun fonts, and forcibly applying East Asian font settings. Step 662, Composite Content Parsing and Dual-Channel Table Rendering: Perform DOM parsing and cell merging restoration on HTML format tables, and perform regular matrix parsing on Markdown tables to achieve accurate reconstruction of complex layouts; Step 663, Multimedia resource embedding and target document interaction: Parse image paths and perform embedded insertion and automatic caption formatting. Finally, the format conversion tool serializes the fully constructed in-memory document stream and saves it as a target format report file, completing the delivery.

8. A large language model-driven report generation intelligent agent system based on the method of claim 1, characterized in that, include: The intelligent agent engine module is used to build the intelligent agent execution framework. It designs prompt word templates that include thought chain reasoning content and action instructions, formats and constrains the output of the large language model, obtains the preset JSON structure to generate decision information, and then parses and schedules local utility functions. This enables the large language model to complete autonomous planning and task execution in the "perception-reasoning-execution-feedback" loop, forming an independently run report generation intelligent agent. The data processing module is used to parse the reference files provided by the user, extract the text content and document structure information, preprocess the extraction results, and save the processed data as a structured file of the references. The knowledge base construction module is used to perform semantic segmentation and vectorization processing on the structured files of reference materials, generate a searchable document vector index, and persist it for storage. The report catalog generation module is used to enable the intelligent agent to execute the framework, autonomously plan according to the user's report generation task description, retrieve the local vector knowledge base based on the report generation task description to obtain relevant reference materials, call the report catalog generation tool to create a report catalog structure containing chapter levels, and save the report catalog structure as a structured intermediate file; The report content generation module is used to enable the intelligent agent to execute the framework, generate specific requirements or chapter titles based on the report directory structure in the structured intermediate file, retrieve local vector knowledge base, and optionally trigger network search, call the report content generation tool, drive the generation of chapter content using concurrent flow control and exponential backoff retry mechanism, update the generated chapter content to the document structure object in memory, and serialize the complete document structure object and overwrite and save it to the structured intermediate file to complete the persistent storage of data; The format conversion module is used to convert the updated structured intermediate file into a target format report file by having the intelligent agent execute the framework to call the format conversion tool and convert it according to preset mapping rules.

9. A report generation intelligent agent device driven by a large language model, characterized in that, include: Memory: A computer program for a large language model-driven report generation agent method as described in any one of claims 1-7, which is a computer-readable device; Processor: Used to implement the large language model-driven report generation agent method according to any one of claims 1-7 when executing the computer program.

10. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores a computer program that, when executed by a processor, enables the implementation of a large language model-driven report generation agent method as described in any one of claims 1-7.

Citation Information

Patent Citations

  • Software requirement specification document automatic generation method based on large language model

    CN120524932A

  • Large model-based standard document automatic generation and multi-dimensional auditing method and system

    CN120597846A

  • Method and system for automatic generation and multi-dimensional review of standard documents based on large models

    CN120597846B

Cited By

  • Disease-related content automatic typesetting and background manuscript storage system and method

    CN122047165A