A two-stage legal search method based on intent routing
By employing intent routing and a two-stage retrieval method, the system addresses the issues of scenario adaptability and long document processing in existing legal research systems, thereby improving retrieval accuracy and output quality and generating high-quality legal analysis documents.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- SHANGHAI ZHIHE NETWORK TECH CO LTD
- Filing Date
- 2026-06-16
- Publication Date
- 2026-07-21
AI Technical Summary
Existing legal information retrieval and intelligent question-answering systems suffer from problems such as legal provision illusion, case illusion, unreasonable resource allocation, insufficient semantic perception segmentation, lack of deduplication mechanism for redundant entries, and poor scenario adaptability when dealing with complex legal issues.
A two-stage legal retrieval method based on intent routing is adopted. The query intent is classified through a large language model, and the document is segmented and the summary is compressed. Combined with structured search parameters and vector search, content fingerprint deduplication and double byte reduction are performed to generate scenario-specific analysis documents.
It achieves scenario adaptation for legal research, long document processing, improved retrieval accuracy, and context control, and outputs high-quality formatted analysis documents.
Smart Images

Figure CN122432301A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of artificial intelligence technology, and specifically to a two-stage legal retrieval method based on intent routing. Background Technology
[0002] In existing legal information retrieval and intelligent question-answering technology systems, researchers have attempted to combine large language models with retrieval-enhanced generation techniques to improve the automation level of legal research. Traditional legal retrieval systems typically employ keyword matching or Boolean logic queries, requiring users to construct query expressions and manually filter relevant content from the returned document list. This approach demands high levels of user expertise and struggles to handle complex legal issues expressed in natural language. In recent years, end-to-end question-answering solutions based on large language models have been proposed. These solutions directly input user questions into the large language model, relying on the model's internal knowledge to generate answers. However, due to the frequent updates and highly specialized nature of legal knowledge, a single model is prone to legal or case-based illusions, resulting in answers lacking authoritative basis. Another approach employs a vector-based retrieval-enhanced language model architecture. This involves first recalling relevant legal text fragments through vector similarity, then concatenating them with the user question before inputting them into the large language model to generate the answer. However, these solutions still have several shortcomings in practice: most solutions do not perform semantically aware segmentation and compression processing on user-uploaded legal documents (such as contracts and draft judgments), and long files are prone to exceeding the model's context window when directly input; the candidate items recalled by vector retrieval contain a large amount of low-relevance content, lacking refined relevance judgment for each candidate item; redundant items between different recall sources (laws, cases, practical articles) lack an effective deduplication mechanism; in addition, existing solutions usually do not differentiate retrieval parameters, context budgets, and generated templates according to the user's intent type (such as case analysis, document drafting, legal query, etc.), resulting in unreasonable resource allocation and a single output format. Therefore, a legal research intelligent agent workflow method is needed that can comprehensively handle intent routing, adaptive file compression, two-stage retrieval filtering, content fingerprint deduplication, and differentiated generation to systematically solve the above-mentioned technical problems. Summary of the Invention
[0003] To comprehensively handle intent routing, adaptive file compression, two-stage retrieval filtering, content fingerprint deduplication, and differentiated generation of legal research workflows, this invention proposes a two-stage legal retrieval method based on intent routing, including the following steps:
[0004] S1: Receive query instructions and a list of associated file contents sent by the terminal device;
[0005] S2: Call the large language model to classify the query command according to the preset mutually exclusive intent classification template, and output the type code that is uniquely selected from multiple preset type codes;
[0006] S3: When the file content list is not empty, perform semantic segmentation and two-level summary compression on the file, extract the summary information containing multiple preset structured fields as the file processing result; otherwise, skip.
[0007] S4: Based on the type code, call the large language model to transform the query instructions and document processing results into a structured set of search parameters that includes at least an array of core questions, a legal retrieval vector, and a case retrieval vector;
[0008] S5: Based on the structured retrieval parameter set, the corresponding vector retrieval interface is called concurrently to obtain the initial knowledge entries. Then, the filtering large language model is called concurrently to output a Boolean relevance judgment for each initial knowledge entry. Only the entries that are judged to be true are retained. Finally, the retained entries are deduplicated by content fingerprint and double byte budget reduction to obtain the final retrieval results.
[0009] S6: Apply differential character limit reduction to the final search results based on the scenario-specific type corresponding to the type code;
[0010] S7: Based on the type code, call the corresponding scenario-specific large language model, take the truncated final search results, query instructions and file processing results as input, generate a formatted analysis document and output it.
[0011] Furthermore, in step S2, the mutually exclusive intent classification template imposes the following constraints on the large language model:
[0012] (a) The response format is set to a JSON object containing a type code, confidence level, classification reason, and explanation of ambiguity;
[0013] (b) When the query command contains position keywords, the large language model outputs the corresponding case analysis type code, without considering other classifications;
[0014] (c) For query instructions that do not contain the position keywords in (b), the large language model determines whether the answer to the query instruction differs due to different parties or case facts: if the answer is yes, the case analysis type code is output; if the answer is no, the comprehensive legal issue research type code is output.
[0015] (d) When the query command references the file content but the file content list is empty or the file text cannot be obtained, the large language model determines the output based on the preset mapping table between query command keywords and type codes.
[0016] Furthermore, in step S3, the extracted data includes at least the following preset structured fields: file name, parties involved, key time points, core rights and obligations, disputed clauses or risk points, content directly related to user issues, and summary.
[0017] Furthermore, in step S3, the semantic segmentation and two-level summary compression based on semantic segmentation points specifically includes the following steps:
[0018] Iterate through the list of file contents and sum the character count for each file to get the total number of characters in the entire file;
[0019] When the total number of characters in the entire file does not exceed the preset first character threshold, the entire file will be encapsulated into a list of pass-through entries and output directly.
[0020] When the total number of characters exceeds the preset first character threshold, a semantic cutting point search is performed on files whose single file character count exceeds the upper limit of the block character count: starting from the file character position corresponding to the upper limit of the block character count, the search is performed forward within the preset search range, prioritizing the position of two consecutive newline characters as semantic cutting points, and then searching the position of a single newline character. If neither exists, the file character is directly truncated at the file character position corresponding to the upper limit of the block character count.
[0021] The file is divided into multiple blocks based on semantic segmentation points, and each block is appended with a context header field;
[0022] The large language model is invoked using an asynchronous multi-threaded concurrent call mechanism, and the corresponding preset structured fields are extracted for each block.
[0023] When the cumulative number of characters in the summary exceeds the preset second character threshold, the large language model is called again to integrate and deduplicate the summary according to the preset structured fields.
[0024] Furthermore, in step S4, the structured retrieval parameter set also includes a clause specification field and a validity level field. When generating the structured retrieval parameter set, the large language model is subject to at least one of the following normalization constraints:
[0025] (a) The core issue array is in the form of declarative sentences. The length of a single sentence is constrained by a preset character limit. The array length is not less than the preset number and each sentence covers mutually exclusive legal dimensions.
[0026] (b) The legal retrieval vector shall adopt a standard sentence structure that includes the legal subject, applicable conditions and legal consequences, and must include legal effect indicator words of the pre-defined categories;
[0027] (c) The case retrieval vector adopts a narrative structure that includes information about the parties involved, the disputed acts, the claims of each party, and the focus of the dispute. The length of a single entry is constrained by a preset minimum character limit.
[0028] (d) The clause specification field adopts the preset clause numbering format;
[0029] (e) To implement the mapping conversion of the abbreviation of regulations to the official name, and to replace old laws that have been superseded by subsequent laws;
[0030] (f) The effectiveness level field outputs the corresponding preset code group based on the query content.
[0031] Furthermore, in step S5, concurrently calling the corresponding vector retrieval interface to obtain initial knowledge entries specifically includes:
[0032] An asynchronous multi-threaded concurrent call mechanism with preset batch size and preset concurrent execution number as upper limits sends retrieval requests to the legal vector retrieval interface and the case vector retrieval interface respectively;
[0033] The input parameters for each retrieval request include at least the corresponding retrieval vector extracted from the structured retrieval parameter set. For the case vector retrieval interface, the input parameters also include the minimum similarity threshold, the upper limit of the number of recalls per time, and at least one retrieval scope limitation parameter.
[0034] Receive the list of entries returned by each vector retrieval interface, and merge the list of entries as the initial knowledge entries.
[0035] Furthermore, in step S5, the concurrent invocation of the filtering large language model to output a Boolean relevance judgment for each initial knowledge item specifically includes:
[0036] The initial knowledge items are divided into multiple batches, with the maximum number of items in each batch falling within a preset range;
[0037] For each batch, an asynchronous multi-threaded concurrent call mechanism with a preset concurrent execution limit is used to combine the query command and each knowledge item in the current batch with a preset relevance judgment prompt template to generate multiple independent prompt inputs, and call the filtering large language model respectively.
[0038] The system receives a JSON object returned by the filtering large language model for each knowledge entry, extracts a Boolean value from it, and associates and stores the Boolean value with the corresponding knowledge entry as the result of the Boolean relevance judgment.
[0039] Furthermore, in step S5, the content fingerprint deduplication and double-byte budget reduction of the retained entries specifically include:
[0040] Obtain the list of entries retained after Boolean correlation judgment as the entries to be processed;
[0041] Define an exclusion field set, which includes at least a document type field, a referee date field, and a subtitle field;
[0042] For each entry in the list of entries to be processed, remove the fields that belong to the exclusion field set to obtain the filtered entries;
[0043] When the filtered entries contain a summary field that is a string, the summary field will be truncated to the preset character length limit.
[0044] After sorting the key names of each field in the filtered entries into lexicographical order, serialize them into a normalized JSON string, and use this normalized JSON string as the content fingerprint;
[0045] Determine whether the content fingerprint of the current filtered entry is the same as the content fingerprint of the already retained filtered entries: if they are different, retain the current filtered entry and record its content fingerprint; if they are the same, discard the current filtered entry.
[0046] The retained filtered entries are added to the output list in order, and the estimated byte occupancy of the current filtered entry is accumulated to the cumulative byte count. When the cumulative byte count exceeds the preset soft byte upper limit threshold, the addition of new filtered entries to the output list is stopped.
[0047] The output list is serialized into a JSON string and its actual number of bytes after UTF-8 encoding is calculated. If the actual number of bytes exceeds the preset hard byte limit threshold, the filtered entries are deleted one by one from the end of the output list until the actual number of bytes is lower than the hard byte limit threshold.
[0048] Compared with the prior art, the present invention has at least the following beneficial effects:
[0049] (1) The present invention proposes a two-stage legal retrieval method based on intent routing, which classifies query instructions into mutually exclusive categories through intent routing, so that the subsequent generation of retrieval parameters and generation model invocation can be accurately matched with the specific scenario of legal research.
[0050] (2) For long legal documents, semantic segmentation and two-level summary compression are adopted to effectively control the input length while retaining key information;
[0051] (3) By using a large language model, natural language queries are converted into structured parameters containing arrays of core questions, legal and case retrieval vectors, thereby improving the semantic matching quality of the retrieval;
[0052] (4) In the two-stage retrieval, vector retrieval is used first to ensure the breadth of recall, and then a screening-type large language model is used to output a Boolean relevance judgment for each candidate item, thereby filtering out a large number of irrelevant items at a lower cost and reducing the input noise of the downstream generation model.
[0053] (5) By deduplication of content fingerprint and byte budget pruning of both hardware and software, redundant entries occupy the context window and fundamentally eliminate the risk of context overflow. Combined with intent type, a differentiated character limit is applied to the search results, and a scenario-specific generation model is called to output formatted documents, so that different legal tasks can obtain appropriate response length and professional expression. Attached Figure Description
[0054] Figure 1 This is a flowchart illustrating the steps of a two-stage legal retrieval method based on intent routing.
[0055] Figure 2 This is a schematic diagram illustrating the information flow of the two-stage legal search function module. Detailed Implementation
[0056] The following are specific embodiments of the present invention, which are described in conjunction with the accompanying drawings. However, the present invention is not limited to these embodiments.
[0057] In existing legal information retrieval and intelligent question-answering technologies, mainstream methods can be categorized into three types. The first type is a single large language model end-to-end question-answering system. This type of method directly relies on the parameterized knowledge within the model to generate answers, lacking the ability to retrieve massive authoritative legal and judicial case databases in real time. It is prone to legal and case illusions and cannot distinguish between differentiated needs such as "searching for legal provisions," "finding cases," and "drafting documents." The second type is a vector-based legal retrieval augmented generation (RAG) system. This method encodes regulations and cases into vectors and creates an index. During a query, it performs an approximate vector retrieval and then concatenates the context before inputting it into the large language model. However, in this type of solution, the candidate items recalled by vector retrieval contain a large amount of low-relevance noise and lack refined relevance judgment for each item. Furthermore, there is a lack of content fingerprint-level deduplication mechanisms between multiple recall paths (regulations + cases + practices), resulting in redundant items repeatedly occupying the context window. The length of the concatenated context easily exceeds the model's limitations, and there is a lack of effective byte budget reduction mechanisms. The third type is rule-based legal assistants. These rules are rigid and unable to handle ambiguous expressions in natural language. Furthermore, they often use hard segmentation for long legal documents, disrupting the semantic integrity of legal provisions and paragraphs. Therefore, existing technologies still have significant shortcomings in handling multi-intent scenario adaptation, semantically aware segmentation of long documents, secondary filtering of search results, and precise control of contextual bytes. To address these issues, such as... Figure 1 As shown, this invention proposes a two-stage legal retrieval method based on intent routing, including the following steps:
[0058] S1: Receive query instructions and a list of associated file contents sent by the terminal device;
[0059] S2: Call the large language model to classify the query command according to the preset mutually exclusive intent classification template, and output the type code that is uniquely selected from multiple preset type codes;
[0060] S3: When the file content list is not empty, perform semantic segmentation and two-level summary compression on the file, extract the summary information containing multiple preset structured fields as the file processing result; otherwise, skip.
[0061] S4: Based on the type code, call the large language model to transform the query instructions and document processing results into a structured set of search parameters that includes at least an array of core questions, a legal retrieval vector, and a case retrieval vector;
[0062] S5: Based on the structured retrieval parameter set, the corresponding vector retrieval interface is called concurrently to obtain the initial knowledge entries. Then, the filtering large language model is called concurrently to output a Boolean relevance judgment for each initial knowledge entry. Only the entries that are judged to be true are retained. Finally, the retained entries are deduplicated by content fingerprint and double byte budget reduction to obtain the final retrieval results.
[0063] S6: Apply differential character limit reduction to the final search results based on the scenario-specific type corresponding to the type code;
[0064] S7: Based on the type code, call the corresponding scenario-specific large language model, take the truncated final search results, query instructions and file processing results as input, generate a formatted analysis document and output it.
[0065] In this embodiment, the method proposed in this invention is deployed in an intelligent agent workflow system executed by a server-side data processing engine. This system is deployed on a cloud server and communicates with terminal devices (such as personal computers, tablets, or smartphones used by lawyers) through a standardized application programming interface. The terminal devices run dedicated client applications or web applications, through which users input query commands in natural language and can upload one or more documents related to the legal research task, such as draft contracts, complaints, scanned copies of judgments, or case fact description documents provided by clients. Upon receiving this data, the server initiates the entire legal research intelligent agent workflow.
[0066] The user first enters a query command on their terminal device. In one example case, a lawyer handling commercial disputes needs to investigate whether the original shareholders are still liable for supplementary compensation for company debts incurred before the transfer after the equity transfer, and simultaneously uploads a copy of the target company's "Capital Increase and Share Expansion Agreement" document. The query command data received by the server is a piece of natural language text: "Whether the original shareholders are still liable for supplementary compensation for company debts incurred before the transfer after the equity transfer," and the associated file content list contains a record whose "filename field" is "Capital Increase and Share Expansion Agreement_v2.docx," and whose "file body field" is the plain text content extracted from that document.
[0067] like Figure 2 As shown, after receiving the above data, the system first activates the intent recognition engine. This engine is configured to call a large language model, typically a model with moderate parameters and fast inference speed, and is equipped with a designed system prompt word. This prompt word forces the large language model to classify the user's query according to a mutually exclusive seven-category classification template. These seven type codes are: TYPE_1 (Case Analysis and Litigation Strategy), TYPE_2 (Document Drafting), TYPE_3 (Legal and Regulatory Inquiry), TYPE_4 (Case Retrieval), TYPE_5 (Document Review and Compliance Audit), TYPE_6 (Comprehensive Research on Legal Issues), and TYPE_7 (Invalid / Out-of-Range Input). To ensure the determinism of the output, the model is required to return the results in a strict JSON format. This JSON object must contain at least four fields: "type" (type code), "confidence," "reason" (classification reason), and "ambiguity." The "type" field is the type code uniquely selected from the above seven classification templates.
[0068] When the intent recognition model receives a query asking "After the equity transfer, are the original shareholders still liable for supplementary compensation for the company's debts incurred before the transfer?", it performs internal reasoning. First, it checks if the query contains typical litigation stance keywords such as "our side," "the other party," "plaintiff," "defendant," "victory," and "how to respond." This case's query does not contain such terms, therefore it is not directly directed to TYPE_1. Next, the model assesses whether the query falls under the "general applicability test" rule: that is, whether the answer to the question differs depending on the parties or the facts of the case. For the question of "original shareholders' supplementary compensation liability," different courts may have differing rulings under different case facts, and the answer is not consistent for everyone. Therefore, this query is judged as "the answer varies from person to person and case to case," and thus classified as TYPE_1 (case analysis and litigation strategy). Simultaneously, since the user uploaded a "Capital Increase and Share Expansion Agreement" document, and the query content may be related to this document (the agreement may involve equity transfer clauses), the intent recognition engine will also briefly indicate the classification basis in the "reason" field and record unambiguity in the "ambiguity" field. The final output type code is "TYPE_1".
[0069] After obtaining the type code, the system enters a conditional decision node, which determines whether to execute the file processing branch based on whether the file content list is empty. In this example, the user uploaded a "Capital Increase and Share Expansion Agreement" file, and the file content list is not empty, so the file processing engine is activated. The file processing engine first traverses the file content list, accumulating the character count of each file. Assume that the plain text content of the "Capital Increase and Share Expansion Agreement," after preprocessing, has a total character count of 180,000, while the system's preset pass-through budget (i.e., the preset first character count threshold) is 50,000 characters. Since 180,000 characters far exceeds 50,000, the system will not directly encapsulate and output the file, but instead enters the digest compression path. At this point, the system checks whether the character count of a single file exceeds the block character limit. Here, the preset block character limit (i.e., the maximum number of characters in a single block) is 50,000 characters. Since the file has 180,000 characters, exceeding the 50,000-character limit, a semantic segmentation point search needs to be performed on the file.
[0070] The semantic cut-point search function is invoked. This function takes the full text of the file and a series of target cut positions as input. For example, to divide a 180,000-word file into multiple blocks of approximately 50,000 words each, the first target cut position is around the 50,000th character. The search function does not truncate directly at the exact 50,000th character, but instead searches for the optimal semantic breakpoint around that position within a predefined search range (e.g., searching forward 500 characters). It prioritizes searching for the position of two consecutive newline characters "\n\n", as this usually represents the end of a paragraph; if not found, it searches for the position of a single newline character "\n"; only if even a single newline character is not found does it degenerate into truncating directly at the target cut position. This mechanism maximizes the semantic integrity of each block, avoiding splitting a legal provision or a complete factual argument in half. After searching, the first block is determined after a double newline character at character 50200; the second block starts searching for the next cut point from character 50201, and so on. Ultimately, the 180,000-word "Capital Increase and Share Expansion Agreement" was divided into four blocks (some blocks may be slightly smaller than the upper limit). Each block was appended with a context header field, in the form of "File name: Capital Increase and Share Expansion Agreement_v2.docx, Block N / 4 of 4, Total characters in the original text: 180,000", so that the subsequent model could understand the relative position and ownership of the block in the original file when generating the summary.
[0071] Next, the system initiates the batch summarization phase. The file processing engine employs an asynchronous multi-threaded concurrent call mechanism, with specific parameters including a maximum batch size of 200 and a maximum number of concurrent executions of 10. This means the system will simultaneously send up to 10 requests to the large language model, with each request processing one chunk (or a batch of chunks, but typically each request processes one chunk to ensure summarization quality). Guided by prompts, the large language model is required to extract seven pre-defined structured fields from each chunk: filename, parties involved, key time points, core rights and obligations, disputed clauses or risk points, content directly related to the user's question, and a comprehensive summary. This structured information is encapsulated as a JSON object and returned.
[0072] Once all chunk summaries are generated, the system merges all summary texts and sums their total character count. Assume the summaries from the four chunks total 90,000 characters, while the system's preset secondary compression budget (i.e., the preset second character count threshold) is 80,000 characters. Since 90,000 exceeds 80,000, the system determines that secondary compression needs to be triggered. Therefore, the large language model is invoked again. The model's prompts require it to integrate, deduplicate, and eliminate redundancy from multiple summaries according to a more refined five-element structure—parties involved, key time points, core rights and obligations, disputed clauses or risk points, and content directly related to the user's question—while retaining as much information as possible directly related to the user's query (the original shareholder's supplementary compensation liability). After secondary compression, a final summary text with a length not exceeding the budget is output and passed to the downstream as the file processing result. If the cumulative summaries do not exceed the secondary compression budget, they are directly merged and output without invoking the large language model again.
[0073] After the document processing engine completes its work, the retrieval element generation engine begins operation. Based on the intent recognition output type code "TYPE_1", this engine routes to a structured extraction template specifically designed for the "case analysis and litigation strategy" scenario. This template contains a series of cue word constraints, requiring the large language model to extract a set of structured retrieval parameters from the user's query and the document processing results (i.e., the summary obtained in the previous step). The output structured retrieval parameter set contains at least three core parts: a core question array, a legal retrieval vector (lvector), and a case retrieval vector (cvector). Additionally, it may include article numbers, filtering fields (such as court location, judgment date range), and effectiveness level codes. The large language model is subject to strict normalization constraints.
[0074] For example, the core question array (core_question) must be output in declarative sentence form, with each question not exceeding 50 characters in length, and the array length must be no less than 3 and no more than 5 questions, with different questions covering mutually exclusive legal dimensions. For this case, the generated core_question might be: [“What are the constituent elements of the original shareholder's supplementary liability for the company's debts before the transfer of equity?”, “What are the common circumstances under which the original shareholder is exempted from liability in judicial practice?”, “Has the liability of the original shareholder changed under the new Company Law?”]. The legal retrieval vector (lvector) is required to use the standardized sentence structure of “subject + condition or circumstance + legal effect,” with a length of no less than 15 characters. It must contain at least one legal effect word from “must not,” “shall,” “has the right,” and “deemed”, and is prohibited from containing specific law names and article numbers. The system might generate an lvector as: “The original shareholder after the equity transfer shall bear supplementary liability to the company's creditors if he / she fails to fulfill his / her capital contribution obligations or fails to make effective arrangements for the debts before the transfer.” The case retrieval vector (cvector) is required to adopt a narrative structure of "basic information of the parties → core disputed behavior → claims of each party → focus of the dispute," with a length of no less than 100 words, presented in the form of declarative sentences. For example: "Company A's original shareholder A transferred all of its shares to B. Later, the company's creditor C claimed that A should bear supplementary compensation liability for a loan of 2 million yuan incurred before the transfer. A claimed that it had fully contributed its capital and that the transfer agreement stipulated that the debt should be borne by B. The focus of the dispute is whether the internal provisions of the share transfer agreement can prevail against external creditors, and whether the original shareholder's liability is premised on the failure to fulfill its capital contribution obligation."
[0075] After the element generation engine completes its output, the two-stage retrieval engine begins executing the four-stage retrieval pipeline.
[0076] The first stage is vector retrieval batch processing. The system encapsulates the legal and case retrieval vectors generated in the previous step into JSON requests, employing an asynchronous multi-threaded concurrent call mechanism (batch size capped at 100, concurrent execution capped at 10), and simultaneously sends requests to external legal and case vector retrieval plugins. The legal vector retrieval plugin connects to a vector database containing current laws, regulations, judicial interpretations, departmental rules, and other legal documents, while the case vector retrieval plugin connects to a vector database containing a massive amount of judgment documents. The parameters for each retrieval request also include a minimum similarity threshold (e.g., 0.65), a maximum number of items recalled per request (e.g., 50 each), and optional filtering conditions (e.g., limiting the court level to "Supreme Court" or "High Court," and limiting the judgment date to the last five years). In this case, the system recalls 50 legal candidate entries and 50 case candidate entries respectively, merging them to obtain 100 initial knowledge entries.
[0077] The second stage is the relevance assessment batch processing. The system divides the initial 100 knowledge entries acquired in the first stage into multiple batches, each batch consisting of 100 to 200 entries (since the total number is only 100, it can be considered as one batch). Then, using an asynchronous multi-threaded call mechanism with a maximum concurrent execution count of 10, a filtering large language model is invoked. The model's temperature parameter is set to 0.4 (low randomness), the topP parameter is set to 0.7, the maximum output token is 4096, and the response format is forcibly set to a JSON object containing the boolean field "is_relevant". The system constructs an independent prompt for each knowledge entry, containing the user's original query command and the text content (or summary) of the entry, requiring the model to determine whether the entry can analyze legal research tasks from a certain perspective. The model outputs for each entry, for example, {"is_relevant": true} or {"is_relevant": false}. Of the 100 items recalled, only about 30 may be deemed true (for example, cases and legal provisions that discuss the supplementary liability of the original shareholders, withdrawal of capital, and the validity of equity transfer agreements are deemed relevant; while items that discuss completely unrelated patent infringement or labor disputes are deemed irrelevant).
[0078] The third stage is Boolean filtering. The system uses a simple code node to traverse all initial knowledge entries, appending the Boolean values from the second stage output as annotation fields to each entry object, and then using list comprehensions to retain only those entries whose annotation fields are true. After this step, 100 entries are reduced to 30, and noise is significantly eliminated.
[0079] The fourth stage involves merging, deduplication, and double-byte budget reduction. The system first retrieves the 30 items to be retained. A set of exclusion fields is defined, such as excluding fields that are volatile or do not affect the core content, like "document_type," "judgment_date," and "sub_title." For each item, after removing these fields, if the item contains a "summary" field that is a string, it is truncated to under 500 characters. Then, the fields in the filtered items are sorted lexicographically by key name (e.g., "court_level" first, "id" last), and serialized into a normalized JSON string. This string serves as the content fingerprint of the item. The system maintains a set of seen fingerprints. For each of the 30 items, its content fingerprint is calculated. If the fingerprint is not in the seen set, the item is retained and its fingerprint is added to the set; otherwise, it is discarded. This deduplication method is more thorough than simply deduplicating based on entry ID because it can identify duplicate entries with identical content but slightly different metadata (such as the same judgment in different databases). Assuming 5 out of 30 entries are duplicates, after deduplication, 25 remain.
[0080] Subsequently, the system performs soft-byte budget reduction. A preset soft-byte limit is established (e.g., 1.5 million bytes, approximately 1.5MB). The system sequentially iterates through the 25 deduplicated entries, accumulating the byte size of each entry after the above filtering and truncation (obtained by calculating the UTF-8 encoded length of its normalized JSON string). When the cumulative byte size exceeds 1.5 million bytes, the system immediately stops adding new entries, even if there are still unprocessed entries. Assuming the first 15 entries have accumulated 1.5 million bytes, only these 15 entries are retained, and the last 10 are discarded. Finally, the system serializes the list of these 15 entries into a complete JSON string and calculates the actual UTF-8 encoded byte size of the string. If this actual byte size exceeds a preset hard-byte limit (e.g., 1.8 million bytes), the system deletes entries one by one from the end of the list until the actual byte size is below the hard limit. After this double reduction, the final output search result may be reduced to 13 or 14 entries, ensuring that the context window limit is never exceeded during the subsequent LLM generation stage.
[0081] After obtaining the final search result list after two stages of retrieval and pruning, the system enters the character budget control node. This node applies differentiated character limit pruning to the final search results based on the type of the downstream generation node (i.e., the type code TYPE_1 output from the intent recognition stage). The system presets multiple character limit values, such as 35,000 characters for case analysis and litigation strategies, 40,000 characters for comprehensive legal issues research, and 55,000 characters for legal and regulatory queries. For TYPE_1, the system starts from the head of the pruned final search result list and sequentially adds the string representation length of each entry until the added length exceeds 35,000 characters, at which point only the added entries are retained. The purpose of this is to provide just enough contextual information without exceeding the limit for the downstream scenario-specific large language model.
[0082] Finally, the analysis and generation engine begins its work. Based on the type code TYPE_1, the system invokes the corresponding "Case Facts and Litigation Strategy Generator"—a large language model instance optimized with specific prompts. The input to this generation model includes: a list of search results (containing detailed information on relevant legal provisions and cases) after character budget reduction, the user's original query command, and a file summary output by the file processing engine. The system prompts for the generation model are configured to output a formatted analysis document with a three-section structure: the first section is an overview (summarizing the background and core legal disputes); the second section is a detailed analysis (analyzing the requirements, exceptions, and judicial tendencies regarding the original shareholder's supplementary liability for compensation, based on the retrieved legal provisions and cases); and the third section provides litigation strategy recommendations (providing practical advice on whether the original shareholder should be held liable, how to collect evidence, and potential defenses based on the analysis results). The output format also requires specific link formats for cited regulations and cases. Once generated, the system packages this formatted analysis document, along with a list of associated legal identifiers, a list of case identifiers, and (if any) a list of practical article identifiers, and returns it to the terminal device. Users can view well-structured and properly cited legal research reports on the client, and can click on links to jump directly to the detailed page of the original legal documents for verification.
[0083] The above complete process demonstrates how the two-stage legal retrieval method based on intent routing of this invention responds to a specific legal research request. It achieves scenario adaptation through intent routing, solves the context overflow problem of long documents through a file processing engine, significantly improves retrieval accuracy through a two-stage retrieval engine (especially LLM Boolean judgment), ensures context safety through content fingerprint deduplication and double byte budget reduction, and finally outputs high-quality formatted analysis documents through a scenario-specific generator.
[0084] In another variant embodiment, if the user does not upload any files, the file content list is empty, and step S3 is skipped. The system can still function normally; in this case, the retrieval element generation engine generates structured retrieval parameters based solely on the query command, and the two-stage retrieval and analysis generation continues. Furthermore, if the intent identification output type code is TYPE_7 (invalid / out-of-range input), the system will not perform retrieval and generation but will directly return a guiding response, such as "Your input is irrelevant to legal research or beyond my capabilities; please ask specific legal questions."
[0085] In another variant, for a query with type code TYPE_2 (document drafting), the system invokes the document drafting generator. This generator's output template differs from the case analyzer; it directly outputs a complaint-formatted document containing party information, claims, facts and reasons, and a list of evidence. Furthermore, the search element generation engine may omit case search vectors, retaining only legal search vectors, because the complaint primarily relies on legal provisions rather than similar cases.
[0086] In summary, this invention uses intent routing to classify query commands into mutually exclusive categories, enabling subsequent retrieval parameter generation and generation model invocation to accurately match specific legal research scenarios. Building upon this, it employs semantic segmentation-aware chunking and two-level summary compression for long legal documents, effectively controlling input length while preserving key information. Furthermore, it utilizes a large language model to convert natural language queries into structured parameters containing arrays of core questions, legal and case retrieval vectors, improving the semantic matching quality of the retrieval. In the two-stage retrieval process, vector retrieval first ensures broad recall, then a filtering large language model outputs Boolean relevance judgments for each candidate item, filtering out a large number of irrelevant items at a lower cost and significantly reducing input noise to the downstream generation model. Subsequently, content fingerprint deduplication and dual-byte budget pruning (both hardware and software) prevent redundant items from occupying the context window and fundamentally eliminate the risk of context overflow. Finally, it applies differentiated character limits to the retrieval results based on intent type and invokes a scenario-specific generation model to output formatted documents, ensuring that different legal tasks (such as case analysis, document drafting, and legal retrieval) can obtain appropriate response lengths and professional expressions.
[0087] It should be noted that all directional indications (such as up, down, left, right, front, back, etc.) in the embodiments of the present invention are only used to explain the relative positional relationship and movement of each component in a certain specific posture (as shown in the figure). If the specific posture changes, the directional indication will also change accordingly.
[0088] Furthermore, in this invention, descriptions involving terms such as "first," "second," and "a" are for descriptive purposes only and should not be construed as indicating or implying their relative importance or implicitly specifying the number of technical features indicated. Thus, a feature defined as "first" or "second" may explicitly or implicitly include at least one of that feature. In the description of this invention, "a plurality of" means at least two, such as two, three, etc., unless otherwise explicitly specified.
[0089] In this invention, unless otherwise explicitly specified and limited, the terms "connection," "fixed," etc., should be interpreted broadly. For example, "fixed" can mean a fixed connection, a detachable connection, or an integral part; it can mean a mechanical connection or an electrical connection; it can mean a direct connection or an indirect connection through an intermediate medium; it can mean the internal communication of two components or the interaction between two components, unless otherwise explicitly limited. Those skilled in the art can understand the specific meaning of the above terms in this invention according to the specific circumstances.
[0090] Furthermore, the technical solutions of the various embodiments of the present invention can be combined with each other, but only if they are feasible for those skilled in the art. If the combination of technical solutions is contradictory or cannot be implemented, it should be considered that such combination of technical solutions does not exist and is not within the scope of protection claimed by the present invention.
Claims
1. A two-stage legal retrieval method based on intent routing, characterized in that, Including the following steps: S1: Receive query instructions and a list of associated file contents sent by the terminal device; S2: Call the large language model to classify the query command according to the preset mutually exclusive intent classification template, and output the type code that is uniquely selected from multiple preset type codes; S3: When the file content list is not empty, perform semantic segmentation and two-level summary compression on the file, extract the summary information containing multiple preset structured fields as the file processing result; otherwise, skip. S4: Based on the type code, call the large language model to transform the query instructions and document processing results into a structured set of search parameters that includes at least an array of core questions, a legal retrieval vector, and a case retrieval vector; S5: Based on the structured retrieval parameter set, the corresponding vector retrieval interface is called concurrently to obtain the initial knowledge entries. Then, the filtering large language model is called concurrently to output a Boolean relevance judgment for each initial knowledge entry. Only the entries that are judged to be true are retained. Finally, the retained entries are deduplicated by content fingerprint and double byte budget reduction to obtain the final retrieval results. S6: Apply differential character limit reduction to the final search results based on the scenario-specific type corresponding to the type code; S7: Based on the type code, call the corresponding scenario-specific large language model, take the truncated final search results, query instructions and file processing results as input, generate a formatted analysis document and output it.
2. The two-stage legal retrieval method based on intent routing as described in claim 1, characterized in that, In step S2, the mutually exclusive intent classification template imposes the following constraints on the large language model: (a) The response format is set to a JSON object containing a type code, confidence level, classification reason, and explanation of ambiguity; (b) When the query command contains position keywords, the large language model outputs the corresponding case analysis type code, without considering other classifications; (c) For query instructions that do not contain the position keywords in (b), the large language model determines whether the answer to the query instruction differs due to different parties or case facts: if the answer is yes, the case analysis type code is output; if the answer is no, the comprehensive legal issue research type code is output. (d) When the query command references the file content but the file content list is empty or the file text cannot be obtained, the large language model determines the output based on the preset mapping table between query command keywords and type codes.
3. The two-stage legal retrieval method based on intent routing as described in claim 1, characterized in that, In step S3, the extracted data includes at least the following preset structured fields: file name, parties involved, key time points, core rights and obligations, disputed clauses or risk points, content directly related to the user's question, and summary.
4. The two-stage legal retrieval method based on intent routing as described in claim 3, characterized in that, In step S3, the semantic segmentation and two-level summary compression based on semantic segmentation points specifically includes the following steps: Iterate through the list of file contents and sum the character count for each file to get the total number of characters in the entire file; When the total number of characters in the entire file does not exceed the preset first character threshold, the entire file will be encapsulated into a list of pass-through entries and output directly. When the total number of characters exceeds the preset first character threshold, a semantic cutting point search is performed on files whose single file character count exceeds the upper limit of the block character count: starting from the file character position corresponding to the upper limit of the block character count, the search is performed forward within the preset search range, prioritizing the position of two consecutive newline characters as semantic cutting points, and then searching the position of a single newline character. If neither exists, the file character is directly truncated at the file character position corresponding to the upper limit of the block character count. The file is divided into multiple blocks based on semantic segmentation points, and each block is appended with a context header field; The large language model is invoked using an asynchronous multi-threaded concurrent call mechanism, and the corresponding preset structured fields are extracted for each block. When the cumulative number of characters in the summary exceeds the preset second character threshold, the large language model is called again to integrate and deduplicate the summary according to the preset structured fields.
5. The two-stage legal retrieval method based on intent routing as described in claim 1, characterized in that, In step S4, the structured retrieval parameter set also includes a clause specification field and a validity level field. When generating the structured retrieval parameter set, the large language model is subject to at least one of the following normalization constraints: (a) The core issue array is in the form of declarative sentences. The length of a single sentence is constrained by a preset character limit. The array length is not less than the preset number and each sentence covers mutually exclusive legal dimensions. (b) The legal retrieval vector shall adopt a standard sentence structure that includes the legal subject, applicable conditions and legal consequences, and must include legal effect indicator words of the pre-defined categories; (c) The case retrieval vector adopts a narrative structure that includes information about the parties involved, the disputed acts, the claims of each party, and the focus of the dispute. The length of a single entry is constrained by a preset minimum character limit. (d) The clause specification field adopts the preset clause numbering format; (e) To implement the mapping conversion of the abbreviation of regulations to the official name, and to replace old laws that have been superseded by subsequent laws; (f) The effectiveness level field outputs the corresponding preset code group based on the query content.
6. The two-stage legal retrieval method based on intent routing as described in claim 1, characterized in that, In step S5, concurrently calling the corresponding vector retrieval interface to obtain the initial knowledge entries specifically includes: An asynchronous multi-threaded concurrent call mechanism with preset batch size and preset concurrent execution number as upper limits sends retrieval requests to the legal vector retrieval interface and the case vector retrieval interface respectively; The input parameters for each retrieval request include at least the corresponding retrieval vector extracted from the structured retrieval parameter set. For the case vector retrieval interface, the input parameters also include the minimum similarity threshold, the upper limit of the number of recalls per time, and at least one retrieval scope limitation parameter. Receive the list of entries returned by each vector retrieval interface, and merge the list of entries as the initial knowledge entries.
7. The two-stage legal retrieval method based on intent routing as described in claim 1, characterized in that, In step S5, the concurrent invocation of the filtering large language model to output a Boolean relevance judgment for each initial knowledge item specifically includes: The initial knowledge items are divided into multiple batches, with the maximum number of items in each batch falling within a preset range; For each batch, an asynchronous multi-threaded concurrent call mechanism with a preset concurrent execution limit is used to combine the query command and each knowledge item in the current batch with a preset relevance judgment prompt template to generate multiple independent prompt inputs, and call the filtering large language model respectively. The system receives a JSON object returned by the filtering large language model for each knowledge entry, extracts a Boolean value from it, and associates and stores the Boolean value with the corresponding knowledge entry as the result of the Boolean relevance judgment.
8. The two-stage legal retrieval method based on intent routing as described in claim 1, characterized in that, In step S5, the content fingerprint deduplication and double-byte budget reduction of the retained entries specifically include: Obtain the list of entries retained after Boolean correlation judgment as the entries to be processed; Define an exclusion field set, which includes at least a document type field, a referee date field, and a subtitle field; For each entry in the list of entries to be processed, remove the fields that belong to the exclusion field set to obtain the filtered entries; When the filtered entries contain a summary field that is a string, the summary field will be truncated to the preset character length limit. After sorting the key names of each field in the filtered entries into lexicographical order, serialize them into a normalized JSON string, and use this normalized JSON string as the content fingerprint; Determine whether the content fingerprint of the current filtered entry is the same as the content fingerprint of the already retained filtered entries: if they are different, retain the current filtered entry and record its content fingerprint; if they are the same, discard the current filtered entry. The retained filtered entries are added to the output list in order, and the estimated byte occupancy of the current filtered entry is accumulated to the cumulative byte count. When the cumulative byte count exceeds the preset soft byte upper limit threshold, the addition of new filtered entries to the output list is stopped. The output list is serialized into a JSON string and its actual number of bytes after UTF-8 encoding is calculated. If the actual number of bytes exceeds the preset hard byte limit threshold, the filtered entries are deleted one by one from the end of the output list until the actual number of bytes is lower than the hard byte limit threshold.