A legal intelligent question answering method based on retrieval-enhanced language model
The BiGRU-CNN model and vector retrieval technology with dynamic weight adjustment of self-attention, combined with the legal text database, solve the problem of insufficient knowledge timeliness and accuracy of language models in the legal field, and improve the answer quality and retrieval of legal intelligent question and answer efficiency.
Patent Information
- Application Number
- CN202410714259.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2024-06-04
- Publication Date
- 2024-10-01
- Estimated Expiration
- 2044-06-04
AI Technical Summary
In the existing technology, pre-trained or fine-tuned language models lack knowledge timeliness, accuracy, in-depth logic and professional insight capabilities in the legal field, resulting in the accuracy and reliability of legal intelligent question and answer answers being affected, and retrieval efficiency and precision are low. Not high, the ability to deal with complex problems is poor, and the recall effect is also poor.
The BiGRU-CNN question classification model based on dynamic weight adjustment self-attention is used to classify legal issues, combined with a large-scale legal text database for vector retrieval, and the answering ability of the language model is enhanced through transitional prompt templates and secondary iterative retrieval mechanisms. Improve retrieval efficiency and accuracy, and optimize the sorting of knowledge items.
It has significantly improved the knowledge timeliness, accuracy and professionalism of legal intelligent Q&A, improved retrieval efficiency and precision, and improved the ability to respond to complex issues and the quality of knowledge recall.
Smart Images

Figure CN118277538B_ABST
Abstract
Description
Technical Field
[0001] The present invention belongs to the field of computer technology, and in particular relates to a legal intelligent question-answering method based on a retrieval enhanced language model. Background Art
[0002] With the rapid development of artificial intelligence technologies such as deep learning and large-scale neural networks in recent years, especially the emergence of large language models, the ability of machine logical reasoning and learning has been greatly improved. Large language models have powerful language understanding and generation capabilities, can understand complex contextual information, and generate coherent, logical and rich and diverse texts. Through large-scale pre-training and fine-tuning, they can cope with various downstream tasks, such as legal question and answer, intelligent customer service, medical consulting, etc.
[0003] In actual tasks, pre-trained or fine-tuned language models may have problems such as insufficient knowledge timeliness and accuracy, lack of deep logic, and lack of deep insights into professional fields. When facing specific, professional, and unpopular legal issues, legal intelligent question answering based purely on pre-trained or fine-tuned language models may be affected in accuracy and reliability due to incomplete or outdated coverage of relevant legal knowledge in the training corpus. Therefore, it is necessary to combine a large-scale legal text database with a large language model to enhance the model's answering ability in real time by retrieving the most relevant legal clauses, precedents, and other information.
[0004] The current basic retrieval technology adopts a full database retrieval strategy for questions, does not classify questions, and does not finely divide the database, resulting in low retrieval efficiency and low retrieval accuracy. In addition, the current retrieval method mainly relies on calculating the similarity between the question vector and the database text vector to obtain the contextual knowledge required by the large model. This method does not fully consider the response needs of complex problems, resulting in low relevance between some questions and the retrieved knowledge. In addition, the current vector retrieval method has the problem of poor recall effect, that is, those knowledge items that are highly relevant to the question are often ranked relatively backward in the retrieval result list. Summary of the invention
[0005] In order to solve the shortcomings of the existing technology, improve the timeliness, accuracy, deep logic and professional insight of pre-trained or fine-tuned language models in the legal field, and improve the retrieval efficiency, retrieval accuracy, complex problem response ability and recall effect in the field of legal naive question and answer, the present invention adopts the following technical solutions:
[0006] A legal intelligent question answering method based on a retrieval enhanced language model comprises the following steps:
[0007] Step 1: Obtain legal texts of different categories to build a database and obtain vector databases of different categories;
[0008] Step 2: Obtain the legal question text and input it into the BiGRU-CNN problem classification model based on dynamic weight adjustment self-attention to obtain the corresponding categories; the categories include: marriage and family disputes, traffic accident disputes, labor disputes, personal injury compensation, work-related injuries and deaths, medical and aesthetic disputes, contract loan disputes, real estate rental and sale disputes, banking, finance and insurance, consumer shopping disputes, village and community neighborhood disputes, and other contradictions and disputes;
[0009] Step 3: Through the retrieval model, according to the category of the legal issue text, a set of matching legal knowledge is found from the vector database of the corresponding category, and then the legal knowledge is rearranged based on the correlation evaluation between the legal issue text and the legal knowledge;
[0010] Step 4: Integrate legal knowledge and legal issues to construct a transitional prompt template, input it into the large language model, and obtain a transitional answer;
[0011] Step 5: Input the transitional answer, the vector database constructed in step 1, and the question category obtained in step 2 into the retrieval model to obtain the legal knowledge after the second iteration. Integrate the legal knowledge and legal questions after the second iteration to construct the final prompt template, input it into the large language model, and obtain the final answer.
[0012] Furthermore, the construction of the database in step 1 includes the following steps:
[0013] Step 1.1: Obtain legal texts of different categories, including laws and regulations, judicial precedents, and legal questions and answers, and pre-process the original texts, including cleaning and removing irrelevant information such as headers and footers, advertisements, special symbols, etc. For question and answer data, filter out short and incoherent answers to ensure that only high-quality and meaningful texts are included;
[0014] Step 1.2: Segment the preprocessed long text into smaller units (such as paragraphs, sentences or clauses) for the subsequent creation of a vector database, which can reduce the computational cost of vectorization operations and improve the accuracy of vector retrieval.
[0015] Step 1.3: Use the pre-trained embedding model fine-tuned on legal texts to encode the segmented legal texts and convert them into high-dimensional feature vectors;
[0016] Step 1.4: Associate and map the encoded legal text vector with the original text, and use the vector retrieval tool faiss to build a vector index, through which the corresponding text can be recalled;
[0017] Step 1.5: Write the constructed vector index into the vector database to build vector databases of different categories of laws and regulations, legal cases, and legal questions and answers.
[0018] Furthermore, the pre-trained embedding model in step 1.3 uses bge-large-zh, and the fine-tuning data uses professional legal sentences and constructs sentence triple samples. The sentence triple samples contain a similar pair of professional legal sentences and a dissimilar sentence as a negative example control. The fine-tuning training process uses a triple loss function to calculate the distance between the positive and negative sentence sample pairs, and makes the feature distance of the positive sample pair smaller than the feature distance of the negative sample pair as much as possible. The calculation formula of the triple loss function is as follows:
[0019]
[0020] Among them, margin is a positive hyperparameter, which represents the distance threshold and is used to adjust the strictness of the fine-tuning training process. Represents the vector representation of the current sentence, Represents the sentence vector that is semantically similar to the current sentence, Represents a sentence vector that is semantically dissimilar to the current sentence. and Cosine distance ratio and When the cosine distance is smaller than the margin, the sentence sample is penalized. By optimizing the triple loss function, the embedding model's ability to learn the similarities and differences between samples can be improved, thereby improving the model's performance in dealing with semantic similarity and retrieval problems. When fine-tuning the embedding model, each round of training process inputs the sentence triple samples constructed from professional legal sentences into the embedding model, calculates the triple loss function, and uses the stochastic gradient descent SGD (Stochastic Gradient Descent) optimizer to update the model parameters. After the loss reaches convergence, the fine-tuned embedding model is saved.
[0021] Furthermore, the training of the question classification model in step 2 includes the following steps:
[0022] Step 2.1: Collect various legal issue texts and their corresponding category labels, remove duplicates, remove irrelevant information, fill in missing values, unify formats and vocabulary specifications, and divide the sorted data into training set, validation set and test set according to 7:1.5:1.5;
[0023] Step 2.2: Construct a BiGRU-CNN question classification model based on dynamic weight adjustment self-attention. The model models the global information of the legal question text through a bidirectional gated recurrent neural network, and adjusts the self-attention layer through dynamic weights. The deep global semantic features extracted further and the local features of the legal question text extracted by the convolutional neural network are input into the feature fusion layer together. The fused features are used by the classifier to predict the question category.
[0024] Step 2.3: Segment the legal question text, perform word embedding on the segmented text, represent each word in the natural language as a vector with unified meaning and unified dimension, and input the obtained word vector matrix into the convolutional network layer and the bidirectional gated recurrent neural network respectively. Calculate the model loss by calculating the gap between the predicted result and the actual result to obtain a trained question classification model.
[0025] Furthermore, in step 2.3, the convolutional neural network includes a convolutional layer and a maximum pooling layer. The convolutional layer performs a convolution operation on the acquired text features through a set of sliding windows of different sizes to learn the local features of the text. The calculation formula is as follows:
[0026]
[0027]
[0028] in, Represents word vector matrix The text feature vector obtained after the i-th row convolution operation, Represents word vector matrix The submatrix from row i to row i+k-1, represents the ReLU activation function, represents the bias vector, Represents word vector matrix The feature matrix composed of the text feature vectors in the i-th row, k represents the number of sliding windows, is the sequence length; the sliding step is 1;
[0029] The maximum pooling layer performs a pooling operation on the feature set output by the convolutional layer, retains the local key features in the text, discards irrelevant features, reduces the dimension of the feature vector, and prevents overfitting. The maximum pooling method is used to filter out a maximum eigenvalue from each sliding window. The calculation formula is as follows:
[0030] .
[0031] Furthermore, in step 2.3, the bidirectional gated recurrent neural network includes two sets of unidirectional gated recurrent units GRU in opposite directions. At each moment, two gated recurrent units GRU in opposite directions are provided for the input word vector matrix at the same time. The hidden layer state at the current moment t is determined by the current input , the input of the hidden state from time t-1 forward and the output of the reverse hidden state Jointly decide, through the forward hidden layer state and the reverse hidden state The weighted summation yields:
[0032]
[0033]
[0034]
[0035] in, represents the current input at time t, , They represent the forward hidden state of the gated recurrent unit GRU at time t. and the reverse hidden state The corresponding weight, represents the bias corresponding to the hidden layer state at time t, It represents the encoding operation performed by the gated recurrent unit GRU. Through the nonlinear transformation of the input word vector, the word vector is encoded into the corresponding gated recurrent unit GRU hidden layer state, and finally the global semantic feature G after data encoding is output.
[0036] Furthermore, in step 2.3, the global semantic feature G is input into the dynamic weight adjustment self-attention layer for feature enhancement, and the position weight parameter W is introduced based on the self-attention mechanism. weight , according to the training position of the text vector, the calculated self-attention weight probability value is redistributed, the weight of the text vector at the front training position is reduced and the weight of the text vector at the back training position is increased, so as to optimize the representation of the text feature vector and enhance the expressiveness of the text feature. The dynamic weight adjustment self-attention mechanism is implemented as follows:
[0037]
[0038]
[0039]
[0040] Among them, weight is a parameter iterator with an initial value of 1. During the training process, the overall self-attention weight of the front beginning feature is reduced through parameter iteration, so that the back features obtain higher weights. m represents the length of the text word; represents the n-dimensional global semantic feature vector output by the bidirectional gated recurrent neural network, Represents the adjustment factor of the function, usually the dimension of the input vector, for X·X T The inner product of is adjusted, and T represents the transpose of the matrix to avoid uneven distribution of results due to large differences in the values obtained by the function.
[0041] Furthermore, the step 3 comprises the following steps:
[0042] Step 3.1: Convert the legal issue text into a vector: Use the embedding model to map the legal issue text into a high-dimensional vector space to form a dense vector representation of a fixed length.
[0043] Step 3.2: Filter out the corresponding legal laws and regulations, legal cases and legal question-answer vector database according to the legal question category;
[0044] Step 3.3: Vectorize the legal problem The legal knowledge vector in the corresponding vector database , calculate the cosine similarity, and use the legal knowledge index with the largest dot product To achieve recall, a group of legal knowledge with the highest similarity is taken as the result of retrieval recall;
[0045] Step 3.4: Based on the BERT ranking model with adaptive edge ranking loss, the relevance score between the legal question query text and the legal knowledge is determined, thereby re-ranking and screening the legal knowledge.
[0046] Furthermore, in step 3.3, the cosine similarity formula is as follows:
[0047]
[0048]
[0049] Where dot_product(Q,D) represents the legal issue vector and legal knowledge vector The dot product of is the sum of the corresponding elements multiplied together. express The magnitude of the vector, express The magnitude of the vector, Represents the legal knowledge index with the largest dot product.
[0050] Furthermore, the sorting model in step 3.4 concatenates the legal issue query text and its corresponding positive text or negative text with the second special symbol, and adds the first and second special symbols at the beginning and end of the concatenated sentence, and the obtained positive and negative samples are used as training data, wherein the output corresponding to the position of the first special symbol is the semantic representation of the whole sentence; based on the concatenated sentence, a semantic vector is obtained through BERT encoding, and is mapped to a 1-dimensional scalar by a fully connected layer, and then the output is mapped to a range of 0 to 1 through a normalized sigmoid function, so as to determine the relevance score between the legal issue query text and the legal knowledge, thereby re-ranking the legal knowledge; in the model training process, the query and knowledge are fused to construct a binary classification task, i.e., predicting whether the relationship between the current query and the knowledge is 0 or 1, where 0 represents that the current query is irrelevant to the recalled knowledge, and 1 represents that the current query is completely relevant to the recalled knowledge, and an adaptive edge sorting loss function is used. To optimize:
[0051]
[0052] Among them, neg(i) represents the set of negative examples corresponding to the positive examples of sample i, margin j is the distance between the legal knowledge recalled and the legal question queried Determine the hyperparameters, for the positive sample pairs of the query And there are negative sample pairs corresponding to them They are compared one by one and then added together as the loss of the current query.
[0053] Furthermore, in step 4, the legal knowledge text and legal issues text Together as prompts, input into the large language model Generate transitional responses , transitional answer The generation formula is as follows:
[0054]
[0055] in, Indicates a prompt.
[0056] Furthermore, in step 5, in the initial iteration phase, only the legal issue text is relied upon. The knowledge base is searched. In the second iteration process, since the output of the large language model in the previous iteration can reveal relevant information that may be involved in answering the question, it can be used to bridge the semantic gap, that is, by using the output of the large language model in the previous iteration to retrieve legal knowledge, the relevance of the retrieved knowledge is improved. After the second iteration retrieval, the legal knowledge of the next iteration is obtained. The legal knowledge after the second iteration is used and legal issues text Together as prompts, input into the large language model Generate final answer , the final answer The generation formula is as follows:
[0057] .
[0058] The advantages and beneficial effects of the present invention are:
[0059] The present invention adds a retrieval mechanism based on a large language model and combines it with a large-scale legal knowledge base for retrieval enhancement, which can effectively improve the accuracy of answers and legal expertise. The present invention introduces a question classification and database refinement division mechanism, which pre-segments the database according to the type and attribute of the question, significantly improving the retrieval efficiency and the accuracy of the retrieval results; the present invention proposes a secondary iterative retrieval mechanism, which uses the output of the large language model in the first round of iteration to further retrieve legal knowledge and improve the relevance of the retrieved knowledge; the present invention also proposes a re-ranking filter that can effectively optimize the order of knowledge items related to the question in the retrieval result list, thereby improving the recall quality of legal knowledge. BRIEF DESCRIPTION OF THE DRAWINGS
[0060] Figure 1 is a flow chart of a method in an embodiment of the present invention.
[0061] Figure 2 It is a schematic diagram of the structure of the database building module in an embodiment of the present invention.
[0062] Figure 3 It is a schematic diagram of the structure of the question classification module in an embodiment of the present invention.
[0063] Figure 4 It is a schematic diagram of the structure of the retrieval module in an embodiment of the present invention. DETAILED DESCRIPTION
[0064] In order to better understand the purpose, structure and function of the present invention, the following is a further detailed description of a legal intelligent question answering method based on a retrieval enhanced language model of the present invention in conjunction with the accompanying drawings.
[0065] like Figure 1 As shown, a legal intelligent question answering method based on a retrieval enhanced language model of the present invention comprises the following steps:
[0066] Step 1: Obtain laws, regulations, cases, and question-and-answer documents, and input them into the database construction module to obtain a vector database. Figure 2 As shown, the construction of the database includes the following steps:
[0067] Step 1.1: Data preparation: In the embodiment of the present invention, 12 types of legal documents are collected, including laws and regulations, judicial precedents, and legal questions and answers. The original text is cleaned to remove irrelevant information such as headers and footers, advertisements, special symbols, etc. For question and answer data, short and incoherent answers are filtered out to ensure that only high-quality and meaningful texts are included.
[0068] Step 1.2: Document segmentation: The cleaned long legal documents are segmented into smaller units (such as paragraphs, sentences or clauses) for the subsequent creation of vector databases, which can reduce the computational cost of vectorization operations and improve the accuracy of vector retrieval. Legal documents are segmented according to clauses; judicial case documents are segmented according to case dispute focus and case analysis; legal Q&A documents are segmented according to questions and answers.
[0069] Step 1.3: Text encoding: Use the pre-trained embedding model fine-tuned on legal text to encode the segmented legal text and convert it into a high-dimensional feature vector.
[0070] The pre-trained embedding model uses bge-large-zh, and the fine-tuning data uses professional legal sentences and constructs sentence triple samples. The sentence triple samples contain a similar pair of professional legal sentences and a dissimilar sentence as a negative example. The fine-tuning training process uses the triple loss function to calculate the distance between the positive and negative sentence sample pairs, and try to make the feature distance of the positive sample pair smaller than the feature distance of the negative sample pair. The calculation formula of the triple loss function is as follows:
[0071]
[0072] Among them, margin is a positive hyperparameter used to adjust the strictness of the fine-tuning training process. is the vector representation of the current sentence, is the sentence vector that is semantically similar to the current sentence, is a sentence vector that is semantically dissimilar to the current sentence. and Cosine distance ratio and When the cosine distance is less than the threshold margin, the sentence sample is penalized. By optimizing the triple loss function, the embedding model's ability to learn the similarities and differences between samples can be improved, thereby improving the model's performance in dealing with semantic similarity and retrieval problems. When fine-tuning the embedding model, each round of training process inputs the sentence triple samples constructed from professional legal sentences into the embedding model, calculates the triple loss function, and uses the stochastic gradient descent SGD (Stochastic Gradient Descent) optimizer to update the model parameters. After the loss reaches convergence, the fine-tuned embedding model is saved.
[0073] Step 1.4: Create an index: By mapping the encoded legal text vector with the original text and using the vector retrieval tool faiss to build a vector index, the corresponding text can be recalled through the vector index.
[0074] Step 1.5: Create a vector database: Write the constructed vector index into the vector database and build a 12-category vector database of laws and regulations, legal cases, and legal questions and answers.
[0075] Step 2: Obtain the legal issue, input the legal issue text into the issue classification module, and use the BiGRU-CNN issue classification model based on dynamic weight adjustment self-attention to obtain the category information of the corresponding legal issue. Figure 3 As shown in the figure, the problem classification module refers to a problem classification model that can classify the input legal problems into categories, including: marriage and family disputes, traffic accident disputes, labor disputes, personal injury compensation, work-related injuries and deaths, medical and cosmetic disputes, contract loan disputes, real estate rental and sale disputes, banking, finance and insurance, consumer shopping disputes, village and community neighborhood disputes, and other contradictions and disputes. The training of the BiGRU-CNN problem classification model based on dynamic weight adjustment of self-attention includes the following steps:
[0076] Step 2.1: Data preparation: Collect various legal issues and their corresponding category labels from authoritative sources such as various legal consulting platforms. Perform operations such as deduplication, remove irrelevant information, fill missing values, unify format and vocabulary specifications on the collected data. Divide the sorted data into training set, validation set and test set according to the ratio of 7:1.5:1.5.
[0077] Step 2.2: Model network structure design: The BiGRU-CNN problem classification model based on dynamic weight adjustment self-attention integrates the deep learning architecture of convolutional neural network and bidirectional gated recurrent neural network. The convolutional neural network is used to extract the local features of legal issues, and the bidirectional gated recurrent neural network is used to model the global information of the legal issue text. The dynamic weight adjustment self-attention layer is used to further extract deep global semantic features.
[0078] Step 2.3: Use the word segmenter to segment the text and remove stop words to obtain the word segmentation results corresponding to the text to be classified. Perform word embedding operations on the text information after word segmentation, and represent each word in the natural language as a vector with unified meaning and unified dimension to obtain a word vector matrix.
[0079] The output word vector matrix is input into the convolution layer, where the local features of the text are learned by convolution operation on the text features using k sliding windows of different sizes. The calculation formula is as follows:
[0080]
[0081]
[0082] in, is the feature vector obtained after the convolution operation; is the characteristic matrix composed of eigenvectors; is the word vector matrix The submatrix from row i to row i+k-1; is the ReLU activation function; is the bias vector; is the sequence length; the sliding step is 1.
[0083] Then, the feature set output by the convolutional layer is pooled to retain the local key features in the text, discard irrelevant features, reduce the dimension of the feature vector, and prevent overfitting. The maximum pooling method is used to filter out a maximum eigenvalue from each sliding window. The calculation formula is as follows:
[0084]
[0085] The output word matrix is input into the bidirectional gated unit (BiGRU). BiGRU is a neural network model that consists of two unidirectional GRUs (gated recurrent units) in opposite directions. At each moment, the input will provide two GRUs in opposite directions at the same time, and the output is jointly determined by these two unidirectional GRUs.
[0086] The current hidden state of BiGRU is determined by the current input , the input of the hidden state at time (t-1) forward and the output of the reverse hidden state The three parts jointly determine that the hidden state of BiGRU at time t is determined by the forward hidden state and the reverse hidden state The weighted summation yields:
[0087]
[0088]
[0089]
[0090] in, , They represent the forward hidden layer state corresponding to the bidirectional GRU at time t. and the reverse hidden state The corresponding weight, represents the bias corresponding to the hidden layer state at time t, express The encoding operation of the encoder is a nonlinear transformation of the input word vector, encoding the word vector into the corresponding The hidden state outputs the global semantic feature G after data encoding through BiGRU.
[0091] The global semantic feature G is input into the dynamic weight adjustment self-attention layer for feature enhancement. Based on the self-attention mechanism, the position weight parameter weight is introduced for improvement. According to the position of the text vector training, the calculated self-attention weight probability value is redistributed, reducing the weight of the text vector at the front training position and increasing the weight of the text vector at the back training position, so as to optimize the representation of the text feature vector and enhance the expressiveness of the text feature. The dynamic weight adjustment self-attention mechanism is implemented as follows:
[0092]
[0093]
[0094]
[0095] Among them, weight is a parameter iterator with an initial value of 1. It will be continuously optimized during the training process, so as to reduce the overall weight of self-attention of the features at the beginning during training, and obtain higher weights for the features at the end; m is the length of the text word; is the n-dimensional vector output by BiGRU; is the adjustment factor of the function, usually representing the dimension of the input vector. The adjustment factor can be used to adjust X·X T The inner product of is adjusted to avoid the uneven distribution of results caused by too large a difference in the value obtained by the function. Dynamic weight adjustment outputs deep global semantic features from the attention layer.
[0096] Finally, the local feature S obtained by convolution pooling and the deep global semantic features obtained by the dynamic weight adjustment self-attention layer are combined and converted into category labels through the feature fusion layer. The Softmax classifier is used to calculate the probabilities of each category, and the category with the largest probability is taken as the prediction result.
[0097] The loss of the model network is calculated by calculating the gap between the predicted results and the actual results. If the network loss continues to decrease, the training process will continue until the preset number of iterations m is reached, thereby obtaining the final optimized model; if during the training process, the network loss tends to stabilize and no longer decreases significantly, the iteration is stopped and the model in the current state is used as the final result.
[0098] Step 3: Input legal issues, legal issue category information and vector database into the search module to obtain legal knowledge. Figure 4 As shown, the specific implementation of the retrieval module includes the following steps:
[0099] Step 3.1: Convert the legal issue text into a vector: Use the embedding model to map the legal issue text into a high-dimensional vector space to form a dense vector representation of a fixed length.
[0100] Step 3.2: Database screening: According to the legal issue category, the corresponding legal regulations, legal cases and legal question and answer vector databases are obtained.
[0101] Step 3.3: Calculate similarity and recall: through legal question vector and legal knowledge vector The cosine similarity is calculated to evaluate the matching degree between legal issues and legal knowledge. The calculation formula is as follows:
[0102]
[0103] in, Is a legal issue vector and legal knowledge vector The dot product of is the sum of the corresponding elements multiplied together; yes The magnitude of the vector, yes The magnitude of the vector.
[0104] The recall process is carried out through the collection of legal knowledge Find the legal problem vector The corresponding legal knowledge vector Legal knowledge index with the largest dot product To achieve this, the calculation formula is as follows:
[0105]
[0106] Legal Knowledge Index The legal knowledge text can be recalled, and finally the top-k1, top-k2, and top-k3 relevant laws and regulations, relevant cases, and related question-and-answer knowledge texts with the highest similarity are taken as the retrieval recall results.
[0107] Step 3.4: Rearrange and filter the legal and regulatory knowledge: Input the top-k1 legal and regulatory knowledge recalled in the previous step into the rearrangement filter to re-rank and filter the top-k1' legal and regulatory knowledge, thereby improving the accuracy of the retrieval results, where top-k1' < top-k1. The rearrangement filter uses the BERT ranking model based on the adaptive edge ranking loss, and concatenates the query and its corresponding positive or negative samples to construct training data as the pre-training model input. The specific construction process is as follows:
[0108] The query and its corresponding positive or negative sample are concatenated with the special symbol "[SEP]", and the special symbols "[CLS]" and "[SEP]" are added at the beginning and end of the concatenated sentence to obtain a positive or negative sample, where the output corresponding to the "[CLS]" position is the semantic representation of the entire sentence. The concatenated sentence is encoded by BERT to obtain a semantic vector and mapped to a one-dimensional scalar by the fully connected layer. The output is then mapped to a range of 0 to 1 through the sigmoid function, thereby realizing the relevance score determination between the query and the knowledge. During the model training process, the query and knowledge are fused to construct a binary classification task, that is, predicting whether the relationship between the current query and the knowledge is 0 or 1. 0 means that the current query is not related to the recalled knowledge, and 1 means that the current query is completely related to the recalled knowledge. Use the adaptive edge sorting loss function for optimization. The adaptive edge sorting loss function The formula is as follows:
[0109]
[0110] Among them, neg(i) represents the set of negative examples corresponding to the positive examples of sample i, margin j =αd j , is a hyperparameter, which is the distance between the recalled knowledge and the query , α represents the preset distance adjustment coefficient, and the formula means the positive sample pair of the query And there are negative sample pairs corresponding to them They are compared one by one and then added together as the loss of the current query.
[0111] Step 4: Integrate legal knowledge and legal issues to construct a prompt template, input it into the large language model, and obtain a transitional answer.
[0112] Specifically, the legal knowledge text and legal issues text Together as prompts, input into the large language model Generate transitional responses , where large language models use open source models such as Baichuan2, ChatGLM3, Qwen, etc., transitional answers The generation formula is as follows:
[0113]
[0114] in, Indicates a prompt.
[0115] Step 5: Perform a second iteration operation, input the transitional answer, the vector database constructed in step 1, and the question category obtained in step 2 into the retrieval module to obtain the legal knowledge after the second iteration. Integrate the legal knowledge and legal questions after the second iteration to construct a prompt template, and input it into the large language model to obtain the final answer.
[0116] Specifically, in the initial iteration phase, only the dependency problem The knowledge base is searched. In the second iteration process, since the output of the large language model in the previous iteration can reveal relevant information that may be involved in answering the question, it can be used to bridge the semantic gap, that is, by using the output of the large language model in the previous iteration to retrieve legal knowledge, the relevance of the retrieved knowledge is improved. After the second iteration retrieval, the legal knowledge after the second iteration is obtained.
[0117] Use the legal knowledge after the second iteration and legal texts Together as prompts, input into the large language model Generate final answer , the final answer The generation formula is as follows:
[0118] .
[0119] The above embodiments are only used to illustrate the technical solutions of the present invention, rather than to limit the same. Although the present invention has been described in detail with reference to the aforementioned embodiments, those skilled in the art should understand that the technical solutions described in the aforementioned embodiments may still be modified, or some or all of the technical features thereof may be replaced by equivalents. However, these modifications or replacements do not deviate the essence of the corresponding technical solutions from the scope of the technical solutions of the embodiments of the present invention.
Claims
1. A legal intelligent question answering method based on a retrieval-enhanced language model, characterized in that The steps include: Step 1: Obtain legal texts of different categories to build a database and obtain vector databases of different categories; Step 2: Obtain the legal question text and input it into the question classification model based on dynamic weight adjustment self-attention to obtain the corresponding category; the training of the question classification model includes the following steps: Step 2.1: Collect various legal issue texts and their corresponding category labels; Step 2.2: Construct a question classification model based on dynamic weight adjustment self-attention. The model models the global information of the legal question text through a bidirectional gated recurrent neural network, and adjusts the self-attention layer through dynamic weights. The deep global semantic features extracted further and the local features of the legal question text extracted by the convolutional neural network are input into the feature fusion layer together. The fused features are used by the classifier to predict the question category. Step 2.3: Segment the legal question text, perform word embedding on the segmented text, and input the obtained word vector matrix into the convolutional network layer and the bidirectional gated recurrent neural network respectively. Calculate the model loss by calculating the difference between the predicted result and the actual result to obtain the trained question classification model; In step 2.3, the global semantic features are input into the dynamic weight adjustment self-attention layer for feature enhancement, and the position weight parameter W is introduced based on the self-attention mechanism. weight , according to the position of text vector training, the calculated self-attention weight probability value is redistributed, the weight of the text vector at the front training position is reduced and the weight of the text vector at the back training position is increased. The dynamic weight adjustment self-attention mechanism implementation formula is as follows: Among them, weight is a parameter iterator. During the training process, the overall weight of the self-attention of the front feature is reduced through parameter iteration, so that the back feature obtains a higher weight. m represents the length of the text word; X represents the global semantic feature vector output by the bidirectional gated recurrent neural network. Represents the adjustment factor of the function, usually the dimension of the input vector, for X·X T The inner product is adjusted, and T represents the transpose of the matrix; Step 3: Through the retrieval model, according to the category of the legal issue text, a set of matching legal knowledge is found from the vector database of the corresponding category, and then the legal knowledge is rearranged based on the correlation evaluation between the legal issue text and the legal knowledge; In step 3, based on the ranking model with adaptive edge ranking loss, the relevance score between the legal question query text and the legal knowledge is determined, thereby re-ranking and screening the legal knowledge; The sorting model concatenates the legal question query text and its corresponding positive text or negative text with the second special symbol, and adds the first and second special symbols at the beginning and end of the concatenated sentence. The obtained positive and negative samples are used as training data, where the output corresponding to the position of the first special symbol is the semantic representation of the whole sentence; based on the concatenated sentence, a semantic vector is obtained after encoding, and is mapped to a scalar by a fully connected layer, and then normalized to determine the relevance score between the legal question query text and the legal knowledge, thereby re-ranking the legal knowledge; in the model training process, an adaptive edge sorting loss function L is used i To optimize: Among them, neg(i) represents the set of negative examples corresponding to the positive examples of sample i, margin j is the distance d between the recalled legal knowledge and the queried legal question j Determine the hyperparameters, for the positive sample pairs of the query and its corresponding negative sample pair They are compared one by one and then added up as the loss of the current query; Step 4: Integrate legal knowledge and legal issues to construct a transitional prompt template, input it into the large language model, and obtain a transitional answer; Step 5: Input the transitional answer, the vector database constructed in step 1, and the question category obtained in step 2 into the retrieval model to obtain iterated legal knowledge, integrate the iterative legal knowledge and legal questions to construct the final prompt template, input it into the large language model, and obtain the final answer.
2. According to claim 1, a legal intelligent question answering method based on a retrieval enhanced language model is characterized by: The construction of the database in step 1 includes the following steps: Step 1.1: Obtain different types of legal texts including laws and regulations, judicial precedents, and legal questions and answers, and pre-process the original texts; Step 1.2: Segment the preprocessed long text into sections, such as dividing the legal text into clauses, dividing the judicial precedent text into case dispute focus and case analysis, and dividing the legal question and answer text into questions and answers; Step 1.3: Use the pre-trained embedding model fine-tuned on legal texts to encode the segmented legal texts and convert them into high-dimensional feature vectors; Step 1.4: Associate and map the coded legal text vector with the original text, and use a vector retrieval tool to build a vector index; Step 1.5: Write the constructed vector index into the vector database to build vector databases of different categories of laws and regulations, legal cases, and legal questions and answers.
3. The legal intelligent question answering method based on retrieval enhanced language model according to claim 2, characterized in that: The pre-trained embedding model in step 1.3 is fine-tuned using professional legal sentences as data and constructing sentence triple samples. The sentence triple samples contain a similar pair of professional legal sentences and a dissimilar sentence as a negative example. The fine-tuning training process uses a triple loss function to calculate the distance between the positive and negative sentence sample pairs, and makes the feature distance of the positive sample pair smaller than the feature distance of the negative sample pair. The calculation formula of the triple loss function is as follows: L=max(margin+S·S + -S·S - ,0) Among them, margin is a positive hyperparameter, which represents the distance threshold and is used to adjust the strictness of the fine-tuning training process. S represents the vector representation of the current sentence, and S + Represents the sentence vector that is semantically similar to the current sentence, S - Represents a sentence vector that is semantically dissimilar to the current sentence. When S is equal to S - The cosine distance ratio S and S + When the cosine distance is smaller than margin, the sentence sample is penalized.
4. The legal intelligent question answering method based on retrieval enhanced language model according to claim 1, characterized in that: In step 2.3, the convolutional neural network includes a convolutional layer and a maximum pooling layer. The convolutional layer performs a convolution operation on the acquired text features through a set of sliding windows of different sizes to learn the local features of the text. The calculation formula is as follows: C i =f(w×D i:i+k-1 +b), P i =[C1,C2,...,C L-k+1 ], Among them, C i Denotes the text feature vector obtained after the convolution operation on the i-th row of the word vector matrix D, D i:i+k-1 represents the submatrix of the word vector matrix D from the i-th row to the i+k-1th row, f represents the activation function, b represents the bias vector, P i represents the feature matrix composed of the text feature vectors in the i-th row of the word vector matrix D, k represents the number of sliding windows, L is the sequence length; the sliding step size is 1; The maximum pooling layer performs a pooling operation on the feature set output by the convolutional layer, retains the local key features in the text, and uses the maximum pooling method to filter out a maximum eigenvalue from each sliding window. The calculation formula is as follows: S=max{P i }。 5. The legal intelligent question answering method based on retrieval enhanced language model according to claim 1, characterized in that: In step 2.3, the bidirectional gated recurrent neural network includes two sets of unidirectional gated recurrent units with opposite directions. At each moment, two gated recurrent units with opposite directions are provided for the input word vector matrix at the same time. The hidden state at the current moment t is determined by the current input x t , the forward hidden state and the reverse hidden state Jointly decide, through the forward hidden layer state and the reverse hidden state The weighted summation yields: Among them, x t represents the current input at time t, w t 、v t Represent the forward hidden state of the gated recurrent unit at time t and the reverse hidden state The corresponding weight, b t It represents the bias corresponding to the hidden state at time t. GRU() represents the encoding operation performed by the gated recurrent unit. Through the nonlinear transformation of the input word vector, the word vector is encoded into the corresponding gated recurrent unit hidden state, and finally the global semantic features after data encoding are output.
6. The legal intelligent question answering method based on retrieval enhanced language model according to claim 1, characterized in that: The step 3 comprises the following steps: Step 3.1: Convert legal question text into vectors; Step 3.2: Filter out the vector database of the corresponding category according to the legal issue category; Step 3.3: Calculate the cosine similarity between the legal question vector Q and the legal knowledge vector D in the corresponding vector database, and use the legal knowledge index i with the largest dot product to achieve recall, and take the set of legal knowledge with the highest similarity as the result of retrieval and recall; Step 3.4: Based on the ranking model with adaptive edge ranking loss, the relevance score between the legal question query text and the legal knowledge is determined, thereby re-ranking and screening the legal knowledge.
7. The legal intelligent question answering method based on retrieval enhanced language model according to claim 6, characterized in that: In step 3.3, the cosine similarity formula is as follows: Among them, dot_product(Q, D) represents the dot product of the legal issue vector Q and the legal knowledge vector D, ||Q|| represents the modulus of the Q vector, ||D|| represents the modulus of the D vector, and i represents the legal knowledge index with the largest dot product.
