A precise legal consultation system based on multi-agent orchestration
By employing multi-agent orchestration technology, the shortcomings of existing legal AI consultation systems in intent recognition and context management are addressed, enabling efficient and personalized legal consultation services and improving user experience and system adaptability.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-04-20
- Publication Date
- 2026-06-02
Smart Images

Figure CN122133811A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the fields of artificial intelligence and legal technology, specifically to a precise legal consultation system and method based on multi-agent orchestration. Background Technology
[0002] With the rapid development of internet technology and artificial intelligence, legal AI consultation systems are playing an increasingly important role in meeting the public's legal needs. Currently, legal AI consultation systems on the market mainly employ three technical solutions: a single large model direct output solution, a keyword matching + template retrieval solution, and a single RAG retrieval enhancement solution. However, these solutions have many shortcomings, including long analysis times when handling complex cases, a lack of personalized services, and difficulty adapting to different legal consultation scenarios.
[0003] While a single large-scale model-based approach can understand user questions to some extent, the high rigor, standardization, and logical dependence of legal texts mean that if the model fails to fully grasp the semantic connections and hierarchical validity of the provisions, it is highly susceptible to generating erroneous or misleading responses, impacting the accuracy of consultations. Keyword matching combined with template retrieval, though simple and easy to implement, lacks systematic modeling and dynamic linkage of the "facts-evidence-rules-precedents" process in case handling, failing to achieve intelligent analysis throughout the entire process from case access to conclusion derivation. While a single RAG-based enhanced retrieval approach improves accuracy to some extent, it lacks the relational reasoning capabilities of legal knowledge graphs, hindering in-depth searches such as "cases related to the same legal provision" and "case level expansion," resulting in a failure to establish a two-way connection between legal knowledge and factual data, making it difficult to create a "case profile."
[0004] Existing patent documents (such as US11893358B1) disclose intent classification and service routing methods based on large language models. These methods identify intent through LLM and then route queries to the corresponding backend services. However, these methods are mainly geared towards general dialogue scenarios and do not consider the specificities of the legal consultation field. Intent classification in legal consultation not only requires identifying whether the user is "consulting" or "chatting," but also requires refining the user's intent down the legal cause of action hierarchy tree to the specific legal cause of action (e.g., from "labor dispute" to "unlawful termination of labor contract"). Otherwise, it is impossible to accurately match the corresponding legal knowledge base and case analysis template.
[0005] US Patent 12141754B2 discloses a workflow management method based on finite state machines for managing the workflow states of data objects. However, this method is geared towards general data object management and does not consider the constraint of "completeness of legal elements" on state transitions in legal cases. In real legal consultation scenarios, whether the session state can transition from "submission of data collection form" to "generation of in-depth analysis report" depends not only on the user's submission action but also on whether the collected information meets the statutory requirements for the completeness of the constituent elements under the cause of action. In complex scenarios such as mediation consultation, how to improve the accuracy, efficiency, and user experience of legal question-and-answer systems, while enhancing their adaptability and personalized service capabilities for complex cases, has become an urgent technical problem to be solved. Meanwhile, European Patents EP3572995B1 and EP3093809B disclose methods for generating state machines, allocating workflow states, and defining operations for case data objects. However, the state transitions in these methods are directly driven by user operations and do not consider proactive identification and guidance mechanisms for supplementing incomplete information.
[0006] Furthermore, existing technologies (such as Chinese patent CN111797246B) disclose courtroom question-and-answer methods based on legal knowledge graphs, but their application scenarios are for simulating judge rulings, which are fundamentally different from the consultation and assistance scenarios for ordinary users of this invention. In complex scenarios such as mediation and consultation, how to improve the accuracy, efficiency, and user experience of legal question-and-answer systems, while enhancing their adaptability to complex cases and their ability to provide personalized services, has become an urgent technical problem to be solved.
[0007] In summary, existing legal AI consultation systems generally suffer from several common shortcomings: they lack the ability to orchestrate multiple agents according to their responsibilities, resulting in an excessive burden on a single model; they lack a refined intent classification and routing mechanism oriented towards the hierarchical structure of legal causes of action, making it impossible to finely locate user intent along the hierarchical tree of legal causes of action; they lack a dynamic routing mechanism, failing to switch different processing paths based on intent type and session state; their retrieval depth is insufficient, making it difficult to meet the in-depth analysis needs of complex cases; their context management is imprecise, leading to low token utilization and a tendency to generate illusions in long sessions, particularly lacking a neutral processing mechanism for historical in-depth analysis reports, causing the model to become fixated on old report content in subsequent rounds; they lack a legal element completeness verification mechanism, failing to determine whether the collected information meets the statutory elements of a crime before state transitions; and they lack emotion perception and personalized reassurance capabilities, resulting in a mechanical user experience. These problems severely restrict the development and application effectiveness of legal AI consultation systems, necessitating a precise legal consultation system based on multi-agent orchestration to solve these technical challenges. Summary of the Invention
[0008] The technical problem this invention aims to solve is to address the issues of inefficient context management, inaccurate intent recognition, insufficient capacity for handling complex cases, awkward user experience, and high coupling between front-end and back-end in existing legal consultation systems during multi-turn dialogues. Specifically, it aims to provide a precise legal consultation method and system based on multi-agent orchestration. Specifically, it aims to resolve the following technical pain points.
[0009] The issues include: Token explosion in long conversations: As the number of consultation rounds increases, historical messages lead to a surge in model inference costs, increased attention distraction, and a higher risk of illusion. Vulnerability in intent recognition: Relying solely on large model intent classification is prone to misjudgment or omissions in specific scenarios. Limited processing of complex cases: It is difficult to provide differentiated and accurate processing flows for different case stages (such as new cases, follow-up questions, and closing). Delayed interactive feedback and fragmented user experience: Lack of dynamic feedback during backend processing and high development costs for cross-platform adaptation.
[0010] Hybrid Intent Classification and Intelligent Routing: Receives user input messages and dialogue history, employing a three-tiered linkage mechanism of "LLM remote inference + local heuristic correction + keyword fallback" to determine intent. Specifically, this includes: sending a request to the large model to obtain an initial classification; performing secondary corrections locally, such as quick entry overwriting, key entity density analysis of legal cases, matching with a legal cause-of-fact domain thesaurus, and maintaining the coherence of the preceding stages based on rendering type. The secondary corrections include refining the initial classification results downwards along a preset legal cause-of-fact hierarchy tree to obtain refined cause-of-fact identifiers; performing ternary routing determination based on the correction results for individual case links, legal question-and-answer links, or basic consultation links; and ensuring 100% routing output through a keyword dictionary in fallback scenarios such as network anomalies.
[0011] Dynamic multi-link and legal consultation auxiliary state machine-driven process orchestration: Maintaining the legal consultation auxiliary state machine to manage multiple states such as new case, pending supplementary documents, submitted data collection form, and generated report. This state machine assists users in completing legal information collection and analysis preparation. Its state transitions are not directly driven by user operations or dialogue events, but are determined by the matching ratio results of the legal requirement completeness verification. When routing to a case link, differentiated processes are executed based on the state machine determination: New Case Status: Displays the case information collection form and automatically fills in the detailed case details.
[0012] Legal Requirement Completeness Verification State: After the data collection form is submitted but before in-depth analysis is triggered, the system does not directly execute a state transition, but instead enters the legal requirement completeness verification state. In this state, the system extracts the collected information and performs a one-way matching comparison with the list of legal requirements corresponding to the current cause of action in a preset static legal requirement template library. The static legal requirement template library remains unchanged in a single consultation session and is not updated in real time based on the user's dialogue content. The system calculates the matching ratio of the matched legal requirements to the total number of legal requirements. If the matching ratio reaches a preset completeness threshold, the system transitions to the in-depth analysis state. If it is below the threshold, the system transitions to the requirement completion state, identifies the missing legal requirements, generates a list of missing requirements, arranges them in the logical order of legal requirements, and calls the reassurance agent to transform the missing requirements into easy-to-understand guiding questions to help the user supplement key information. This mechanism realizes a technical improvement from "passive state management" to "proactive legal consultation guidance," which is different from the passive state change method triggered by user operation or preset events in the existing technology.
[0013] After passing the legal requirement completeness verification, the deep analysis report generation process is triggered, performing a dual-path retrieval of vector retrieval and legal knowledge graph relationship expansion, and generating a structured JSON report under illusion prevention constraints (such as restrictions on legal citation and evidence status enumeration) for legal document generation scenarios. The deep analysis report is a legal knowledge integration report, including legal basis, similar case references, and comparisons of multi-path solutions. The report explicitly states, "This report is for legal information reference only and does not constitute legal advice." Unlike court trial simulation systems, this invention does not include quantitative predictions of the probability of winning a case, adjudicative determinations of the probative value of evidence, or final determinations of legal liability.
[0014] Follow-up questioning status: Invoke the soothing agent to perform a three-stage soothing guidance process of "empathy-clarification-micro-steps".
[0015] For legal dialogue scenarios, a multi-dimensional adaptive context compression algorithm is introduced to reduce token overhead before performing model inference and retrieval. Specifically, this includes: Route-aware truncation: Sets different limits on the number of rounds or characters to retain in historical conversations based on the current link type (legal Q&A / default / case follow-up). For individual case links, a longer window is retained to maintain the continuity of case facts.
[0016] Rendering type hierarchical truncation: Set differentiated character truncation thresholds based on the rendering type of the message (such as legal Q&A cards, collection forms, and plain text), and enforce a priority retention strategy for collection fields, giving priority to retaining the core legal elements fields of structured messages.
[0017] Neutralization of outdated reports: Identify nodes in historical in-depth analysis reports and replace them entirely with summary tag text containing only identifiers and summary meta-information (report existence identifier, generation timestamp, cause of action type, number of core disputes). This prevents the model from becoming fixated on old reports, and in particular, prevents the model from erroneously applying legal conclusions from historical reports to new inquiry scenarios.
[0018] Query pruning: Before vector retrieval, query text exceeding a threshold is truncated to prioritize user input, ensuring the integrity of the legal fact description and improving retrieval accuracy.
[0019] Emotional perception and multi-stage personalized reassurance: An emotional reassurance mechanism is embedded throughout the entire formal legal response process. First, the system obtains the user's emotional tags and crisis markers through an emotion recognition interface. Then, it executes a three-stage reassurance process: pre-response reassurance with empathy and clarification before the legal response; intermediate refining by softening the tone during response generation; and personalized closing reassurance based on the user's demographic characteristics and emotional tags. Simultaneously, the system can automatically detect keywords in the user's closing statements and trigger a termination guidance process that is mutually exclusive with the legal response process.
[0020] Decoupled front-end and back-end interaction based on a rendering type protocol: A communication protocol is defined, including `renderType` and `routeType` fields. The back-end only outputs structured business data and corresponding rendering type enumeration values (such as case collection forms, in-depth reports, legal Q&A cards, etc.), prohibiting the embedding of HTML / CSS or other front-end directives. Upon receiving the data, the front-end renders the corresponding component independently based on the mapping table; unknown types are downgraded to plain text display. Rendering type tags are synchronously stored during message persistence to support accurate style restoration during historical playback, achieving unified and independent evolution of the same back-end interface across multiple platforms (Web, mobile, and mini-programs).
[0021] The phased streaming response experience design divides the backend processing into multiple semantic phases, including intent recognition, retrieval, graph expansion, and generation. After a user sends a message, the frontend immediately displays a progress bubble and receives phase updates pushed from the backend via SSE or polling to replace the prompt text in real time, creating continuous dynamic feedback. The system configures differentiated timeout thresholds for each phase to handle anomalies and reserves an extension interface for token-level streaming output, supporting a word-by-word typewriter effect to further optimize the waiting experience.
[0022] Accordingly, the present invention also provides a precision legal consultation system based on multi-agent orchestration, including a front-end orchestration layer, a back-end capability layer, a data storage layer, and a user interaction layer.
[0023] The user interaction layer provides multi-channel interaction methods, including web and mobile devices. The system uses natural language processing technology to intelligently parse and respond to user input, and provides personalized reassurance and guidance in special scenarios.
[0024] The front-end orchestration layer includes an intent classification module, a session state machine module, and a ternary routing decision module. The intent classification module employs a hybrid intent classification method, utilizing a three-level linkage of LLM remote inference, heuristic secondary correction, and keyword fallback to achieve refined identification and classification of user intents. The session state machine module records and analyzes user session history, enabling dynamic management of session states. The ternary routing decision module performs dynamic routing decisions based on the intent classification results and session states to determine the optimal processing path.
[0025] The backend capability layer includes the Intent Agent module, Retrieval Agent module, Knowledge Graph Agent module, Generation Agent module, and Soothing Agent module. The Intent Agent module is responsible for parsing and processing user input, extracting key information and intent elements; the Retrieval Agent module employs a dual retrieval mechanism, combining vector retrieval and knowledge graph expansion to achieve deep-level information retrieval; the Knowledge Graph Agent module, based on the Neo4j knowledge graph, realizes a structured representation of legal concepts and relationships; the Generation Agent module utilizes a deep generative model to generate structured analysis reports and response content based on the retrieval results; and the Soothing Agent module, based on an emotion recognition model, provides personalized soothing and guidance.
[0026] The legal knowledge graph of this invention adopts a dual-link architecture that separates online consultation and offline updates: (1) Online Consultation Link: During the user's legal consultation process, the knowledge graph provides services in read-only mode. The graph agent only performs query operations, and the search direction is limited to a forward expansion from the cause of action to the statutory requirements, including the expansion of related cases with the same legal provisions and the expansion of the parent-child relationship of the cause of action hierarchy. The system does not perform any write, update or delete operations on the knowledge graph.
[0027] (2) Offline update link: The content update of the knowledge graph is completed by an independent offline update link, which is completely separated from the online consultation link. The offline update link regularly (e.g., daily) pulls incremental data from authoritative legal data sources (including legal databases, judicial interpretation databases, and judgment document databases), performs incremental construction of the graph in the offline environment, and after quality verification (including orphan node detection and relationship integrity verification), switches the graph version used by the online service through blue-green deployment.
[0028] Unlike existing technologies that rely on real-time user dialogue to drive the dynamic evolution of the knowledge graph, this invention ensures the stability of online services in high-concurrency scenarios and avoids the potential impact of users' non-professional expressions on the quality of legal knowledge graph data through a separation design of consultation and update links.
[0029] The data storage layer includes a persistent session database, a case retrieval database, a legal knowledge base, and a user profile database. The persistent session database stores user session history and intermediate states; the case retrieval database and legal knowledge base store retrieval results and basic data; and the user profile database stores personalized user information and historical preferences.
[0030] The beneficial effects of this invention are as follows: 1. The legal consultation process is broken down into five decoupled intelligent agents: "intent recognition → retrieval enhancement → graph expansion → structure generation → emotional soothing". Through a dynamic multi-link processing method, based on the intent classification results, three capability links (case consultation link, legal Q&A link, and basic consultation link) are switched according to the session state, which realizes specialized processing for different scenarios and provides personalized and efficient services.
[0031] 2. By adopting a hybrid intent classification method, and through a three-level linkage of LLM remote reasoning, local heuristic correction, and keyword fallback, the analysis efficiency of complex cases is significantly improved, the processing time is shortened, and the user experience is enhanced.
[0032] 3. A multi-dimensional context compression algorithm is introduced. Through an adaptive context compression mechanism based on message type, the problem of the continuous growth of historical message tokens in long dialogues is effectively solved, reducing the model inference cost and reducing the risk of attention distraction and illusion.
[0033] 4. A method for emotion perception and personalized reassurance is proposed. Through emotion recognition, three-stage reassurance generation and automatic conversation end detection, affective computing and personalized care are integrated into the entire interactive process, thereby improving the user's perception experience and satisfaction.
[0034] 5. Adopt a phased flow response experience design method, which improves the user's waiting experience by displaying progress indicator bubbles on the front end and updating them in real time with the processing stage, breaking down a single long wait into a continuous phased feedback flow.
[0035] 6. The front-end and back-end decoupling method driven by the rendering type protocol is adopted. By defining the renderType field as the front-end and back-end decoupling protocol, the flexibility of the front-end rendering method is realized. The rendering method is determined autonomously according to the renderType value, without the back-end participating in the UI logic, which greatly improves the adaptability and scalability of the system. Attached Figure Description
[0036] The above is merely an overview of the technical solution of the present invention. In order to better understand the technical means of the present invention, the present invention will be further described in detail below with reference to the accompanying drawings and specific embodiments.
[0037] Figure 1 This is a diagram of the architecture of the precision legal consultation system based on multi-agent orchestration in this invention; Figure 2 This is a flowchart of the multi-agent orchestration provided in this invention; Figure 3 This is a schematic diagram of the context compression strategy provided in this invention; Detailed Implementation
[0038] To make the objectives, technical solutions, and advantages of this invention clearer, the invention will be further described in detail below with reference to the accompanying drawings and specific embodiments. It should be understood that the specific embodiments described herein are merely illustrative and not intended to limit the invention. Example
[0039] This embodiment describes the basic implementation process of a precision legal consultation method based on multi-agent orchestration. This process integrates hybrid intent classification, dynamic multi-link processing, multi-dimensional context compression, and emotion perception and reassurance mechanisms to achieve a complete closed loop from user input to precise legal response.
[0040] I. Hybrid Intent Classification and Intelligent Routing When a user enters a legal consultation message through the interactive interface, the system first performs a hybrid intent classification to determine which processing path the message should follow. This hybrid intent classification mechanism employs a three-tiered linkage architecture of "LLM remote inference + local heuristic correction + keyword fallback" to ensure the accuracy and robustness of intent recognition.
[0041] Step 1.1: Remote Large Language Model Intent Inference. The front-end orchestration module obtains the user's current input message and the most recent N rounds of dialogue history, preferably N=10. This dialogue history is encapsulated and sent to the back-end intent recognition agent. The intent recognition agent calls the remote large language model, sets the model temperature parameter T=0.1 to ensure the determinism of the output, and requests the model to return a structured intent classification result. This result includes an intent field (intent type, values include case, general, other) and an is_cause_of_action field (boolean value, indicating whether it is a legal cause of action).
[0042] Step 1.2: Local Heuristic Secondary Correction. Because large language models may misclassify or omit certain cases under specific boundary conditions, the front-end orchestration module, after receiving the remote classification results, will execute a series of heuristic rules locally for secondary correction. This includes the following sub-steps: Quick Entry Override: If the _lcCaseConsultSendPrimed flag in the session context is detected to be true, indicating that the user entered the session through the "Case Consultation" quick entry, then the intent will be forcibly overridden to case.
[0043] Entity density analysis: The `_heuristicCaseIntent` function is executed to determine whether a user message is a case description based on its text length and the frequency of key legal entities such as dates, amounts, and names. For messages containing rich entities but misclassified as short messages by the model, they are corrected to case intent.
[0044] Domain keyword fallback: The `_fallbackIsMarriageFamilyKeywords` function is executed to match a pre-defined domain thesaurus of legal causes of action (such as "divorce," "custody," "bride price," "domestic violence," etc.) using regular expressions. If the domain identifier returned by the large model is empty or has a confidence level below the threshold, but the message text matches the thesaurus, the domain identifier is completed or corrected to match the legal cause of action.
[0045] Maintaining continuity of the previous round: Execute the `_shouldContinueMarriageLawQAFromLastTurn` function to check the rendering type of the response generated in the previous round of dialogue. If the previous round was a "legal Q&A card" (lqa-card), then the intention of this round to continue along the legal Q&A path is to be maintained, avoiding incorrect jumps to other paths due to brief follow-up questions from the user.
[0046] Independent new case determination: Execute the _suppressMergeWithPriorIntake function to identify when a user suddenly starts describing a new fact that is completely unrelated to the content of the current collection table (i.e., "independent new case long narrative"), and determine it as an independent new case to avoid mistakenly incorporating it into the follow-up questioning process of old cases.
[0047] Step 1.3: Three-element route determination.
[0048] Based on the revised intent result from step 1.2, the front-end orchestration module performs route determination: If intent=case and is_cause_of_action=true, then the route is routed to the case link (case link).
[0049] If intent=general and is_cause_of_action=true, then the route is to the general legal advice link (general link).
[0050] In other cases, the question-and-answer link is routed to other domains (other links).
[0051] Step 1.4: Keyword Backup Guarantee. If steps 1.1 and 1.2 fail to output valid results due to network anomalies in the remote large language model service, interface timeouts, response format parsing failures, or missing fields in the LLM return results, the system will activate a pure keyword matching backup mechanism. This mechanism specifically includes: preprocessing the user input message (removing stop words, word segmentation, and text normalization); based on a pre-built three-level keyword dictionary (level 1 consists of procedural keywords such as "lawsuit" and "litigation," level 2 consists of entity keywords such as "divorce" and "custody," and level 3 consists of functional keywords such as "consultation" and "how"); using the longest match priority principle for keyword matching and priority ranking; and finally, outputting the backup routing result based on the highest priority of the matched keywords, and recording the backup trigger log for subsequent optimization. This mechanism ensures that the system can output a valid routing direction 100% of the time under any circumstances.
[0052] II. Dynamic Multi-Link and Session State Machine-Driven Process Orchestration The front-end orchestration module maintains a legal consultation auxiliary state machine to manage the user's current stage in the consultation session. State transitions in this machine are not directly triggered by user actions, but are determined by the results of legal requirement completeness verification. States include, but are not limited to: new_case (new case status, data collection form not yet submitted), case_intake_form (data collection form being displayed), requirement_verification (legal requirement completeness verification status), case_intake_submitted (data collection form submitted and passed requirement verification, awaiting in-depth analysis), case_report_done (in-depth report generated), general_qa (general Q&A status), and soothing (soothing status). After each user interaction, the system updates the session state based on the execution result of the current link; the state machine then drives the branch selection of subsequent processing logic.
[0053] Link A: Case link processing flow. When routing to a case link, the state machine drives the following branch logic: Branch A1: Initial processing of new cases. The orchestration module checks if a message record with renderType=case-report exists in the current session history. If not, it is determined to be a new case. At this time, the system calls the _presentMarriageCaseIntakeForm() function to automatically construct and display a case information collection form, and automatically populates the form with the cause of action (matched_cause) matched in the intent classification stage to guide the user to supplement case details. This form state is persisted, and the corresponding rendering type is renderType=case-intake-form.
[0054] Branch A1.5: Legal Requirement Completeness Verification. After the user fills out and submits the data collection form, the system does not immediately enter the deep analysis process, but first enters the legal requirement completeness verification state. The system calls the _verifyLegalRequirements() function to perform the following verification steps: (1) Extract the information fields filled in by the user in the collection form, including case type, fact description, time node, party information, etc.; (2) Obtain the list of statutory elements corresponding to the current cause of action from the preset static statutory elements template library. This template library is built based on current laws and regulations and remains static in a single consultation session; (3) Perform a one-way matching comparison between the factual elements in the collected information and the list of statutory requirements, and calculate the proportion of the matched requirements to the total number of statutory requirements; (4) Determine whether the ratio reaches a preset completeness threshold (preferably, the threshold is 60%): If the threshold is reached, the system transitions to the case_intake_submitted state and continues to execute the deep analysis process. If the threshold is not met, the system transitions to the requirement_pending state, identifies the missing legal requirements, generates a list of missing requirements, and calls the reassurance agent to translate the missing requirements into easily understandable guiding questions (e.g., changing "Did the employer give you 30 days' notice?" to "How much notice did the company give you when you didn't need to come to work?"). These questions are then returned to the user in logical order, guiding them to supplement the information. This proactive guidance mechanism differs from the passive management approach in existing technologies that only determines state changes based on whether an event has occurred.
[0055] Branch A2: In-depth analysis after the data collection form is submitted. After the user fills out and submits the data collection form, the system persists the submission status as renderType=case-intake-submitted and enters the in-depth analysis process: Dual-path retrieval: The `_runCaseIntakeDeepAnalysis()` function is called to concatenate the data from the collection table with the dialogue history and send it to the backend ` / case-report-reply` interface. The backend retrieval agent first vectorizes the case summary and retrieves the Top-5 similar cases and Top-8 related legal provisions from the Qdrant vector database. Simultaneously, the graph agent uses the retrieved legal provision IDs as seed nodes to perform relational traversal in the Neo4j knowledge graph, expanding to obtain related cases with the same legal provision and the parent-child relationships of the cause of action hierarchy.
[0056] Context building and generation: The system combines vector retrieval results, graph expansion results, collected table data and dialogue history into a unified context, calls the large language model, and preferably sets the model temperature parameter T=0.3 to generate a structured in-depth analysis report in JSON format.
[0057] Hallucination Prevention: During the generation process, the system enforces hallucination prevention constraints, which include: requiring models to only reference the legal provisions and case list provided by the backend during the generation process, and prohibiting the creation of their own; factual statements must use uncertainty prefixes, including but not limited to "according to user description" and "if true"; the evidence satisfaction status is strictly limited to a four-value enumeration of "satisfied", "not satisfied", "disputed", and "cannot be determined".
[0058] Report Output: The final structured in-depth analysis report includes the following data fields: summary (event overview), issue_list (list of disputes, each including fact-findings, legal element analysis, evidence evaluation, cited legal provisions, and cited cases), and case_solutions (multi-path solutions, each including solution name, success rate of similar case mediation, advantages and disadvantages analysis, specific steps, and risk warnings). The report is presented to the user in card format with renderType=case-report. A disclaimer is clearly stated at the top of the report: "This report is for legal information reference only and does not constitute legal advice. Please consult a professional lawyer for specific cases." The report content focuses on the integration of legal knowledge and the presentation of multi-path solutions, and does not include quantitative predictions of the probability of winning a case, adjudicative determinations of the probative value of evidence, or final judgments of legal liability.
[0059] Branch A3: Follow-up handling of issued reports. If the orchestration module detects a message record with renderType=case-report in the current session history, it determines that this is a follow-up scenario after a report has been issued. At this time, the system calls the reassurance agent to execute a three-stage reassurance strategy: The first paragraph (empathetic response): expresses understanding of the user's continued concerns.
[0060] The second paragraph (clearly informing): clearly informs the user that the report is currently in a "report completed" state, guiding the user to focus on specific issues in the report and ask follow-up questions.
[0061] The third paragraph (Directional Suggestions): Provides follow-up suggestions, such as refining the points of contention, comparing solutions, and assessing risks. The reassurance content is output in card format with renderType=soothe-card.
[0062] Link B: General Legal Consultation Link Processing Flow. When the orchestration module receives the routing determination result (intent=general and cause_of_action=true), it enters the general legal consultation link. The system calls the retrieval agent to perform Qdrant vector retrieval to obtain Top-K relevant legal knowledge entries, preferably K is set to 8 by default; it calls the graph agent to use the retrieved legal provision ID as the seed node to expand and obtain related cases and related legal provisions in the Neo4j knowledge graph; it calls the generation agent to concatenate the retrieval results with the dialogue history, calls the large language model, preferably sets the model temperature parameter T=0.2, and generates an LQA structured card. This card includes: question restatement, answer summary, legal basis, related cases, and further reading, and is output in the form of renderType=lqa-card.
[0063] Link C: Other Domain Question-Answer Link Processing Flow. When the orchestration module receives the routing determination result (non-specific case domain or routing determination failure), it enters the other domain question-answer link. The system calls the retrieval agent to perform Qdrant vector retrieval to obtain Top-K relevant legal knowledge entries, preferably K is set to 6 by default; it calls the generation agent to concatenate the retrieval results with the dialogue history, calls the large language model, preferably sets the model temperature parameter T=0.3, and generates a basic question-answer card. This card is output in the form of renderType=plain.
[0064] III. Multi-dimensional context compression Before sending the dialogue history to the large language model for inference or retrieval, the system performs a multi-dimensional context compression algorithm to reduce token overhead, decrease attentional distraction, and mitigate the risk of hallucinations. This algorithm includes the following steps: Step 3.1: Route-Aware Historical Window Truncation. Based on the link type of the current session, a differentiated historical dialogue round window truncation strategy is implemented. Specifically: when the link type is a Legal QA (LQA) link, the most recent 16 rounds of dialogue are retained; when the link type is a default link, the most recent 20 rounds of dialogue are retained; when the link type is a case follow-up link, historical messages exceeding 3500 characters are truncated.
[0065] Step 3.2: Character truncation by rendering type. Iterate through each message in the dialogue history, obtain its `renderType` attribute, and execute the corresponding truncation strategy based on the value. Specifically: when `renderType` is `lqa-card`, truncate to 2800 characters; when `renderType` is `plain`, truncate to 3500 characters; when `renderType` is `case-intake-form` or `case-intake-submitted`, truncate to 8000 characters. Preserving complete collected data has a higher priority than truncation, meaning non-collected fields are truncated first. For messages exceeding the threshold, truncation is performed using header retention, footer retention, or key field retention strategies. For structured JSON messages, core fields (such as `summary` and `issue_list`) are retained first, while non-core descriptive content is truncated.
[0066] Step 3.3: Neutralize Stale Report Nodes. Call the `strip_case_pipeline_turns_for_general_consultation()` function to iterate through all messages in the dialogue history and identify message nodes with `renderType: case-report`. Replace the identified case-report JSON content with a preset summary tag text. This summary tag text includes the following information: report existence identifier (indicating the existence of a historical report in this round of dialogue), report generation time (indicating the timestamp of report generation), and a report summary (containing meta-information such as the cause of action and the number of core disputes, but excluding specific legal analysis and conclusions). Output the neutralized dialogue history for subsequent model inference. Replacing the complete report content with summary tags prevents the model from becoming fixated on old report content in subsequent rounds, avoiding misjudgments of intent or skewed responses due to excessive focus on historical reports.
[0067] Step 3.4: RAG Query Context Pruning. Obtain the query text to be sent to the vector retrieval engine. The query text includes the current user input and necessary context information. Determine if the character length of the query text exceeds a preset threshold, preferably 2000 characters. If it does not exceed the threshold, send it directly to the vector retrieval engine (Qdrant) for retrieval; if it exceeds the threshold, perform a pruning operation: prioritize preserving the complete content of the current user input to ensure user intent is not lost; for the excess portion, truncate the historical context sequentially from oldest to newest according to message time; if the threshold is still exceeded after truncating the historical context, truncate the current user input at the end, retaining the first 2000 characters. Output the pruned query text and send it to the vector retrieval engine for retrieval. By limiting the query text length, retrieval noise introduced by excessively long queries can be avoided, improving the relevance and accuracy of the retrieval results.
[0068] IV. Emotional Perception and Personalized Reassurance Throughout the consultation process, the system provides users with an interactive experience that offers emotional support through emotion perception and a multi-stage reassurance mechanism.
[0069] Step 4.1: Emotion Recognition. Obtain the user's most recent speech text and call the backend ` / comfort-emotion` interface. Preferably, set the model temperature parameter T=0.15 to ensure output determinism. The large language model performs emotion analysis on the user's speech, outputting structured emotion recognition results, including: `emotion_labels` (a set of emotion labels selected from a pre-defined emotion dictionary, including but not limited to anxiety, anger, sadness, helplessness, confusion, and disappointment), `crisis` (a crisis flag, with a value of true or false, used to identify whether the user has extreme emotions or a potential crisis state), and `intensity` (emotion intensity score, ranging from 0 to 1, with higher scores indicating stronger emotions). The emotion recognition results are persisted to the current conversation context for subsequent reassurance generation.
[0070] Step 4.2: Three-stage reassurance generation. This invention embeds a three-stage emotional reassurance mechanism throughout the entire process of formal legal response: Pre-emptive reassurance: Performed before the formal legal response. The backend ` / comfort-four-step-reply` interface is called, preferably with the model temperature parameter T=0.45. Based on emotion recognition results, the large language model generates a three-part reassurance text: the first part, "empathy," realistically reflects the user's current emotional state; the second part, "clarification," summarizes the user's core demands and confirms correct understanding; the third part, "micro-steps," provides immediately actionable, low-risk action suggestions. This pre-emptive reassurance text is output before the formal legal response.
[0071] Intermediate polishing: Performed during the generation of the formal legal response. The backend ` / comfort-script-polish` interface is called, preferably with the model temperature parameter T=0.35. The original legal response template is obtained, and the large language model adjusts the tone of the response template. Without changing the legal conclusions, legal citations, and case analysis, the straightforward expressions are softened, including replacing affirmative judgments with conditional statements, adding moderating transitional phrases, and reducing the intensity of negative conclusions.
[0072] Closing and appeasing: This is performed after the legal response is completed. User demographic characteristics (including gender, age group, and education level) are extracted from the case collection form. Based on these demographic characteristics, a pre-set personalized closing statement template library is used. The backend ` / comfort-closing` interface is called, preferably with the model temperature parameter T=0.4. The matched basic template and emotion tags are input into a large language model for fine-tuning and polishing, generating personalized closing text, which is appended to the end of this round of responses.
[0073] Step 4.3: Automatic Session Closing Detection. After each round of legal responses, the front-end orchestration layer calls the `_lcLooksLikeSessionClosing()` function to perform a closing detection. This checks if the user's latest message contains closing keywords, including but not limited to: "thank you," "thank you," "goodbye," "end," "no questions," and "consultation complete." If any closing keyword is matched, the closing flag `is_session_closing` is set to true, and the `_lcOnConsultTurnComplete()` callback function is triggered, automatically executing the closing and comforting process: calling the ` / comfort-closing` interface to generate a warm closing guidance card. This card includes thank-you messages, summaries, blessings, and follow-up instructions, and is output in `renderType=closing-card` format. A mutual exclusion control is implemented between the closing detection and the case follow-up comforting: when `is_session_closing` is true, the current round will not enter the case follow-up comforting link or the formal legal response generation link. After the closing and reassurance process is completed, the session state transitions to the session_closed state, awaiting the user to initiate a new round of inquiries. Example
[0074] This embodiment, based on the basic process described in Embodiment 1, further describes the optimized design for improving system scalability and user experience, specifically including a front-end and back-end decoupling method driven by rendering type protocol and a staged streaming response experience design.
[0075] I. Decoupling of front-end and back-end driven by rendering type protocol To address the issues of high coupling between the front-end and back-end and high costs of multi-platform adaptation in traditional web applications, this invention defines a communication protocol based on the renderType field to achieve decoupling between the front-end and back-end and unified rendering across multiple platforms.
[0076] Step 5.1: Define the rendering type protocol field. Define the `renderType` field as a core protocol field in the front-end and back-end communication protocol. This field is required and its value type is an enumerated string. Simultaneously define the `routeType` field as an auxiliary field to identify the business link type to which the message belongs. Values include, but are not limited to: `case`, `general`, and `other`. The protocol response structure includes the rendering type, route type, business content, and timestamp.
[0077] Step 5.2: Define rendering type enumeration values and front-end rendering behaviors. The system predefines the following rendering type enumeration values and their corresponding front-end custom rendering behaviors: case-intake-form: Case information collection form.
[0078] case-intake-submitted: The case-intake table submits a summary.
[0079] case-report: In-depth case analysis report.
[0080] lqa-card: Legal Q&A card.
[0081] basic-card: Basic question and answer cards.
[0082] Comfort-four-step: a three-stage approach to comforting and guiding.
[0083] persona-comfort-closing: Personalized closing comfort cards.
[0084] plain: Degradation of plain text.
[0085] Step 5.3: Backend Output Protocol Specification. After completing business logic processing, each backend agent is only responsible for outputting structured business data that conforms to the protocol (i.e., the content of the `content` field), along with the corresponding `renderType` and `routeType` tags. The backend is prohibited from embedding HTML fragments, CSS styles, or frontend layout directives in the response. The `content` field output by the backend uses different structures depending on the `renderType`. The backend is unaware of the specific frontend implementation technology stack (React / Vue / native JS) and the terminal type (Web / mobile / mini-program).
[0086] Step 5.4: Front-end autonomous rendering execution. After receiving the back-end response, the front-end extracts the `renderType` field value and matches it against a preset rendering component mapping table. This mapping table defines the correspondence between `renderType` and front-end components. The front-end uses the content field as the data source, instantiates the corresponding rendering component, and performs rendering. If the `renderType` value is not in the mapping table, the front-end falls back to using plain rendering to display the content.
[0087] Step 5.5: Message Persistence and History Replay. Each message, along with its renderType, routeType, content, and timestamp, is persisted to the database or local storage upon sending / receiving. When the user refreshes the page or re-enters the session, the front-end calls the _replayAIMessage() function to perform history replay. During history replay, this function reads the renderType field of each message and accurately recreates the original card style and layout based on the field value. If the renderType field is missing or invalid during replay, the display is downgraded to plain text, and a data anomaly log is recorded.
[0088] Step 5.6: Unified Rendering Support Across Multiple Platforms. Since the backend only outputs renderType tags and structured data, without outputting client-specific UI code, the same backend interface can simultaneously serve multiple frontend platforms, including web, mobile, and mini-programs. Each frontend platform independently implements the mapping from renderType to native platform components according to its own UI design specifications. When adding a new platform, only the renderType mapping table needs to be implemented on the new platform; no backend modifications are required.
[0089] II. Staged Flow Response Experience Design To address the long waiting times caused by complex backend processing (such as dual-path retrieval and large model generation), this embodiment designs a staged streaming response mechanism to provide users with continuous and dynamic processing feedback.
[0090] Step 6.1: Define the processing stage enumeration. Divide the complete backend processing flow into multiple semantically clear stages, each corresponding to a progress prompt message. These stages include, but are not limited to: intent, case analysis, search, graph expanding, generate, and closing. Define stage status enumeration values: start, progress, and complete.
[0091] Step 6.2: Front-end Stage Streaming Display Mechanism. After a user sends a message, the front-end immediately creates and displays an initial progress bubble with the initial message "Understanding your question...". The front-end establishes a stage status push channel with the back-end, which can use any of the following technologies: SSE, polling, or WebSocket. After receiving a stage update message, the front-end extracts the current stage identifier and replaces the text of the current progress bubble with the corresponding stage identifier's message. A smooth transition effect is used during text replacement, including but not limited to: text fade-in / fade-out and stepless bubble height changes, avoiding abrupt visual jumps. The text is replaced in real-time upon completion of each stage, providing the user with a continuous feedback stream rather than a single long wait.
[0092] Step 6.3: Stage Transition Rules. Define different stage transition order rules based on the general link or the case link. The backend pushes stage updates sequentially according to the current link type. The backend can skip certain stages in the stage sequence (e.g., graph_expanding is only triggered in the case link), and when skipped, the frontend uses the previous progress text or automatically adapts.
[0093] Step 6.4: Final Result Replacement. After the backend completes all processing steps, it pushes the stage status "complete" and the final response content. Upon receiving the complete response, the frontend replaces the progress bubble with the final structured card, which is rendered according to the `renderType` protocol. Once replaced, the progress bubble is no longer retained or displayed repeatedly.
[0094] Step 6.5: Exception Handling and Timeout Control. Configure differentiated timeout thresholds for each stage, with the thresholds varying according to the characteristics of each stage (e.g., 5 seconds for the intent classification stage, 8 seconds for the retrieval stage). When the processing time of a stage exceeds the threshold, the front-end automatically replaces the prompt with "Processing time is long, please wait...". When the total process time exceeds 30 seconds, the front-end displays "Generating a response for you, please wait patiently..." and keeps the progress bubble active. If the back-end processes an exception or times out without response, the front-end replaces the progress bubble with an error message bubble and displays "System busy, please try again later," while providing a retry button.
[0095] Step 6.6: Token-level Streaming Output Extension Interface. This invention reserves an extension interface for token-level streaming output based on the staged streaming response. The extension interface supports SSE or WebSocket protocols, allowing the backend to push large model output content token by token during the generation stage. When the frontend receives token-level streaming output, it supports two rendering modes: real-time appending of generated text content to the progress bubble and real-time rendering of streaming text in the area below the bubble. Token-level streaming output and staged streaming response can be used in combination, i.e., further decomposed into token-level pushes within the generating stage. The extension interface uses a switch control, dynamically enabling / disabling token-level streaming output based on network environment or user configuration.
[0096] The above description is merely a preferred embodiment of the present invention and is not intended to limit the scope of protection of the present invention. Any variations or substitutions that can be easily conceived by those skilled in the art within the scope of the technology disclosed in the present invention should be included within the scope of protection of the present invention. Therefore, the scope of protection of the present invention should be determined by the scope of the claims.
Claims
1. A legal consultation assistance method based on multi-agent orchestration, characterized in that, Includes the following steps: S1: Receive legal consultation messages and dialogue history input by users through the front-end orchestration module, and send them to the back-end intent recognition agent. The agent calls the large language model to classify the intent and obtain a structured classification result that includes consultation intent type, domain identifier, preliminary matching cause of action and cause of action confidence score. S2: In the front-end orchestration module, the structured classification results are subjected to local heuristic secondary correction based on the hierarchical tree structure of legal causes of action. The correction process includes forced overwriting based on shortcut entry markers, analysis and correction based on the density of key entities in legal cases, catch-all matching of domain identifiers based on the domain thesaurus of legal causes of action, maintaining the continuity based on the rendering type of the previous round of dialogue, and determining the facts of independent new cases based on the hierarchical tree of causes of action, so as to generate the corrected intent type and refine the cause of action identifiers and domain information. S3: Based on the revised intent type and refined case identifier, the front-end orchestration module performs a three-element routing determination for the legal consultation scenario, and routes the current user message to a single processing link among the case link, legal Q&A link, or basic consultation link; S4: When routing to the case link, the current session state is determined according to the legal consultation auxiliary state machine of the session as one of the following: new case consultation state, legal requirement completeness verification state, requirement to be supplemented state, report already issued follow-up state, or session closing state. Based on this, the following actions are executed respectively: collection table display, legal requirement completeness verification and active guidance based on one-way matching of legal constituent element templates, in-depth analysis report generation, three-stage reassurance guidance or personalized closing reassurance process; wherein, the state transition of the state machine is not directly driven by user operation or dialogue event, but is determined by the matching ratio result of the legal requirement completeness verification. S5: Introduces a multi-dimensional context compression algorithm for legal dialogue scenarios. Before sending the dialogue history to the large language model for reasoning, the historical messages are compressed through an adaptive context compression mechanism that is hierarchical according to the message rendering type. This includes replacing the entire historical in-depth analysis report with a summary tag text containing only the cause of action and the number of disputes in the outdated report. This addresses the problems of increased model reasoning costs, distraction, and fixation on historical legal conclusions caused by the continuous growth of the number of historical message tokens in long dialogues. S6: The persistence module persists each message in the session along with its corresponding rendering type tag and routing type tag so that the original front-end display style of the message can be accurately restored according to the rendering type tag during historical playback.
2. The precise legal consultation method based on multi-agent orchestration according to claim 1, characterized in that, The local heuristic secondary modification of the legal cause-of-fact hierarchy in step S2 further includes a combination of one or more of the following rules: S2.1: Shortcut Entry Override Rule: When the shortcut entry flag in the session context is detected to be active, the intent type of the current message is forcibly overridden to "Case Consultation"; S2.2: Legal Case Key Entity Density Analysis Rules: When the length of the message text input by the user exceeds the preset threshold, and after analysis by the entity recognition model, it contains at least two of the following keywords: date, amount, specific name, and cause of action, the intent type is corrected to "case consultation", and the cause of action identifier is refined downward along the preset legal cause of action hierarchy tree according to the hit entity type. S2.3: Last-line rule for the legal cause of action domain thesaurus: When the domain identifier in the structured classification result is empty or the confidence level is lower than the threshold, but the message text matches the preset legal cause of action domain thesaurus, the domain identifier is corrected to the matched cause of action, and the complete cause of action hierarchical path is filled by backtracking upwards along the legal cause of action hierarchy tree; S2.4: Previous round coherence rule based on rendering type: When the rendering type corresponding to the previous round of dialogue message is "legal Q&A card", the routing tendency of the current round is adjusted to remain in the legal Q&A link, and the cause of action identifier of the previous round of dialogue is inherited as the context cause of action constraint of the current round.
3. The precise legal consultation method based on multi-agent orchestration according to claim 1, characterized in that, The personalized closing and reassurance process in step S4 is executed by the reassurance agent, and specifically includes: S4.1: Detect closing keywords in user input messages using keyword matching technology, including closing phrases specific to legal consultation scenarios; S4.2: Extract the user's demographic information from the case collection table associated with the current session; S4.3: Based on the demographic characteristics, match the corresponding basic script templates from the reassurance script template library, which is classified and stored according to the type of legal case. S4.4: Combining the user emotion tags identified in the current conversation, the large language model is invoked to fine-tune and refine the matched basic dialogue template, generating a personalized reassurance response.
4. The legal consultation assistance method based on multi-agent orchestration according to claim 1, characterized in that, The legal requirement completeness verification, proactive guidance, and in-depth analysis report generation process in step S4 specifically includes: S4.5: Before triggering the generation of the in-depth analysis report, perform the legal requirement completeness verification step: extract the information fields filled in by the user in the collection form, and perform a one-way matching comparison with the legal requirement list corresponding to the current case in the preset static legal requirement template library. The static legal requirement template library keeps its content unchanged in a single consultation session and is not updated in real time according to the user's dialogue content; calculate the matching ratio of the matched legal requirements to the total number of legal requirements; if the matching ratio reaches the preset completeness threshold, continue to perform the in-depth analysis step; if it is lower than the preset completeness threshold, identify the missing legal requirements, generate a list of missing requirements, arrange them in the logical order of the legal requirements, call the soothing agent to transform the missing requirements into popular guiding questions, return them to the user to guide supplementary information, and at the same time jump to the requirement to be completed state; S4.6: The retrieval agent performs semantic retrieval of legal cases and provisions based on a vector database, while the graph agent performs relational expansion retrieval of a legal knowledge graph based on a graph database. The legal knowledge graph is provided in read-only mode during the online consultation session, and its content is updated by an independent offline update link. The relational expansion retrieval includes expansion of cases related to the same legal provision and expansion of parent-child relationships at the cause of action level. The retrieval direction is limited to a forward expansion query from the cause of action to the statutory requirements. S4.7: Combine the dual-path search results with the case data entered by the user to construct contextual prompts; S4.8: Under the pre-set illusion prevention constraints for legal document generation scenarios, the generating agent drives the large language model to generate a deep analysis report in structured JSON format. The deep analysis report is a legal knowledge integration reference report. The report is required to include a disclaimer that "this report is for legal information reference only and does not constitute legal advice", and does not include quantitative predictions of the probability of winning the case, adjudicative determinations of the probative value of evidence, or final determinations of legal liability.
5. The precise legal consultation method based on multi-agent orchestration according to claim 4, characterized in that, The hallucination prevention constraints in step S4.7 for legal document generation scenarios specifically include: Legal citation constraints: When generating in-depth analysis reports, the large language model is only allowed to cite specific content provided by the backend retrieval agent or graph agent that exists in the preset "List of Available Legal Provisions" and "List of Related Cases". The model is prohibited from fabricating or citing legal provision numbers and case names that have not been searched and confirmed. Factual statement constraints: Statements in the report that involve factual inferences or legal judgments about the user's case must use uncertain prefixes, including "according to the user's description", "if true", and "based on the available materials". Evidence evaluation constraints: The output value range for evaluating the satisfaction status of the evidence mentioned by the user is strictly limited to four enumeration types: "satisfied", "not satisfied", "disputed", and "cannot be determined". The model is prohibited from outputting evidence evaluation conclusions that exceed this value range.
6. The precise legal consultation method based on multi-agent orchestration according to claim 1, characterized in that, The multi-dimensional context compression algorithm for legal dialogue scenarios in step S5 specifically includes the following steps: S5.1: Route-aware historical window truncation: Based on the link type of the current session, a differentiated historical dialogue round window truncation strategy is executed, in which a longer historical window is retained for individual links to maintain the continuity of case facts; S5.2: Hierarchical character truncation by rendering type: Traverse each message in the dialogue history and execute a differentiated character length truncation strategy based on its rendering type attribute, where legal structured messages are given higher priority than ordinary text messages. S5.3: Neutralization of outdated report nodes: In-depth analysis report nodes in historical dialogues that have exceeded the timeliness threshold are replaced with preset summary marker text. The summary marker text only contains the report existence identifier, report generation timestamp, cause of action type and number of core disputes, and does not contain specific legal analysis content and conclusions, so as to prevent the large language model from becoming fixated on the content of old reports. S5.4: Query Context Trimming: Before sending the query text to vector search, the query text is length-limited and optimized, prioritizing the retention of the complete legal fact description entered by the current user to improve the accuracy of search results.
7. The multi-dimensional context compression algorithm for legal dialogue scenarios according to claim 6, characterized in that, The route-aware history window truncation in step S5.1 further includes: When the current conversation link type is determined to be a legal question and answer link, the history of the most recent 16 rounds of dialogue is retained; When the current session link type is determined to be the default link, the history of the last 20 rounds of dialogue is retained. When the current session link type is determined to be a case follow-up link, the portion of the historical message with a total character count exceeding 3500 characters is truncated. During truncation, messages containing case information and structured collection table messages are retained first.
8. The multi-dimensional context compression algorithm for legal dialogue scenarios according to claim 6, characterized in that, The character truncation by rendering type in step S5.2 further includes: When the message is rendered as a legal Q&A card, it is truncated to 2800 characters; When the message is rendered as plain text, it is truncated to 3500 characters. When the message rendering type is a case collection form or case collection submission, it is truncated to 8000 characters, and the collection field priority retention strategy is enforced when truncating: the key-value pairs of all legal requirement collection fields are retained in their entirety first, and the descriptive content and guiding text of non-collection fields are truncated first. For messages exceeding the threshold, truncation is performed using one or more of the following strategies: header retention, tail retention, or key field retention. For structured JSON messages, priority is given to retaining the core summary portions of the summary field, issue_list field, and case_solutions field.
9. The multi-dimensional context compression algorithm for legal dialogue scenarios according to claim 6, characterized in that, The stale report node neutralization in step S5.3 further includes: Traverse all messages in the dialogue history and identify message nodes whose rendering type is case report; The identified report JSON content is replaced with summary marker text, which includes: report existence identifier, report generation timestamp, and a summary summary of the report containing the cause of action and the number of core disputes, and clearly marks the prompt message "Historical report content has been compressed. Please scroll up to view the full report"; By using summary tags instead of full report content, we can prevent misjudgment of intent or biased responses in subsequent rounds of model reasoning due to the full report content. In particular, we can prevent the model from incorrectly applying legal conclusions from historical reports to new follow-up questioning scenarios.
10. The multi-dimensional context compression algorithm for legal dialogue scenarios according to claim 6, characterized in that, The retrieval query context trimming in step S5.4 further includes: Obtain the query text to be sent to the vector retrieval engine, the query text including the current user input and necessary context information; Determine whether the character length of the query text exceeds a preset threshold of 2000 characters; If the threshold is not exceeded, the data will be sent directly to the vector retrieval engine for retrieval. If the threshold is exceeded, a pruning operation is performed: the user input priority retention strategy is enforced, that is, the complete content of the current user input is retained first, and the excess part is truncated in the order of message time from oldest to newest; if the threshold is still exceeded after truncating the historical context, the current user input is truncated at the end, retaining the first 2000 characters, and legal proper nouns and case keywords are not cut off during truncation.
11. A legal consultation assistance system based on multi-agent orchestration, characterized in that, The system, which employs the method as described in any one of claims 1 to 10, comprises: The front-end orchestration layer is used to perform user interaction, send and receive intent classification requests, heuristic secondary correction logic oriented towards the hierarchical tree structure of legal causes of action, ternary routing determination in legal consultation scenarios, and management and flow of the legal consultation auxiliary state machine. The state transition of the state machine is not directly driven by user operation or dialogue events, but is determined by the matching ratio result of the legal requirement completeness verification. The front-end orchestration layer is a stateless lightweight routing layer and does not store global task state information. The backend capability layer, deployed on the backend server, includes the following intelligent agents decoupled according to their legal consulting business responsibilities: The intent recognition agent receives the dialogue history and calls the large language model for processing, outputting a structured classification result that includes intent type, refined case identifier, and domain identifier; The retrieval agent is used to manage and query the vector database, performing semantic similarity-based vector retrieval of legal cases and provisions to obtain the legal knowledge needed to generate in-depth analysis reports; The Graph Agent is used to manage and query a legal knowledge graph database, and to perform extended searches of legal entity relationships based on the knowledge graph to obtain related cases and cause-of-fact hierarchical relationships. The legal knowledge graph is provided in read-only mode during online consultation sessions, and its content updates are completed by an independent offline update link. The offline update link periodically obtains incremental data from authoritative legal data sources and performs batch updates to the graph. The Graph Agent's search direction is limited to forward searches from cause of action to statutory requirements, rather than backward reasoning from facts to conclusions. An Agent is generated to receive search results, case data, and contextual information. Under the pre-set illusion prevention constraints for legal document generation scenarios, the Agent drives a large language model to generate structured legal analysis reports or question-and-answer card content. The legal analysis report is a legal knowledge integration reference report, which is required to include a disclaimer and does not contain any adjudicative judgments. The soothing agent is used to perform emotion recognition on user messages and generate a three-part soothing response or personalized closing soothing content based on the conversation status. The offline update layer operates independently of the online consultation process and includes: - Data acquisition module, used to periodically pull incremental legal data from authoritative legal data sources, including at least one of legal databases, judicial interpretation databases, and judgment document databases; - An incremental construction module is used to parse the incremental legal data into structured legal entities and relationships, and perform incremental write operations in an offline graph database instance; - The quality verification module is used to perform consistency verification on the updated offline graph, including isolated node detection and relation integrity verification; - Version switching module, used to switch the version of the legal knowledge graph used by the online service to the new version through blue-green deployment after verification; The data storage layer includes a persistence module, which stores each user message and system reply, along with its corresponding rendering type tag and route type tag, in the database, and provides a query interface to support accurate replay rendering of historical sessions.
Citation Information
Patent Citations
Trial methods, apparatus, electronic devices and machine-readable storage media
CN111797246B
Systems and methods for state machine management
EP3093809A1
Case management by a state machine
EP3572995B1
Intent-based query and response routing between users and backend services
US11893358B1
Finite state machines for implementing workflows for data objects managed by a data processing system
US12141754B2