A judgment document assisted writing method and system based on retrieval enhancement generation

By constructing reasoning-oriented judicial summaries and hierarchical legal provision matching retrieval strategies, and coordinating with a large language model to generate reasoning texts for judgments, the problems of inconsistent generated content and inaccurate legal provision citations in existing technologies have been solved. This has improved the accuracy and logic of reasoning in judgments, enhanced the consistency between generated content and case facts, and improved the accuracy of legal provision recall, thereby alleviating the writing pressure on judges.

CN122364448APending Publication Date: 2026-07-10SHANDONG UNIV
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
SHANDONG UNIV
Filing Date
2026-03-17
Publication Date
2026-07-10

AI Technical Summary

Technical Problem

Existing systems for assisting in drafting judicial documents have issues when generating the reasoning section of judgments, such as inconsistencies between the generated content and the facts of the case, inaccurate citations of legal provisions, and illogical reasoning. These issues make it difficult to meet the stringent requirements of accuracy and standardization in judicial settings.

Method used

By constructing reasoning-oriented judicial summaries, designing hierarchical legal provision matching and retrieval strategies, and using summaries and legal provisions to collaboratively guide the generation of reasoning texts by a large language model, including structured segmentation of case facts, sparse attention mechanism, multi-granularity feature fusion, hierarchical query rewriting, and vectorized legal provision retrieval, a structured generation input is formed, and finally, segmented and controlled generation of judgment reasoning texts is achieved.

Benefits of technology

It significantly improves the accuracy, compliance, and logic of reasoning in judgment documents, reduces redundant narrative interference, enhances the consistency between generated content and case facts and the accuracy of legal provision recall, alleviates the writing pressure on judges, and improves judicial credibility.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122364448A_ABST
    Figure CN122364448A_ABST
Patent Text Reader

Abstract

The application relates to a judgment document auxiliary writing method and system based on retrieval enhancement generation, which comprises the following steps: step 1, case fact structured block and law article library construction; step 2, generation of a judgment-oriented judicial abstract; step 3, hierarchical query rewriting to generate a retrieval expression; formation of a multi-granularity query expression from coarse to fine; step 4, vectorization law article retrieval and reordering; multi-layer query parallel retrieval is carried out in a pre-constructed law article vector retrieval library, and a relevant law article set is output by weighting and reordering according to semantic similarity and law article effectiveness level; step 5, construction of a structured generation input; step 6, segmented controlled generation of a judgment reasoning text; a staged generation strategy is adopted to sequentially complete case nature identification, dispute focus analysis, legal application demonstration and judgment conclusion expression, and finally splice to form a complete reasoning text. The application improves the consistency and integrity of the reasoning text and the case facts.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to a method and system for assisting in the drafting of judicial documents based on retrieval enhancement, belonging to the field of judicial document assisting drafting technology. Background Technology

[0002] Currently, courts and technology companies across China are exploring the application of artificial intelligence (AI) technology to assist in the drafting of court judgments. The Shenzhen Intermediate People's Court pioneered the construction of the nation's first large-scale judicial model, covering multiple core trial stages, including judgment generation. The LegalAID legal model developed by the Tsinghua University Internet Justice Research Institute has launched a one-click document generation function, which has been implemented in courts nationwide. Furthermore, commercial platforms such as Alpha and Zhilvyun, catering to legal professionals, have also launched judgment drafting assistance functions. These explorations demonstrate that AI-assisted judgment drafting has broad application prospects and an urgent practical need.

[0003] However, existing solutions for assisting in drafting judgments still have significant shortcomings in the quality of the reasoning section. Existing systems generally suffer from inconsistencies between the generated content and the facts of the case, inaccurate or even fabricated legal citations, and sloppy argumentation logic. Existing research and practice have pointed out that "the generated factual findings and the court's opinion sections are not ideal" and are unable to meet the strict requirements of accuracy and standardization in judicial settings.

[0004] Currently, the most widely used solution for assisting in the generation of court judgments is a structured filling method centered on fixed document templates. The basic approach is as follows: standardized judgment templates are pre-established for different case types (such as loan disputes, divorce disputes, and labor disputes). These templates include fields for party information, factual descriptions, legal basis, and judgment conclusions. When the system is used, it extracts the basic elements of the case and automatically fills the information into the corresponding template fields according to preset rules, generating a formatted draft document. Some systems also include a built-in list of recommended legal provisions for common causes of action, allowing judges to directly select them when filling in the legal basis field. Currently, many intelligent auxiliary systems used by domestic courts, as well as commercial platforms such as Alpha and FaGouGou, adopt this technical approach, primarily covering the generation of simple case types such as element-based and tabular formats.

[0005] The limitations of template-based solutions stem directly from their reliance on fixed templates. Firstly, fixed templates cannot adapt to the personalized argumentation needs of the reasoning section, resulting in generic and unspecific texts. The reasoning section of court documents requires personalized argumentation based on the specific facts of the case, the points of contention between the parties, and the logic of legal application. Fixed templates only provide a general textual framework and cannot flexibly adjust the content and logical structure of the argumentation according to the actual circumstances of each case. In practice, the reasoning section generated by this solution often uses the same set of general expressions, with low relevance to the facts of the case. Judicial personnel still need to make extensive manual modifications, resulting in very limited auxiliary effect. Secondly, the system relies on manually preset case-legal provision correspondence rules, which cannot handle the complex situation of semantic differences between case facts and legal provisions, leading to insufficient accuracy in legal provision recommendations. In real cases, the same legal facts may involve multiple competing legal provisions, and judges need to choose the most appropriate applicable basis based on the specific circumstances of the case. Furthermore, with legislative revisions, the content of legal provisions continuously changes, and preset rules are difficult to keep up with, posing a risk of recommending repealed or inapplicable provisions. This problem is particularly prominent in civil cases with complex legal relationships.

[0006] Another common approach is a legal knowledge assistance system centered on keyword retrieval. This approach involves the system having a built-in database of laws and regulations and a historical judgment document database. When handling cases, judges or the system extract several keywords (such as cause of action, party relationships, dispute type, etc.) from the case description or points of contention. Using these keywords as search criteria, the system retrieves matching legal provisions and similar cases from the database and presents the search results to the judge as a reference for drafting their case. Currently, mainstream domestic legal database platforms (such as Peking University Law Database, Wolverhampton Law, Wusong Cases, and Faxin) all provide this function. Some smart court systems also integrate similar case recommendations and legal provision association search functions. The Supreme People's Court's "Guiding Opinions on Unifying the Application of Law and Strengthening Similar Case Retrieval" also explicitly lists keyword retrieval as a standard search method.

[0007] While keyword-based legal provision recommendations and case-based drafting methods have performed well in some cases, they also have limitations. First, there is a natural "expression gap" between the facts of a case and the legal provisions, leading to insufficient recall precision from direct keyword matching. The factual portion of court documents uses natural language, such as "the defendant has long been in arrears on payments and refuses to pay," while the corresponding legal provisions use highly standardized legal terminology, such as "If one party fails to perform its contractual obligations or performs them in a manner that does not conform to the agreement, it shall bear the liability for breach of contract, including continuing performance, taking remedial measures, or compensating for losses." The significant differences in word choice and expression between the two mean that directly using terms from the case facts as keywords for legal provisions can easily result in the failure to recall the relevant provisions or the recall of irrelevant provisions, making it difficult to guarantee search accuracy. Second, this solution only provides reference materials and lacks the ability to integrate search results with the case facts to generate persuasive text; judges still need to complete the creative process from materials to written text themselves. The current search assistance system's ultimate goal is to present judges with relevant legal provisions and lists of similar cases. However, transforming these materials into logically consistent arguments still relies entirely on judges' manual drafting. This means that the solution offers limited help in alleviating judges' workload in drafting reasoned arguments.

[0008] With the rise of large language models such as GPT, LLaMA, and ChatGLM, directly using these models to generate reasoning text for judicial documents has become a research hotspot and engineering practice direction in recent years. This approach involves using the factual description of the case as input prompts, directly calling a general or legally-adjusted large language model (such as ChatLaw or DISC-LawLLM) to generate complete reasoning text end-to-end. Some solutions add simple prompt engineering, such as adding case information to the input or requiring the model to output in a specific format; others involve supervised fine-tuning of the model on large-scale judicial document data, enabling the model to learn the writing style and expression norms of judicial documents. Currently, the Suzhou Intermediate People's Court and the Shenzhen Intermediate People's Court, among others, have launched pilot projects for generative AI-assisted document drafting.

[0009] While methods using large language models to generate persuasive texts can yield impressive results, these approaches fail to fundamentally address the limitations of model knowledge, revealing serious flaws in the highly specialized context of judicial reasoning. First, large language models suffer from the "illusion" problem, easily leading to fabricated or incorrectly cited legal provisions during persuasive text generation. Since their knowledge comes from pre-trained corpora, the models don't truly "know" whether a particular law exists. When generating persuasive texts, they are highly likely to fabricate seemingly plausible but actually nonexistent legal provisions based on statistical patterns, or misattribute irrelevant provisions. This problem has been documented and confirmed by researchers in the legal field and is known as "legal illusion." In judicial settings, false legal citations directly undermine the legitimacy of judicial documents and judicial authority. Second, existing solutions directly feed raw factual text into the model without targeted structured compression, causing the model to "miss the key points," resulting in persuasive content that deviates from the crucial facts of the case. The factual section of civil judgments typically exceeds a thousand words, containing extensive background descriptions, with only a portion of the facts truly influencing the application of law and the judgment's conclusion. Because existing solutions lack a factual summary preprocessing step for reasoning, the model is easily distracted by extremely long, low-information-density inputs, resulting in the generation of reasoning texts that either omit key factual elements or deviate substantially from the facts of the case, thus failing to effectively guarantee the factual accuracy of the reasoning content. Summary of the Invention

[0010] To address the shortcomings of existing technologies, this invention proposes a method for assisting in the drafting of judicial documents based on retrieval enhancement. This method constructs a reasoning-oriented summary of judicial facts, designs a hierarchical legal provision matching retrieval strategy, and uses the summary and legal provisions to collaboratively guide a large language model to generate reasoning text. This solves the core problems existing in the reasoning generation of judicial documents in current solutions and improves the accuracy and practicality of the assisted drafting.

[0011] This invention also proposes a system for assisting in the drafting of judicial documents based on retrieval enhancement.

[0012] This invention improves the factual consistency and logical integrity of reasoning texts by constructing structured judicial summaries, a hierarchical legal provision matching and retrieval mechanism, and a summary-driven controlled generation process, while ensuring the accuracy of legal basis. This method significantly enhances the accuracy, compliance, and logic of reasoning in judicial documents, effectively alleviating the writing burden on judges and representing a key technical solution for improving judicial credibility.

[0013] Terminology Explanation: 1. Legal-BERT-base model: Legal-BERT-base is a language model based on the BERT architecture and pre-trained on a large-scale legal corpus. It can encode legal text into dense vector representations of fixed dimensions, thereby capturing the deep semantic features of legal terms and provisions, and is suitable for downstream tasks such as legal provision retrieval and legal text classification.

[0014] 2. FAISS Framework: FAISS (Facebook AI Similarity Search) is a high-efficiency vector similarity search framework developed by Meta, specifically designed for quickly retrieving and querying the most similar vectors in large-scale, high-dimensional vector sets. It supports various index structures (such as IVF clustering), significantly reducing retrieval complexity, and is widely used in semantic retrieval, recommender systems, and other scenarios.

[0015] 3. IVF Clustering Method: IVF (Inverted File) clustering is a vector indexing technique. Its core idea is to pre-divide a large set of vectors into multiple clusters, each represented by a cluster center. During retrieval, the distance between the query vector and each cluster center is first calculated to locate the few most relevant clusters. Then, a precise search is performed only within these clusters, thereby significantly reducing the number of comparisons and greatly improving retrieval efficiency.

[0016] The technical solution of this invention is as follows: A method for assisting in drafting judicial documents based on retrieval enhancement includes: Step 1: Structural segmentation of case facts and construction of legal provisions database; Receive the basic factual description, party information and dispute focus of the case to be processed, perform semantic analysis and rule recognition, divide the content into three sub-modules: dispute type, litigation claims and case facts, and at the same time, construct a vectorized legal provisions retrieval database; Step 2: Generate reasoning-oriented judicial summaries; model the three types of sub-modules separately, and introduce a sparse attention mechanism to suppress redundant narration for the case facts with low information density and a lot of redundancy. Then, generate a unified judicial summary through multi-granularity feature fusion to form a concise and information-dense factual representation. Step 3: Layered query rewriting to generate search expressions; based on the judicial abstract, the case cause layer is rewritten, the legal element layer is rewritten, and the standardized expression is rewritten in sequence to form a multi-granularity query expression from coarse to fine; Step 4: Vectorized legal provision retrieval and reordering; Perform multi-level parallel retrieval in a pre-built legal provision vector retrieval library, and sort the relevant legal provisions by weight based on semantic similarity and legal provision validity level, and output the relevant legal provision set; Step 5: Construct a structured input for generation; organize the judicial abstract, retrieved legal provisions, and necessary original text fragments into a structured Prompt according to a preset template, and clarify the generation task and argumentation structure requirements; Step 6: Segmented controlled generation of the judgment reasoning text; adopting a phased generation strategy, the determination of the nature of the case, analysis of the points of contention, argumentation of the application of law, and expression of the judgment conclusion are completed in sequence, and finally spliced ​​together to form a complete reasoning text.

[0017] According to a preferred embodiment of the present invention, a vectorized legal provision retrieval library is constructed, comprising: The vectorized legal provision retrieval library includes a legal provision text library, a vector index library, and a metadata database; The legal text database stores the original legal texts, including complete information such as the law name, article number, article content, and revision date; The vector index library uses the Legal-BERT-base model to encode legal provisions into 768-dimensional dense vectors, and constructs the index using the FAISS framework. Specifically, it employs the IVF clustering method to divide the legal provision vectors into 256 cluster centers. During a query, the most relevant cluster is located first, and then a precise search is performed within each cluster, thus reducing retrieval time complexity while maintaining retrieval accuracy. Reduce to ; Metadatabases store auxiliary information about legal provisions, including legal hierarchy, legal force, scope of application, and related provisions, which are used for reordering and filtering search results.

[0018] According to a preferred embodiment of the present invention, generating a reasoned judicial summary includes: Standard full attention coding is used for each type of dispute and claim. Based on the facts of the case, a sparse attention mechanism is introduced during the coding phase; Traditional attention calculation is as follows: (1); in, , , These represent the query matrix, key matrix, and value matrix, respectively. The dimension of the key vector. Represents the attention function. This represents the normalized exponential function; Sparse attention mechanisms involve a combination of three attention modes, as shown below: Local window attention; each Focus only on the front and back indivual A partial window, as shown below: (2); in, , These represent the position numbers of the two tokens in the sequence. Indicates position token to position Attention score of the token It is a location The query vector obtained after linear transformation of the token. It is a location The key vector obtained after linear transformation of the token; Step-through global attention; every indivual Set a global Interact with all locations as follows: (3); Key phrase attention; for identified key phrases, allow the key phrases to interact with global information, as shown below: (4); Where K is the set of key phrase token locations; Indicates the key phrase attention score; Integrated sparse attention This is a combination of local window attention, strafing global attention, and key phrase attention, as shown below: (5); (6); in, The final output of the integrated sparse attention is the sparse attention matrix A_sparse, which is obtained by taking the union of the three attention modes: local window attention A_local, step global attention A_global, and key phrase attention A_key. After being normalized by softmax, it is multiplied by the value matrix V. The summary codes for the dispute type, claims, and facts of the case are as follows: , , ,in The length of the i-th summary is d, and the dimension of the hidden layer is d. Hierarchical cross-attention; employing a hierarchical cross-attention mechanism to capture relationships between summaries; including: The first level of understanding, regarding the type of dispute guiding the litigation claim, is as follows: (7); in, This indicates a statement of claims that has undergone cross-attention enhancement. The second layer involves the type of dispute and the claims in the lawsuit jointly guiding the selection of facts for the case: (8); in, This represents the factual representation of the case after cross-attention enhancement; Cross-attention is defined as follows: (9); Multi-head attention fusion; employing a multi-head mechanism, as shown below: (10); in, This represents the final output of the bullish attention. This represents the output of each attention head. It is a learnable linear projection matrix used to map the concatenated high-dimensional vector back to the original hidden layer dimension to obtain the final multi-head attention output; Set up h=8 attention heads, each focusing on a different semantic dimension; Gating fusion mechanism; introducing a gating mechanism to control the information flow of different digests: (11); (12); in, For contextual representation of other summaries, For the sigmoid function, For element-wise multiplication, the gate value The decision to retain the original information or merge the information. , Let Hᵢ represent the weight matrix and bias term, respectively. Hᵢ represents the original feature representation of the i-th summary after cross-attention enhancement, and H̃ᵢ represents the final feature representation after gating fusion. The final summary, also known as the unified judicial summary generation, involves concatenating the fused features and generating the final summary using a decoder. (13); (14); in, This represents a unified judicial summary representation that integrates the summary encoding representation features of the three sub-modules. The final summary is the result obtained after decoding; it is a concise and information-dense representation of facts.

[0019] Further optimization, setting .

[0020] According to a preferred embodiment of the present invention, hierarchical query rewriting generates a retrieval expression; specifically including: Design a three-layer query rewriting strategy to progressively refine queries from coarse-grained to fine-grained; including: First layer: Case type rewriting; the goal is to map the facts of the case to legal case type categories; given a judicial summary S, i.e. The cause of action category C and the relevant legal field D are obtained through the cause of action classifier: (15); Generate coarse-grained queries: (16); The second layer: element layer rewriting; the goal is to extract key legal elements; based on the judicial summary S and the cause of action category C, a set of legal elements is extracted through a conditional generation model. As shown below: (17); in, This represents the set of legal elements extracted from the abstract, where the subscript k indicates the total number of elements, and e... k That is, the k-th legal element in the set; legal elements include subject elements, behavioral elements, outcome elements, and subjective elements; generating granular queries. : (18); The third layer: standardized rewriting; the goal is to transform factual expressions into legal normative expressions. ,based on and legal terminology dictionary This involves terminology substitution ("not paid" → "unpaid", "delinquent" → "overdue performance"), structural standardization ("because...therefore..." → "when..., ought to..."), and legal terminology conversion. Representing the normalized rewrite function: (19).

[0021] According to a preferred embodiment of the present invention, vectorized legal provision retrieval and reordering includes: Multi-level query parallel retrieval refers to parallel retrieval of three levels of queries, with the results merged, as shown below: (20); (twenty one); (twenty two); (twenty three); in, , , These represent the query representations for the first, second, and third levels, respectively. Representative candidate legal provisions, , , This represents the set of candidate legal provisions retrieved during the search. This represents the total set of candidate legal provisions after merging and deduplication. It is a retrieval operation that selects and returns the k results with the highest similarity scores from the candidate set; The function represents the similarity calculation function between the query vector and the legal provision vector. R1 represents the number of legal provisions with the highest similarity retrieved from the full legal provisions database in the first case type layer retrieval. This indicates the number of items further filtered from the results of R1 in the second-level feature layer retrieval, which serves as the intermediate result R2; This represents the number of records ultimately selected from the results of R2 by the third-level normalized retrieval, which is used as the final result R3. Reordering takes into account query hierarchy, retrieval score, and legal authority. (twenty four); in, This reflects the principle of prioritizing fine-grained details. Indicating legal provisions The authority score is derived from the legal hierarchy information in the metadata database, with higher-level laws scoring higher than lower-level laws. It is the weight of the similarity between the third-level normalized query Q3 and the legal provision r. It is the weight of the similarity between the second-level element layer query Q2 and the legal provision r. It is the weight of the similarity between the first-level case type query Q1 and the legal provision r. This refers to the weight of the legal authority (r), which is assigned a value based on the legal hierarchy to which the legal provision belongs. This represents the comprehensive reordering score of candidate legal provision r. After three layers of query rewriting and collaborative retrieval, the final output is the reordered set of legal provisions. , where m is the final number of legal provisions retained.

[0022] Further optimization, setting , , .

[0023] According to a preferred embodiment of the present invention, constructing a structured generation input specifically includes: After the aforementioned steps, a judicial summary is obtained. and the collection of legal provisions ; By designing regional prompt templates, judicial summaries, retrieved legal provisions, and original factual fragments are organized in a structured manner.

[0024] According to a preferred embodiment of the present invention, segmented controlled generation of judicial reasoning text is provided; specifically, it includes: Step 6.1: Generate the case nature determination; Step 6.2: Generate a dispute focus analysis; Step 6.3: Generate a legal application argument by combining the retrieved legal provisions; Step 6.4: Generate the judgment conclusion.

[0025] A computer device includes a memory and a processor, the memory storing a computer program, and the processor executing the computer program to implement the steps of the above-described method for assisting in drafting judicial documents based on retrieval enhancement.

[0026] A computer-readable storage medium having a computer program stored thereon, which, when executed by a processor, implements the steps of the above-described method for assisting in drafting judicial documents based on retrieval enhancement.

[0027] A retrieval-enhanced judgment writing assistance system includes: The case fact structured segmentation and legal provision database construction module is configured to: receive the basic factual description, party information and disputed points of the case to be processed, perform semantic analysis and rule recognition, divide the content into three sub-modules: dispute type, litigation request and case facts, and at the same time, construct a vectorized legal provision retrieval database; The reasoning-oriented judicial summary generation module is configured to: model three types of sub-modules separately, introduce a sparse attention mechanism to suppress redundant narration for the case facts with low information density and a lot of redundancy, and then generate a unified judicial summary through multi-granularity feature fusion to form a concise and information-dense factual representation. The hierarchical query rewriting and retrieval expression generation module is configured to: rewrite the case cause layer, legal element layer, and standardized expression layer sequentially based on the judicial summary, forming a multi-granularity query expression from coarse to fine; The vectorized legal provision retrieval and reordering module is configured to: perform multi-level parallel retrieval in a pre-built legal provision vector retrieval library, and sort the relevant legal provisions by weight based on semantic similarity and the legal provision validity level, and output a set of relevant legal provisions. The structured input generation module is configured to organize judicial abstracts, retrieved legal provisions, and necessary original text fragments into a structured Prompt according to a preset template, clarifying the generation task and argumentation structure requirements. The segmented controlled generation module for judicial reasoning text is configured to: adopt a phased generation strategy to sequentially complete the determination of the nature of the case, the analysis of the points of contention, the argumentation of the application of law, and the expression of the judgment conclusion, and finally splice them together to form a complete reasoning text.

[0028] The beneficial effects of this invention are as follows: 1. This invention uses a structured block system of "dispute type - litigation claim - case facts" and judicial summary compression to enable the generated model to focus on key factual elements directly related to the judgment conclusion, reduce redundant narrative interference, and thus improve the consistency and completeness of the reasoning text and the facts of the case.

[0029] 2. This invention adopts a hierarchical query rewriting method, which combines case type layer, element layer, and standardization layer, and combines vectorized retrieval and weighted sorting to gradually align factual expressions into standardized legal expressions, thereby enhancing the recall and sorting accuracy of relevant legal provisions and reducing the risk of citing irrelevant or invalid legal provisions.

[0030] 3. This invention, through structured Prompt and segmented controlled generation, fixes the reasoning into a step-by-step unfolding of "case nature determination - analysis of disputed points - argumentation of the application of each legal provision - judgment conclusion". Combined with a retrospective mechanism that ensures consistency of legal provisions and coverage of key facts, it achieves dual constraints on the generated structure and basis, thereby improving the usability and traceability of the output. Attached Figure Description

[0031] Figure 1 This is a schematic diagram of the three-layer structure of the factual section of a judgment document in this invention; Figure 2 This is a diagram of the structure of the vectorized retrieval library in this invention; Figure 3 This is a flowchart of the three-level query rewriting process in this invention; Figure 4 This is a flowchart illustrating the reasoning process of combining abstracts and legal provisions in this invention. Figure 5 This is a general framework diagram of the present invention. Detailed Implementation

[0032] The present invention will be further defined below with reference to the accompanying drawings and embodiments, but is not limited thereto.

[0033] Example 1 A method for assisting in drafting judicial documents based on retrieval enhancement includes: Step 1: Structural segmentation of case facts and construction of a legal provisions database; Receive the basic factual description, party information, and points of contention for the case to be processed, perform semantic analysis and rule recognition, and divide the content into three sub-modules: dispute type, litigation claims, and case facts, providing a structural foundation for subsequent differentiated modeling. Simultaneously, construct a vectorized legal provisions retrieval database covering multiple fields and possessing authoritative and timely information.

[0034] Step 2: Generate reasoning-oriented judicial summaries; model the three types of sub-modules separately, and introduce a sparse attention mechanism to suppress redundant narratives in the case fact section with low information density and a lot of redundancy (containing a lot of procedural descriptions that make the text lengthy but key information sparse). Then, generate a unified judicial summary through multi-granularity feature fusion to form a concise and information-dense factual representation. Step 3: Layered query rewriting to generate search expressions; based on the judicial abstract, the case cause layer is rewritten, the legal element layer is rewritten, and the standardized expression is rewritten in sequence to form a multi-granularity query expression from coarse to fine; this is used to improve the semantic matching effect of legal provisions.

[0035] Step 4: Vectorized legal provision retrieval and reordering; Perform multi-level parallel retrieval in a pre-built legal provision vector retrieval library, and sort the relevant legal provisions by weight based on semantic similarity and legal provision validity level, and output the relevant legal provision set; Step 5: Construct a structured input for generation; organize the judicial abstract, retrieved legal provisions, and necessary original text fragments into a structured Prompt according to a preset template, and clarify the generation task and argumentation structure requirements; Step 6: Segmented controlled generation of the judgment reasoning text; adopting a phased generation strategy, the determination of the nature of the case, analysis of the points of contention, argumentation of the application of law, and expression of the judgment conclusion are completed in sequence, and finally spliced ​​together to form a complete reasoning text.

[0036] Example 2 The difference between the method for assisting in drafting judicial documents based on retrieval enhancement as described in Example 1 and the method described in Example 1 is as follows: Analysis of the factual sections of court judgments reveals inherent patterns in their structure. Therefore, regular expressions can be used to divide these texts into three sub-modules. The specific implementation process is as follows:

[0037] (1) Dispute Type Module: Dispute types typically appear in the text as "XX Dispute Case" or "XX Dispute" in the document title. The following regular expression can be used:

[0038] pattern_type = r'([\u4e00-\u9fa5]+dispute)case' (2) Claims Module: The claims section begins with "Accounts Claimed:" and ends with the content before "Ascertained Upon Trial:". The following regular expression can be used:

[0039] pattern_claim = r'The claim[::](.*?)(?=Defendant.*?(?:Defense|Response|Failure to respond within the time limit)|Ascertained after trial)' (3) Case Facts Module: The case facts section begins with "After investigation:" and continues to the end of the text (within the scope of the case_facts field). The following regular expression can be used:

[0040] pattern_fact = r'After investigation, it was found that [::](.*)' For example, regarding the factual part: Civil Judgment of the First Instance in a Lease Contract Dispute between A and B (Civil Judgment of the People's Court of a Certain District, a Certain City) Plaintiff A, female, born February 18, 1966, Han nationality, residing in a certain district, a certain city. Defendant B, male, Han nationality, residing in a certain district, a certain city. This court accepted the case of Plaintiff A versus Defendant B regarding a lease contract dispute on February 22, 2017, and conducted a public hearing in accordance with the simplified procedure. Plaintiff A appeared in court to participate in the litigation. Defendant B, having been lawfully summoned by this court, failed to appear in court to participate in the litigation without justifiable reason. This court has now concluded the trial. Plaintiff A alleged that: In 2013, Defendant B rented steel pipes and fasteners from me. By January 30, 2014, Defendant B owed me a total of 38,320 yuan and gave me an IOU, promising to pay it off by March 20, 2014, or at a rate of 2% interest. As of February 7, 2016, the defendant had only paid me 15,000 yuan in three installments, and the remaining 23,320 yuan remained unpaid despite repeated demands. I request that the court order the defendant to pay the plaintiff the rent of 23,320 yuan plus interest on the overdue payments. The defendant shall bear the litigation costs. Defendant B failed to file a defense by the due date. The court found that in 2013, Defendant B began renting steel pipes and fasteners from Plaintiff A. As of January 30, 2014, Defendant B owed Plaintiff a total of 38,320 yuan in rent and issued an IOU to Plaintiff stating: "IOU, I hereby owe Plaintiff A 38,320 yuan (thirty thousand three hundred and twenty yuan) in steel pipe rent, to be settled by March 20, 2014. If not settled, interest will be calculated at 2% (starting from September 13, 2013). Debtor: B, January 30, 2014." Defendant B subsequently paid Plaintiff a total of 15,000 yuan in rent in three installments, leaving 23,320 yuan unpaid. After repeated unsuccessful attempts to collect the outstanding amount, Plaintiff filed a lawsuit in court.

[0041] The extraction results are shown in Table 1: Table 1 Analysis of court judgments in the CAIL2018 dataset reveals that the factual portion can be semantically and structurally divided into three levels: dispute type, claims, and case facts; for example... Figure 1 As shown, the three levels have different content characteristics and functional positioning.

[0042] The dispute type layer contains highly generalized information such as the cause of action, the nature of the dispute, and the legal relationships involved. It typically begins the factual section and serves to establish the basic framework for the application of law. The claims layer covers the plaintiff's claims, the defendant's response, and the third party's assertions, clearly reflecting the focus of the dispute and defining the boundaries of the judgment's reasoning. The case factual record documents the facts ascertained during the trial and the admissibility of evidence; this is the longest and most detailed section, but it also contains a large amount of procedural description and redundant information. Typical characteristics of the three layers were statistically analyzed. It can be seen that the average length of the case factual section is more than 15 times that of the dispute type layer, but its information density is only 60% of that, indicating a significant redundancy problem. As shown in Table 2:

[0043] Table 2 To support efficient legal provision retrieval, this invention constructs a vectorized search library covering major legal fields. The data originates from the National Legal Regulations Database and publicly available legal texts on the China Judgments Online website, including 156 laws such as the Civil Code of the People's Republic of China, the Contract Law of the People's Republic of China, and the Tort Liability Law of the People's Republic of China, totaling 8742 legal provisions.

[0044] Construct a vectorized legal provision retrieval library; including: The vectorized legal provision retrieval library includes a legal provision text library, a vector index library, and a metadata database; such as Figure 2 As shown.

[0045] The legal text database stores the original legal texts, including complete information such as the law name, article number, article content, and revision date; The vector index library uses the Legal-BERT-base model to encode legal provisions into 768-dimensional dense vectors, and constructs the index using the FAISS (Facebook AI Similarity Search) framework. Specifically, it employs the IVF (Inverted File) clustering method to divide the legal provision vectors into 256 cluster centers. During a query, the most relevant cluster is located first, and then a precise search is performed within each cluster, thus reducing retrieval time complexity while maintaining retrieval accuracy. Reduce to ; Without any optimization, each query requires comparing the query vector with each of the n legal provision vectors in the legal provision database, resulting in a linear increase in computational cost with the number of legal provisions and low retrieval efficiency. To address this issue, this paper employs the IVF (Inverted File) inverted index method from the FAISS framework to accelerate retrieval. The basic idea of ​​this method is similar to a library's partitioned search: instead of searching through all bookshelves one by one, it first locates the relevant shelf based on the topic and then searches for the target book within that shelf. Specifically, when building the index, the 8742 legal provision vectors are first divided into 256 groups based on semantic similarity using the K-Means clustering algorithm. Each group uses a central vector to summarize the overall semantic features of the legal provisions in that group, with an average of about 34 legal provisions per group. During actual retrieval, the query vector is first compared with the central vectors of the 256 groups to quickly find the groups with the closest semantics. Then, matching is performed only within these groups, without traversing all legal provisions. This significantly reduces the number of legal provisions that need to be compared from thousands to just over a hundred, and the retrieval time complexity is reduced from... Reduce to This significantly improves retrieval speed with almost no loss of retrieval accuracy. The time complexity is... This indicates that the computational load is directly proportional to n.

[0046] Metadatabases store supplementary information about legal provisions, including legal hierarchy (constitution, laws, administrative regulations, etc.), legal force, scope of application, and related provisions, which are used for reordering and filtering search results.

[0047] Generate reasoned judicial summaries; such as Figure 4 As shown, it specifically includes: This invention employs BART-based as the fundamental summarization model, comprising a 6-layer encoder and a 6-layer decoder, with 768 hidden layers and 12 attention heads. The encoder maps the input text information into an encoded representation through an attention mechanism. The dispute type and litigation claim sections are relatively short and have high information density, making standard full-attention encoding effective for modeling. However, the case facts section is lengthy, and a full-attention mechanism would result in excessive weighting of noisy information. Therefore, a sparse attention mechanism is introduced during the case facts encoding stage.

[0048] Standard full attention coding is used for each type of dispute and claim. To address the issue of lengthy factual sections in the case document, a sparse attention mechanism is introduced during the coding phase. Traditional attention calculation is as follows: (1); in, , , These represent the query matrix, key matrix, and value matrix, respectively. The dimension of the key vector. Represents the attention function. This represents the normalized exponential function; Sparse attention mechanisms involve a combination of three attention modes, as shown below: Local window attention; each Focus only on the front and back indivual A partial window, as shown below: (2); in, , These represent the position numbers of the two tokens in the sequence. Indicates position token to position The attention score of the token; the higher the value, the better the position. The more "attention" the position Information, It is a location The query vector obtained after linear transformation of the token. It is a location The key vector obtained after linear transformation of the token; Step-through global attention; every indivual Set a global Interact with all locations as follows: (3); This design selects a "representative token" every 's' positions, and only these representatives can interact with all other positions in the sequence. Let's look at the conditional statements in the formula:

[0049] `i mod s = 0` means that position `i` is divisible by `s`. For example, when `s = 8`, tokens at positions 0, 8, 16, 24, etc., are selected as "global representatives". When `i` is a global representative, it can focus on information at any position `j` in the sequence.

[0050] `j mod s = 0` means that position `j` is divisible by `s`. Attention can be computed even if position `i` is not the global representative, as long as the target position `j` it wants to focus on is the global representative.

[0051] In other words, if either i or j is a global representative (its position number is divisible by s), the attention score is calculated normally; otherwise, it is set to negative infinity, and the weights are reduced to zero after softmax.

[0052] Key phrase attention; for identified key phrases (such as "court found out", "plaintiff's claim", etc.), key phrases are allowed to interact with global information, as shown below: (4); Where K is the set of key phrase token locations; denoted as Key Phrase Attention Score; where K is the pre-identified set of key phrase token locations (such as the locations of judicial landmark phrases like "court found out" and "plaintiff's claim"). Attention is calculated normally when position i or j belongs to this set, so that key phrases can fully interact with global information and guide the model to focus on core factual fragments related to reasoning. Integrated sparse attention This is a combination of local window attention, strafing global attention, and key phrase attention, as shown below: (5); (6); in, The final output of the integrated sparse attention is obtained by taking the union of three attention modes: local window attention A_local, step global attention A_global, and key phrase attention A_key, and then multiplying the result by the value matrix V after softmax normalization. This significantly reduces computational complexity while capturing local context, long-distance dependencies, and key factual information.

[0053] After passing the text from the three sub-modules through encoders using their respective attention methods, the resulting summary encoding representations of the dispute type, litigation claims, and case facts are as follows: , , ,in Let d be the length of the i-th summary and d be the dimension of the hidden layer. Analysis revealed information overlap among the three sub-modules at the textual level: the dispute type and litigation request may repeatedly describe the cause of action, and the litigation request and case facts may repeatedly state key facts, resulting in significant information redundancy. Therefore, a feature fusion module is used to capture the semantic relationships between the three summaries, remove redundant information, and generate an information-dense unified judicial summary.

[0054] Hierarchical cross-attention; employing a hierarchical cross-attention mechanism to capture relationships between summaries; including: The first level of understanding, regarding the type of dispute guiding the litigation claim, is as follows: (7); in, This indicates a statement of claims that has undergone cross-attention enhancement. This means that cross-attention calculation is performed using the litigation claim code H2 as the query and the dispute type code H1 as both the key and value. This enhances the representation of the litigation claim under the guidance of the dispute type semantics, allowing the model to incorporate higher-level contextual information such as cause of action and legal relationship when understanding the litigation claim.

[0055] The second layer involves the type of dispute and the claims in the lawsuit jointly guiding the selection of facts for the case: (8); in, This represents the case facts representation after cross-attention enhancement; the case facts code H3 is used as the query, and the vector [H1;H2'] concatenated from the dispute type code H1 and the enhanced litigation request code H2' is used as both the key and value. This allows the case facts representation to be filtered under the joint guidance of the dispute type and litigation request, thereby enabling the model to focus on key factual content related to the cause of action and the focus of the dispute, and to filter out redundant procedural descriptions.

[0056] Cross-attention is defined as follows: (9); Multi-head attention fusion: To capture the connections between different semantic spaces, a multi-head mechanism is adopted, as shown below: (10); in, This represents the final output of multi-head attention. Its core idea is to split the attention computation into h independent subspaces (h=8 in this paper) and execute them in parallel. This represents the output of each attention head, with each head capturing relational information in different dimensions within a different semantic subspace. It is a learnable linear projection matrix used to map the concatenated high-dimensional vector back to the original hidden layer dimension to obtain the final multi-head attention output; Set up h=8 attention heads, each focusing on a different semantic dimension; Gating fusion mechanism; introducing a gating mechanism to control the information flow of different digests: (11); (12); in, For contextual representation of other summaries, For the sigmoid function, For element-wise multiplication, the gate value The decision to retain the original information or merge the information. , Let Hᵢ represent the weight matrix and bias term, respectively. Hᵢ represents the original feature representation of the i-th summary (dispute type, claim, or case facts) after cross-attention enhancement, and H̃ᵢ represents the final feature representation after gated fusion. This formula controls the proportion of information fusion through a gating value gᵢ (ranging from 0 to 1): when gᵢ is close to 1, H̃ᵢ retains more of its original information Hᵢ; when gᵢ is close to 0, H̃ᵢ absorbs more contextual information H_context from other summaries. During training, the model automatically learns the optimal gating value for each position, achieving adaptive filtering of redundant information and effective fusion of complementary information.

[0057] The final summary, also known as the unified judicial summary generation, involves concatenating the fused features and generating the final summary using a decoder. (13); (14); in, This represents a unified judicial summary representation that integrates the summary encoding representation features of the three sub-modules. The final summary is the result obtained after decoding; it is a concise and information-dense representation of facts.

[0058] The aforementioned attention mechanism can significantly reduce computational complexity. Complexity analysis shows that the time complexity of traditional full attention is... The space complexity is The sparse attention complexity of this invention is: local window Step into the whole Key phrases The overall complexity is In this invention, a setting is provided. The overall complexity is close to This significantly reduces computational overhead.

[0059] Hierarchical query rewriting to generate search expressions; specifically including: Final Summary This serves as the foundational input for the next step of enhanced retrieval. However, judicial abstracts describe facts using natural language, while legal provisions describe legal rules using normative language. This "expression gap" leads to problems such as low similarity in vector retrieval, failure to recall relevant legal provisions, and inaccurate citation of legal provisions. To address this issue, a three-layer query rewriting strategy is designed, progressively refining the query from coarse-grained to fine-grained; for example... Figure 3 As shown. Includes:

[0060] First layer: Case type rewriting; the goal is to map the facts of the case to legal case type categories; given a judicial summary S, i.e. The cause of action category C and the relevant legal field D are obtained through the cause of action classifier: This includes contract law, tort law, etc. The case classification model is essentially a text classification model. Specifically, the judicial summary S is input into the Legal-BERT encoder to obtain a text vector representation. This vector representation is then passed through a fully connected classification layer, which outputs the probability distribution of each case category. The category with the highest probability is taken as the case category C. Then, the relevant legal domain D is located based on a pre-constructed case category-legal domain mapping relationship. For example, when C is "lease contract dispute," D covers the Contract Law section of the Civil Code, the Contract Law, and related judicial interpretations; when C is "tort liability dispute," D covers the Tort Law section of the Civil Code, the Tort Liability Law, and related judicial interpretations.

[0061] (15); Generate coarse-grained queries: (16); The purpose of this layer is to narrow the search scope to specific legal fields, filter out irrelevant legal provisions, and improve search efficiency.

[0062] The second layer: element layer rewriting; the goal is to extract key legal elements; based on the judicial summary S and the cause of action category C, a set of legal elements is extracted through a conditional generation model. As shown below: The condition generation model uses the T5-base model. Specifically, the judicial summary S and the cause of action category C are concatenated as input, and a specific prompt instruction "Extract the following legal elements of cause of action C:" is used as a condition to guide the model to generate a list of legal elements in a sequence-to-sequence (Seq2Seq) manner. For example, if the input is a summary text of "lease contract dispute", the model output may be: "e1=Lease relationship established; e2=Defendant overdue rent payment; e3=Plaintiff's repeated demands for payment unsuccessful".

[0063] (17); in, This represents the set of legal elements extracted from the abstract, where the subscript k indicates the total number of elements, and e... k This refers to the k-th (and last) legal element in the set; each element eᵢ corresponds to an independent legal requirement, including subject elements (such as the identity of the party), behavioral elements (such as overdue payment), result elements (such as rent arrears of 1.56 million yuan), and subjective elements (such as the existence of fault). Legal elements include subject elements (the identity and qualifications of the party), behavioral elements (actions and omissions), result elements (damage consequences and breach of contract), and subjective elements (fault and intent); generating granular queries. :

[0064] (18); For example: "In construction contract disputes, if the employer delays payment and the contractor has completed the work, the employer shall bear the responsibility..."

[0065] The third layer: standardized rewriting; the goal is to transform factual expressions into legal normative expressions. , This refers to the second-layer generated query Q2, which still contains factual, colloquial expressions. Through a terminology dictionary T, it undergoes legal-language conversion to make its expression style closer to the normative language of legal provisions, thereby narrowing the "expression gap" between the query vector and the legal provision vector and improving the accuracy of retrieval matching. Based on and legal terminology dictionary This involves terminology substitution ("not paid" → "unpaid", "delinquent" → "overdue performance"), structural standardization ("because...therefore..." → "when..., ought to..."), and legal terminology conversion. Representing the normalized rewrite function:

[0066] (19).

[0067] Vectorized legal provision retrieval and reordering; including: Multi-level query parallel retrieval refers to parallel retrieval of three levels of queries, with the results merged, as shown below: (20); (twenty one); (twenty two); (twenty three); in, , , These represent the query representations at the first level (coarse-grained at the cause-of-fact level), the second level (medium-grained at the element level), and the third level (fine-grained at the normalized level), respectively. Representative candidate legal provisions, , , This represents the set of candidate legal provisions retrieved during the search. This represents the total set of candidate legal provisions after merging and deduplication. It is a retrieval operation that selects and returns the k results with the highest similarity scores from the candidate set; The function represents the similarity calculation function between the query vector and the legal vector. This invention uses cosine similarity to measure the degree of closeness between the two in the semantic space. R1 represents the number of legal provisions with the highest similarity retrieved from the full legal provisions database at the first case level. The large search scope aims to ensure a high recall rate and minimize the omission of relevant legal provisions. This indicates the number of results further filtered from the R1 results in the second element layer retrieval, which serves as the intermediate result R2; the retrieval scope is narrowed by filtering out insufficiently precise legal provisions in the first layer through legal element matching. R3 represents the number of entries ultimately selected from the results of R2 by the third-level normalized retrieval; it has the smallest retrieval range, and the query after normalization and rewriting is highly matched with the legal provisions, outputting the most accurate set of legal provisions, which can be directly used for subsequent reasoning generation.

[0068] Re-ranking takes into account query hierarchy (fine-grained queries have higher weight), retrieval score, and legal authority (higher-level law > lower-level law): (twenty four); in, This reflects the principle of prioritizing fine-grained details. Indicating legal provisions The authority score is derived from the legal hierarchy information in the metadata database, with higher-level laws scoring higher than lower-level laws. This is the weight of the similarity between the third-level normalized query Q3 and the legal provision r. The largest value reflects the principle of prioritizing fine-grained queries—the query after normalization is closest to the legal provision's expression, resulting in the most reliable matching result. It is the weight of the similarity between the second-level element layer query Q2 and the legal provision r, second only to This reflects that the importance of element-level matching is second only to the normalization layer. This is the weight of the similarity between the first-level case-related query Q1 and the legal provision r. It takes the smallest value because the case-related query has the coarsest granularity and the matching accuracy is relatively low. This is the weight of the legal authority(r), used to introduce information about the legal effect of the legal provision itself. The authority(r) is assigned a value according to the legal hierarchy to which the legal provision belongs. Higher-level laws (such as the constitution and laws) have higher authority than lower-level laws (such as administrative regulations and local regulations), so that legal provisions with higher legal effect levels are ranked higher when they are of equal similarity. This represents the comprehensive reordering score of candidate legal provision *r*, used to uniformly sort all candidate legal provisions returned by the three-layer retrieval. Legal provisions with higher scores are prioritized for inclusion in the final result. After three-layer query rewriting and collaborative retrieval, the final output is the reordered set of legal provisions. , where m is the final number of legal provisions retained (in this paper, top-k3=10). This set of legal provisions, along with the generated judicial summary S, will serve as the input for the next stage of the reasoning generation module.

[0069] set up , , .

[0070] This refers to: weighting and sorting relevant legal provisions based on semantic similarity and the level of their validity, and outputting a set of related legal provisions; This invention compares the retrieval performance of different rewriting levels, as shown in Table 3. It can be seen that the three-layer collaborative rewriting method improves the Recall@10 and MRR metrics by 28.3% and 31.7% respectively compared to the baseline method without rewriting.

[0071] Table 3 Constructing structured inputs; specifically including: After the aforementioned steps, a judicial summary is obtained. and the collection of legal provisions ; By designing regionalized prompt templates, judicial summaries, retrieved legal provisions, and original factual fragments are organized in a structured manner. An example of a prompt template is shown below.

[0072] [Case Summary]; {Judicial Summary S}; [Applicable Law]; {Retrieve legal provisions r1, r2, ..., r m}; [Original Facts] (Optional); {N sentences before the original facts + M sentences after the original facts}; [Generation Requirements]; Based on the facts of the case and the relevant legal provisions, please generate the reasoning section of the judgment.

[0073] Requirements: 1. First, determine the nature of the case and the legal relationship; 2. Analyze the points of contention between the two parties; 3. Explain the application of the law clause by clause; 4. Draw the judge's conclusion; Segmented and controlled generation of judge's reasoning text; specifically including: To ensure generation quality, a segmented generation strategy is adopted: Step 6.1: Generate case nature determination; take the judicial summary S and the retrieved legal provisions R as input, and specify the generation goal as "determine the nature of the case and legal relationship" in the Prompt. The model will output the basic characterization of the case accordingly.

[0074] Step 6.2: Generate the focus of the dispute; append the output of Step 6.1 to the context, and specify the generation goal as "Analyze the focus of the dispute between the two parties" in the Prompt. The model analyzes the dispute between the two parties based on the existing case characterization.

[0075] Step 6.3: Generate a legal application argument by combining the retrieved legal provisions; using the outputs of Steps 6.1 and 6.2, along with the retrieved relevant legal provisions, as the context, the Prompt specifies the generation goal as "argumenting the legal application clause by clause". After clarifying the focus of the dispute, the model cites specific legal provisions for argumentation.

[0076] Step 6.4: Generate the judgment conclusion. Using the outputs of the first three steps as context, the Prompt command specifies the generation goal as "to arrive at the judgment conclusion." The model outputs the final judgment conclusion based on the complete chain of arguments.

[0077] Finally, the outputs of the four steps are pieced together in sequence to form a complete argumentative text. Each step uses the output of the preceding steps as known context, making the argumentation logic progressive—first defining the nature of the argument, then analyzing the controversy, then citing legal provisions, and finally drawing a conclusion. This avoids the logical jumps or contradictions that can easily occur when generating a long text all at once.

[0078] Example input: Civil Judgment of the First Instance in a Lease Contract Dispute between A and B (Civil Judgment of the People's Court of a Certain District, a Certain City) Plaintiff A, female, born February 18, 1966, Han nationality, residing in a certain district, a certain city. Defendant B, male, Han nationality, residing in a certain district, a certain city. This court accepted the case of Plaintiff A versus Defendant B regarding a lease contract dispute on February 22, 2017, and conducted a public hearing in accordance with the simplified procedure. Plaintiff A appeared in court to participate in the litigation. Defendant B, having been lawfully summoned by this court, failed to appear in court to participate in the litigation without justifiable reason. This court has now concluded the trial. Plaintiff A alleged that: In 2013, Defendant B rented steel pipes and fasteners from me. By January 30, 2014, Defendant B owed me a total of 38,320 yuan and gave me an IOU, promising to pay it off by March 20, 2014, or at a rate of 2% interest. As of February 7, 2016, the defendant had only paid me 15,000 yuan in three installments, and the remaining 23,320 yuan remained unpaid despite repeated demands. I request that the court order the defendant to pay the plaintiff the rent of 23,320 yuan plus interest on the overdue payments. The defendant shall bear the litigation costs. Defendant B failed to file a defense by the due date. The court found that in 2013, Defendant B began renting steel pipes and fasteners from Plaintiff A. As of January 30, 2014, Defendant B owed Plaintiff a total of 38,320 yuan in rent and issued an IOU to Plaintiff stating: "IOU, I hereby owe Plaintiff A 38,320 yuan (thirty thousand three hundred and twenty yuan) in steel pipe rent, to be settled by March 20, 2014. If not settled, interest will be calculated at 2% (starting from September 13, 2013). Debtor: B, January 30, 2014." Defendant B subsequently paid Plaintiff a total of 15,000 yuan in rent in three installments, leaving 23,320 yuan unpaid. After repeated unsuccessful attempts to collect the outstanding amount, Plaintiff filed a lawsuit in court.

[0079] Example output: Step 6.1: This court holds that the steel pipe and fastener leasing relationship between Plaintiff A and Defendant B is a true expression of their intentions, legal and valid, and both parties should perform their respective obligations as agreed.

[0080] Step 6.2: Plaintiff A's request for Defendant B to repay the rental fee of 23,320 yuan is supported by the IOU issued by Defendant B and the payment record. The facts are clear and the evidence is conclusive, and this court recognizes it. Regarding the plaintiff's request for overdue interest, interest can be calculated at an annual rate of 24% from September 13, 2013, as stipulated in the IOU issued by Defendant B to Plaintiff A.

[0081] Step 6.3: In accordance with Article 144 of the Civil Procedure Law of the People's Republic of China, Article 212 of the Contract Law of the People's Republic of China, and Article 226 of the Contract Law of the People's Republic of China; Step 6.4: The judgment is as follows: 1. Defendant B shall pay Plaintiff A rent of RMB 23,320 and interest (calculated at an annual interest rate of 24% from September 13, 2013 until the date of full payment) within ten days from the date this judgment becomes effective. II. The plaintiff's other claims are dismissed. If the monetary obligations are not fulfilled within the period specified in this judgment, the defendant shall pay double the interest on the debt for the period of delay, in accordance with Article 253 of the Civil Procedure Law of the People's Republic of China. The case acceptance fee of RMB 383 shall be borne by Defendant B.

[0082] The output of each step serves as context for the next step, forming a coherent chain of reasoning. The final output is the concatenation of the outputs from the four steps. Through segmented control, the model can progressively unfold its arguments, avoiding logical jumps and factual deviations common in long text generation. The overall generation process is detailed below. Figure 5 .

[0083] To demonstrate the practical effectiveness of this invention, the following baseline models were selected for comparison, covering three categories: general generative models, legal domain models, and retrieval enhancement methods. ChatGLM3-6B and ChatGLM3-SFT constituted a hierarchical baseline between zero-shot and SFT methods; Baichuan2-7B-SFT verified cross-model generalization; LexiLaw and LaWGPT represented existing legal domain methods; Naive-RAG and Dense-RAG represented standard implementations of sparse and dense retrieval enhancement schemes, respectively, used to evaluate the advantages of hierarchical query rewriting strategies in the SAGE framework compared to traditional RAG methods. All SFT and RAG baselines used the same ChatGLM3-6B base and LoRA fine-tuning configuration to ensure the fairness of the comparison. The comparison results are shown in Table 4.

[0084] Table 4 Example 3 A computer device includes a memory and a processor. The memory stores a computer program, and the processor executes the computer program to implement the steps of the retrieval-enhanced judgment writing assistance method described in Embodiment 1 or 2.

[0085] Example 4 A computer-readable storage medium having a computer program stored thereon, wherein the computer program, when executed by a processor, implements the steps of the method for assisting in drafting judicial documents based on retrieval enhancement as described in Embodiment 1 or 2.

[0086] Example 5 A retrieval-enhanced judgment writing assistance system includes: The case fact structuring and legal provision database construction module is configured to: receive the basic factual description, party information, and points of contention for a case to be processed; perform semantic analysis and rule recognition; and divide the content into three sub-modules: dispute type, litigation claims, and case facts, providing a structural foundation for subsequent differentiated modeling. Simultaneously, it constructs a vectorized legal provision retrieval database covering multiple fields and possessing authoritative and timely information.

[0087] The reasoning-oriented judicial summary generation module is configured to: model three types of sub-modules separately; introduce a sparse attention mechanism to suppress redundant narration in the factual part of the case with low information density and a lot of redundancy (containing a lot of procedural descriptions that make the text lengthy but key information sparse); and then generate a unified judicial summary through multi-granularity feature fusion to form a concise and information-dense factual representation. The hierarchical query rewriting module is configured to rewrite the case at the cause of action level, the legal element level, and the standardized expression level sequentially based on the judicial summary, forming a multi-granularity query expression from coarse to fine; this is used to improve the semantic matching effect of legal provisions.

[0088] The vectorized legal provision retrieval and reordering module is configured to: perform multi-level parallel retrieval in a pre-built legal provision vector retrieval library, and sort the relevant legal provisions by weight based on semantic similarity and the legal provision validity level, and output a set of relevant legal provisions. The structured input generation module is configured to organize judicial abstracts, retrieved legal provisions, and necessary original text fragments into a structured Prompt according to a preset template, clarifying the generation task and argumentation structure requirements. The segmented controlled generation module for judicial reasoning text is configured to: adopt a phased generation strategy to sequentially complete the determination of the nature of the case, the analysis of the points of contention, the argumentation of the application of law, and the expression of the judgment conclusion, and finally splice them together to form a complete reasoning text.

Claims

1. A method for assisting in drafting judicial documents based on retrieval enhancement, characterized in that, include: Step 1: Structured segmentation of case facts and construction of a legal provisions database; The system receives basic factual descriptions, party information, and points of contention for cases to be processed, performs semantic analysis and rule recognition, divides the content into three sub-modules: dispute type, litigation claims, and case facts, and simultaneously constructs a vectorized legal provision retrieval database. Step 2: Generate reasoning-oriented judicial summaries; model the three types of sub-modules separately, and introduce a sparse attention mechanism to suppress redundant narration for the case facts with low information density and a lot of redundancy. Then, generate a unified judicial summary through multi-granularity feature fusion to form a concise and information-dense factual representation. Step 3: Rewrite the hierarchical query to generate the retrieval expression; Based on the judicial summary, the case cause level, legal element level, and standardized expression are rewritten in sequence to form a multi-granularity query expression from coarse to fine. Step 4: Vectorized legal provision retrieval and reordering; Perform multi-level parallel retrieval in a pre-built legal provision vector retrieval library, and sort the relevant legal provisions by weight based on semantic similarity and legal provision validity level, and output the relevant legal provision set; Step 5: Construct structured generation input; The judicial summary, retrieved legal provisions, and necessary original text excerpts are organized into a structured Prompt according to a preset template, clearly defining the generation task and argumentation structure requirements; Step 6: Segmented controlled generation of the judgment reasoning text; adopting a phased generation strategy, the determination of the nature of the case, analysis of the points of contention, argumentation of the application of law, and expression of the judgment conclusion are completed in sequence, and finally spliced ​​together to form a complete reasoning text.

2. The method for assisting in drafting judicial documents based on retrieval enhancement as described in claim 1, characterized in that, Construct a vectorized legal provision retrieval library; including: The vectorized legal provision retrieval library includes a legal provision text library, a vector index library, and a metadata database; The legal text database stores the original legal texts, including complete information such as the law name, article number, article content, and revision date; The vector index library uses the Legal-BERT-base model to encode legal provisions into 768-dimensional dense vectors, and constructs the index using the FAISS framework. Specifically, it employs the IVF clustering method to divide the legal provision vectors into 256 cluster centers. During a query, it first locates the most relevant cluster, and then performs a precise search within each cluster, thus reducing retrieval time complexity while maintaining retrieval accuracy. Reduce to ; Metadatabases store auxiliary information about legal provisions, including legal hierarchy, legal force, scope of application, and related provisions, which are used for reordering and filtering search results.

3. The method for assisting in drafting judicial documents based on retrieval enhancement as described in claim 1, characterized in that, Generate reasoned judicial summaries; specifically including: Standard full attention coding is used for each type of dispute and claim. Based on the facts of the case, a sparse attention mechanism is introduced during the coding phase; Traditional attention calculation is as follows: (1); in, , , These represent the query matrix, key matrix, and value matrix, respectively. The dimension of the key vector. Represents the attention function. This represents the normalized exponential function; Sparse attention mechanisms involve a combination of three attention modes, as shown below: Local window attention; each Focus only on the front and back indivual A partial window, as shown below: (2); in, , These represent the position numbers of the two tokens in the sequence. Indicates position token to position Attention score of the token It is a location The query vector obtained after linear transformation of the token. It is a location The key vector obtained after linear transformation of the token; Step-through global attention; every indivual Set a global Interact with all locations as follows: (3); Key phrase attention; for identified key phrases, allow the key phrases to interact with global information, as shown below: (4); Where K is the set of key phrase token locations; Indicates the key phrase attention score; Integrated sparse attention This is a combination of local window attention, strafing global attention, and key phrase attention, as shown below: (5); (6); in, The final output of the integrated sparse attention is the sparse attention matrix A_sparse, which is obtained by taking the union of the three attention modes: local window attention A_local, step global attention A_global, and key phrase attention A_key. After being normalized by softmax, it is multiplied by the value matrix V. The summary codes for the dispute type, claims, and facts of the case are as follows: , , ,in The length of the i-th summary is d, and the dimension of the hidden layer is d. Hierarchical cross-attention; employing a hierarchical cross-attention mechanism to capture relationships between summaries; including: The first level of understanding, regarding the type of dispute guiding the litigation claim, is as follows: (7); in, This indicates a statement of claims that has undergone cross-attention enhancement. The second layer involves the type of dispute and the claims in the lawsuit jointly guiding the selection of facts for the case: (8); in, This represents the factual representation of the case after cross-attention enhancement; Cross-attention is defined as follows: (9); Multi-head attention fusion; employing a multi-head mechanism, as shown below: (10); in, This represents the final output of the bullish attention. This represents the output of each attention head. It is a learnable linear projection matrix used to map the concatenated high-dimensional vector back to the original hidden layer dimension to obtain the final multi-head attention output; Set up h=8 attention heads, each focusing on a different semantic dimension; Gating fusion mechanism; introducing a gating mechanism to control the information flow of different digests: (11); (12); in, For contextual representation of other summaries, For the sigmoid function, For element-wise multiplication, the gate value The decision to retain the original information or merge the information. , Let Hᵢ represent the weight matrix and bias term, respectively. Hᵢ represents the original feature representation of the i-th summary after cross-attention enhancement, and H̃ᵢ represents the final feature representation after gating fusion. The final summary, also known as the unified judicial summary generation, involves concatenating the fused features and generating the final summary using a decoder. (13); (14); in, This represents a unified judicial summary representation that integrates the summary encoding representation features of the three sub-modules. The final summary is the result obtained after decoding; it is a concise and information-dense representation of facts.

4. The method for assisting in drafting judicial documents based on retrieval enhancement as described in claim 1, characterized in that, Hierarchical query rewriting to generate search expressions; specifically including: Design a three-layer query rewriting strategy to progressively refine queries from coarse-grained to fine-grained; including: First layer: Case type rewriting; the goal is to map the facts of the case to legal case type categories; given a judicial summary S, i.e. The cause of action category C and the relevant legal field D are obtained through the cause of action classifier: (15); Generate coarse-grained queries: (16); The second layer: element layer rewriting; the goal is to extract key legal elements; based on the judicial summary S and the cause of action category C, a set of legal elements is extracted through a conditional generation model. As shown below: (17); in, This represents the set of legal elements extracted from the abstract, where the subscript k indicates the total number of elements, and e... k That is, the k-th legal element in the set; legal elements include subject elements, behavioral elements, outcome elements, and subjective elements; generating granular queries. : (18); The third layer: standardized rewriting; the goal is to transform factual expressions into legal normative expressions. ,based on and legal terminology dictionary This involves terminology replacement, structural standardization, and legal terminology conversion. Representing the normalized rewrite function: (19)。 5. The method for assisting in drafting judicial documents based on retrieval enhancement as described in claim 1, characterized in that, Vectorized legal provision retrieval and reordering; including: Multi-level query parallel retrieval refers to parallel retrieval of three levels of queries, with the results merged, as shown below: (20); (21); (22); (23); in, , , These represent the query representations for the first, second, and third levels, respectively. Representative candidate legal provisions, , , This represents the set of candidate legal provisions retrieved during the search. This represents the total set of candidate legal provisions after merging and deduplication. It is a retrieval operation that selects and returns the k results with the highest similarity scores from the candidate set; The function represents the similarity calculation function between the query vector and the legal provision vector. R1 represents the number of legal provisions with the highest similarity retrieved from the full legal provisions database in the first case type layer retrieval. This indicates the number of items further filtered from the results of R1 in the second-level feature layer retrieval, which serves as the intermediate result R2; This represents the number of records ultimately selected from the results of R2 by the third-level normalized retrieval, which is used as the final result R3. Reordering takes into account query hierarchy, retrieval score, and legal authority. (24); in, This reflects the principle of prioritizing fine-grained details. Indicating legal provisions The authority score is derived from the legal hierarchy information in the metadata database, with higher-level laws scoring higher than lower-level laws. It is the weight of the similarity between the third-level normalized query Q3 and the legal provision r. It is the weight of the similarity between the second-level element layer query Q2 and the legal provision r. It is the weight of the similarity between the first-level case type query Q1 and the legal provision r. This refers to the weight of the legal authority(r), which is assigned a value based on the legal hierarchy to which the legal provision belongs. This represents the comprehensive reordering score of candidate legal provision r. After three layers of query rewriting and collaborative retrieval, the final output is the reordered set of legal provisions. m is the final number of legal provisions retained; Further optimization, setting , , .

6. The method for assisting in drafting judicial documents based on retrieval enhancement as described in claim 1, characterized in that, Constructing structured inputs; specifically including: After the aforementioned steps, a judicial summary is obtained. and the collection of legal provisions ; By designing regional prompt templates, judicial summaries, retrieved legal provisions, and original factual fragments are organized in a structured manner.

7. A method for assisting in drafting judicial documents based on retrieval enhancement as described in any one of claims 1-6, characterized in that, Segmented and controlled generation of judge's reasoning text; specifically including: Step 6.1: Generate the case nature determination; Step 6.2: Generate a dispute focus analysis; Step 6.3: Generate a legal application argument by combining the retrieved legal provisions; Step 6.4: Generate the judgment conclusion.

8. A computer device comprising a memory and a processor, wherein the memory stores a computer program, characterized in that, When the processor executes the computer program, it implements the steps of the above-described method for assisting in the drafting of judicial documents based on retrieval enhancement.

9. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by the processor, it implements the steps of the above-described method for assisting in the drafting of judicial documents based on retrieval enhancement.

10. A system for assisting in drafting judicial documents based on retrieval enhancement, characterized in that, include: The case fact structured segmentation and legal provision database construction module is configured to: receive the basic factual description, party information and disputed points of the case to be processed, perform semantic analysis and rule recognition, divide the content into three sub-modules: dispute type, litigation request and case facts, and at the same time, construct a vectorized legal provision retrieval database; The reasoning-oriented judicial summary generation module is configured to: model three types of sub-modules separately, introduce a sparse attention mechanism to suppress redundant narration for the case facts with low information density and a lot of redundancy, and then generate a unified judicial summary through multi-granularity feature fusion to form a concise and information-dense factual representation. The hierarchical query rewriting and retrieval expression generation module is configured to: rewrite the case cause layer, legal element layer, and standardized expression layer sequentially based on the judicial summary, forming a multi-granularity query expression from coarse to fine; The vectorized legal provision retrieval and reordering module is configured to: perform multi-level parallel retrieval in a pre-built legal provision vector retrieval library, and sort the relevant legal provisions by weight based on semantic similarity and the legal provision validity level, and output a set of relevant legal provisions. The structured input generation module is configured to organize judicial abstracts, retrieved legal provisions, and necessary original text fragments into a structured Prompt according to a preset template, clarifying the generation task and argumentation structure requirements. The segmented controlled generation module for judicial reasoning text is configured to: adopt a phased generation strategy to sequentially complete the determination of the nature of the case, the analysis of the points of contention, the argumentation of the application of law, and the expression of the judgment conclusion, and finally splice them together to form a complete reasoning text.