A psychological intervention method and system based on dynamic intention routing and thought chain reasoning
Through the collaborative innovation of dynamic intent routing and thought chain reasoning, the shortcomings of existing psychological intervention systems in intent recognition and intervention logic have been solved. This enables millisecond-level recognition and professional intervention of high-risk intents, improving the system's security and response efficiency while protecting user privacy.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- SHANGHAI ZHONGKE XINTU DIGITAL TECHNOLOGY CO LTD
- Filing Date
- 2026-03-09
- Publication Date
- 2026-06-09
Smart Images

Figure CN122174998A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the fields of artificial intelligence and mental health technology, specifically to a psychological intervention method and system based on dynamic intention routing and thought chain reasoning. Background Technology
[0002] With the rapid development of artificial intelligence technology, intelligent dialogue systems are increasingly widely used in the field of mental health services. Currently, most psychological intervention robots or psychological auxiliary dialogue systems on the market adopt one of the following two technical solutions: First, retrieval-based dialogue systems based on pre-set scripts. These systems pre-build a database containing a large number of question-and-answer pairs or psychological intervention scripts, and retrieve the pre-set response that most closely matches the user's input from the database through keyword matching or semantic similarity calculation. Their advantages are controllable response content and high security, but their disadvantages are poor flexibility and difficulty in handling diverse and unpredictable user expressions. Second, generative dialogue systems based on a single large language model (LLM). These systems use an end-to-end large language model to directly generate natural language responses based on user input. Their advantages are natural language expression, smooth interactive experience, and the ability to handle open-domain dialogue. However, general-purpose large language models are not specifically optimized for psychological intervention scenarios, and have significant shortcomings in terms of professionalism, security, and logical rigor.
[0003] When applied to the specific scenario of psychological intervention, the two mainstream approaches mentioned above generally suffer from the following technical problems:
[0004] 1. Insufficient precision in intent recognition makes it difficult to distinguish between emotional venting and emergency requests for help. Existing systems often only understand user input intent at a superficial semantic matching level, lacking the ability to accurately detect deeper psychological intent. When users express statements containing potential crisis signals, such as "I feel like life is meaningless" or "I really want to end this," traditional retrieval systems may classify them as ordinary negative emotions and only return comforting responses; while generative models, due to their open-ended nature, may generate inappropriate or even risk-enhancing responses. The system's inability to accurately distinguish between ordinary emotional venting and emergency requests for help within milliseconds results in high-risk signals being drowned out by the regular conversation flow, posing a serious security risk.
[0005] 2. The intervention logic lacks professionalism, making it difficult to implement standardized psychotherapy plans. Professional psychological interventions, such as cognitive behavioral therapy (CBT), emphasize following specific counseling processes and logical frameworks—from identifying negative thoughts and analyzing cognitive distortions to guiding cognitive restructuring, each step requires rigorous logical deduction. However, existing generative models, when generating responses, rely solely on the predicted probability of the next word, lacking explicit modeling of the psychological intervention process. Their outputs often exhibit logical jumps, confused causal relationships, and inappropriate use of professional terminology, failing to simulate the step-by-step, in-depth intervention process of a human therapist, resulting in superficial intervention effects and insufficient professionalism.
[0006] 3. Fragmented processing of user history information, lacking long-term user psychological profiling: Existing systems often use fragmented vector retrieval methods to process user history dialogue data, searching only historical fragments semantically relevant to the current input. This mechanism fails to systematically integrate multi-turn, cross-session dialogue information, making it difficult to construct dynamically evolving user psychological profiles. Due to the lack of continuous tracking and modeling of user cognitive patterns, emotional trends, and intervention history feedback, the system's intervention strategies cannot achieve long-term consistency and personalized adaptation. Each dialogue resembles an "initial consultation," severely impacting the depth and effectiveness of intervention. Summary of the Invention
[0007] To address the shortcomings of existing technologies, this invention provides a psychological intervention method and system based on dynamic intent routing and thought chain reasoning. It overcomes the deficiencies of existing technologies, is rationally designed, and achieves millisecond-level identification and forced interruption of high-risk intents. Through structured reasoning, it ensures the professionalism and interpretability of the intervention process, significantly improving the safety, professionalism, and response efficiency of the psychological intervention system.
[0008] To achieve the above objectives, the present invention provides the following technical solution:
[0009] A psychological intervention method based on dynamic intention routing and thought chain reasoning includes the following steps:
[0010] S1: Receives the original text input by the user, performs millisecond-level feature scanning on the original text through a dual-track detection mechanism consisting of a semantic similarity calculation model and a sensitive word matching algorithm, and generates a sentiment tendency score and crisis risk weight.
[0011] S2: Input the emotional tendency score and crisis risk weight into the preset threshold judgment matrix, and according to the judgment result, the original text is diverted in real time to one of the red warning path, yellow intervention path or green general path;
[0012] S3: If the traffic is diverted to the red warning path, the forced warning interruption procedure will be triggered, and three levels of system intervention actions will be performed: instruction truncation, interface redirection, and status marking.
[0013] S4: If the patient is diverted to the yellow intervention path, the thought chain reasoning engine will be activated. Following the preset psychological counseling logic sequence, the cognitive distortion operator, emotional mirroring operator, and cognitive reorganization operator will be called in sequence to drive the large language model to generate step-by-step, traceable psychological intervention strategies.
[0014] S5: If the traffic is diverted to the green universal path, the universal dialogue engine will be invoked to generate open domain dialogue;
[0015] S6: Based on the user's feedback to the previous round of responses, calculate the acceptance score, and dynamically adjust the intervention parameters, including guidance intensity and empathy level, according to the acceptance score.
[0016] S7: Based on the adjusted intervention parameters, output the final psychological intervention script.
[0017] Preferably, the dual-track detection mechanism in step S1 includes:
[0018] The first detection track uses the BERT-base lightweight model to vectorize the original text, calculates the cosine similarity between the encoded text vector and the preset psychological crisis vector space, and outputs the semantic similarity score.
[0019] The second probe track uses a high-performance sensitive word filtering operator built with the Aho-Corasick algorithm to perform multi-pattern parallel matching on the original text and output a list of high-risk intent words and real-time risk weights.
[0020] The fusion decision unit, connected to the first and second probe tracks, is used to perform weighted fusion based on the semantic similarity score, sentiment tendency score, and immediate risk weight to generate the final routing decision signal.
[0021] Preferably, the sentiment tendency score uses a continuous value from 0 to 1, generated based on the confidence score of the negative sentiment intensity of the text using a large language model; the threshold judgment matrix includes a dual verification standard:
[0022] First verification criterion: When the semantic similarity is greater than the first threshold and the sentiment score is greater than the second threshold, a red warning signal is automatically generated;
[0023] The second verification standard is to use a weighted algorithm to calculate the real-time risk weight for words in the preset high-risk intent word library. When the sum of the real-time risk weights exceeds the preset safety level threshold, a red warning signal is automatically generated.
[0024] Preferably, in step S3, the forced early warning interruption procedure includes the following three levels of system intervention actions:
[0025] Level 1 action: Instruction interception, sending a STOP interrupt signal to the large language model instance that is currently performing the generation task, forcibly terminating the generation process of the current token sequence;
[0026] The second level of action: safety redirection, which forcibly switches the user interface to the preset emergency help interface through the front-end interface call, and displays the 24-hour psychological assistance hotline and emergency guidance script on the interface.
[0027] Level 3 action: Status marking. Synchronously mark the corresponding user's session status as high-risk in the background database, and restrict the user to access only the professional guidance functions in the preset red path processing module or yellow path processing module within a preset time window, and prohibit them from entering the open domain dialogue of the green path.
[0028] Preferably, in step S4, the thought chain reasoning engine is built based on a directed acyclic graph workflow engine, and uses a directed acyclic graph to visually arrange multiple logical operator nodes; the logical operator nodes include at least:
[0029] The cognitive distortion operator is configured with classification prompt word templates based on the ABC model and few-shot learning examples to identify and classify irrational beliefs in user discourse and output structured cognitive distortion type labels.
[0030] The Emotion Mirroring Operator is used to generate empathetic response templates based on the user's emotional state.
[0031] A cognitive restructuring operator is used to retrieve and call up corresponding cognitive restructuring guidance instructions from a psychology knowledge base based on the cognitive distortion type label, and generate an intervention strategy.
[0032] Data and parameters are passed between logical operator nodes through JSON-formatted session state objects.
[0033] Preferably, the prompt word template for identifying cognitive distortion operators includes:
[0034] The Role field is used to set the role of the large language model as a professional psychological tester.
[0035] The Task field is used to instruct the large language model to identify logical fallacies in user speech and match them with preset standard cognitive distortion types.
[0036] The Logic field indicates that the large language model follows the ABC model, with a focus on identifying irrational components in belief B.
[0037] The Output field is used to instruct the large language model to convert the recognition results into a preset structured data format, which includes cognitive distortion type labels, confidence scores, and original text reference fragments.
[0038] This invention also discloses a psychological intervention system based on dynamic intention routing and thought chain reasoning, comprising:
[0039] The routing agent, deployed at the system input end, is equipped with a dual-track detection engine to perform parallel feature scanning on the original text input by the user. Based on the preset sentiment tendency scoring model and crisis threshold matrix, the text is diverted in real time to one of the red warning path, yellow intervention path, or green general path.
[0040] The red path processing module is connected to the routing agent and is equipped with a forced warning interruption engine. When the text is diverted to the red warning path, it sends an interruption signal to the large language model inference instance, forces the user interface to switch to the emergency help interface, and marks the corresponding user status as high-risk in the background database.
[0041] The yellow path processing module is connected to the routing agent and is equipped with a thought chain reasoning engine. The thought chain reasoning engine contains multiple serial logical operator nodes, which are used to guide the large language model to perform reasoning step by step according to the preset psychological intervention steps and generate a structured intervention strategy.
[0042] The green path processing module is connected to the routing agent and is configured with a general dialogue engine for generating open-domain dialogue when the text is diverted to the green general path.
[0043] The state coordination bus is connected to the routing agent, the red path processing module, the yellow path processing module, and the green path processing module respectively. It is used to maintain a unified session state object and realize parameter pass-through and collaborative work among multiple modules.
[0044] Preferably, it further includes a dynamic adjustment unit for intervention parameters, connected to the yellow path processing module, for:
[0045] Real-time collection of user feedback data on the previous round of system responses; calculation of a quantitative score reflecting user acceptance based on the feedback data; the acceptance score includes at least one or more of the following: response length change rate and positive word proportion.
[0046] When the acceptance score continuously declines and the decline exceeds a preset threshold, the set of intervention parameters is automatically adjusted. The set of intervention parameters includes at least guidance intensity, empathy level, and topic focus.
[0047] The adjustment operations include: reducing the guidance intensity value and increasing the empathy level value, so as to achieve a smooth transition of the system from the cognitive restructuring mode to the emotional acceptance mode.
[0048] Preferably, the system is deployed based on a layered architecture:
[0049] The orchestration layer is built using a visual workflow orchestration framework and is used to undertake the central function of the system. It encapsulates the routing agent, red path processing module, yellow path processing module and green path processing module as independent visual nodes, and realizes the orchestration of data flow and control flow between nodes through a directed acyclic graph.
[0050] The inference layer is built using a localized model inference framework to undertake the functions of the localized inference engine. It deploys a quantized large language model, ensuring that user privacy data does not flow to the public cloud through localized deployment, and achieves low-latency inference response with limited hardware resources through model quantization technology.
[0051] This invention provides a psychological intervention method and system based on dynamic intent routing and thought chain reasoning, which has the following beneficial effects: Through the collaborative innovation of dynamic intent routing and thought chain reasoning, significant technological breakthroughs have been achieved in four core dimensions of psychological intervention: safety, professionalism, response efficiency, and privacy protection. In terms of safety, the system adopts a dual-track detection mechanism and a three-level mandatory early warning architecture, realizing complementary verification at the semantic and keyword levels, significantly improving the recall rate. Once a red alert is triggered, the system can quickly complete three levels of intervention actions: instruction truncation, interface redirection, and status marking, completely eliminating the security risks of traditional AI's slow response or inappropriate output in crisis scenarios from an architectural perspective.
[0052] The psychological intervention process is broken down into multiple logical operators, such as identifying cognitive distortion, emotional mirroring, and cognitive restructuring, through a thought chain reasoning engine. This guides the large language model to reason step-by-step according to a professional paradigm. Simultaneously, a dynamic parameter adjustment mechanism based on user feedback enables adaptive adjustment of guidance intensity and empathy level, ensuring real-time matching between intervention strategies and user states.
[0053] Furthermore, this invention places the intent routing module at the edge gateway to achieve millisecond-level traffic splitting decisions; it implements a modular architecture through Dify workflow orchestration, giving the system high interpretability and scalability; and combined with Ollam localized deployment, all sensitive data is processed on the edge, fundamentally ensuring user privacy and security. Attached Figure Description
[0054] To more clearly illustrate the technical solutions in this invention or the prior art, the accompanying drawings used in the description of this invention or the prior art will be briefly introduced below.
[0055] Figure 1 Overall structural diagram of the psychological intervention system of this invention;
[0056] Figure 2 A flowchart illustrating the psychological intervention method of this invention;
[0057] Figure 3 Schematic diagram of the dual-track detection mechanism in this invention;
[0058] Figure 4 Internal logic diagram of the thought chain reasoning engine in this invention;
[0059] Figure 5 Flowchart of the dynamic parameter adjustment mechanism in this invention. Detailed Implementation
[0060] To make the objectives, technical solutions, and advantages of the present invention clearer, the technical solutions of the present invention will be clearly and completely described below with reference to the accompanying drawings.
[0061] Example 1, as Figures 1 to 5 As shown, this embodiment provides a psychological intervention system based on dynamic intent routing and thought chain reasoning. It adopts a layered architecture design, which includes, from top to bottom: input layer, routing layer, processing layer, collaboration layer and deployment layer.
[0062] The input layer is responsible for receiving raw text input from users. Users can input natural language text through web pages, mobile applications, or instant messaging interfaces. The input layer performs preliminary preprocessing on the raw text, including text cleaning, simplified / traditional character conversion, and emoji conversion, to generate standardized input text, which is then passed to the routing layer.
[0063] The routing layer deploys a routing agent, serving as the system's first line of defense. It operates independently of the subsequent large language model inference process, ensuring millisecond-level response times. The routing agent is deployed at the system input end and internally configured with a dual-track detection engine. This engine performs parallel feature scanning on the user-inputted text and, based on a preset sentiment rating model and crisis threshold matrix, routes the text in real-time to one of three paths: a red warning path, a yellow intervention path, or a green general path. The dual-track detection engine specifically includes:
[0064] The first detection track (semantic similarity calculation track): The input text is vectorized using a lightweight BERT-based prediction model. The system pre-constructs a psychological crisis vector space, which is formed by clustering a large number of crisis texts labeled as "high risk," "self-harm," "suicide," etc., after being encoded using the same BERT-based model. The cosine similarity is calculated between the encoded vector of the current input text and the central vector in the psychological crisis vector space, outputting a semantic similarity score between 0 and 1. The higher the score, the closer the text is to known crisis texts in the semantic space.
[0065] The second detection track (sensitive word matching track): This track utilizes a high-performance sensitive word filtering operator built upon the Aho-Corasick algorithm. The system pre-establishes a high-risk intent word library, containing core intent words such as "want to die," "despair," "life is meaningless," and "end everything," along with their variations. Different immediate risk weights are assigned to each word or phrase (e.g., "want to die" weight 0.8, "despair" weight 0.6). The Aho-Corasick algorithm can match all keywords in parallel in a single scan, with time complexity linearly related to text length, achieving microsecond-level high-efficiency matching. This track outputs a list of high-risk intent word hits and the weight value of each hit word.
[0066] The fusion decision unit connects the first and second probe tracks, receiving semantic similarity scores and an instantaneous risk weight list. Based on a preset threshold judgment matrix, the fusion decision unit makes a comprehensive decision, generating the final routing decision signal.
[0067] The processing layer contains three parallel processing paths, each corresponding to a different user intent type.
[0068] Red Path Processing Module: Connected to the routing agent, it is equipped with a forced warning interruption engine. When the text is diverted to the red warning path, it sends an interruption signal to the large language model inference instance, forces the user interface to switch to the emergency help interface, and marks the corresponding user status as high-risk in the background database.
[0069] Yellow Path Processing Module: Connected to the routing agent, this module is equipped with a thought chain inference engine and is activated upon receiving a yellow intervention signal. The thought chain inference engine is built upon a directed acyclic graph workflow engine, visually arranging multiple logical operator nodes to guide the large language model in executing inference according to a pre-defined psychological counseling logic sequence.
[0070] In this embodiment, an intervention parameter dynamic adjustment unit is also included, connected to the yellow path processing module, for real-time collection of user feedback data on the previous round of system responses, and calculation of a quantitative score reflecting the user's acceptance level based on the feedback data. The acceptance score includes at least one or more of the response length change rate and the proportion of positive words. When the acceptance score continuously decreases and the decrease exceeds a preset threshold, the intervention parameter set is automatically adjusted. The intervention parameter set includes at least guidance intensity, empathy level, and topic focus. The adjustment operation includes: reducing the guidance intensity value and increasing the empathy level value, so as to achieve a smooth transition of the system from a cognitive restructuring mode to an emotional acceptance mode.
[0071] Green Path Processing Module: Connected to the routing agent, it is activated upon receiving a green universal signal. This module is equipped with a universal dialogue engine, employing a universal large language model for open-domain dialogue generation.
[0072] The modules in the processing layer communicate with each other through a state coordination bus. The state coordination bus maintains a unified session state object in JSON format, which can be read and written by each processing module, enabling parameter pass-through and multi-module collaboration.
[0073] The system adopts a layered deployment architecture:
[0074] Orchestration Layer: Built using a visual workflow orchestration framework (such as Dify), this layer serves as the central hub of the system. The routing agents and path processing modules described above are encapsulated as independent visual nodes, and data and control flow orchestration between nodes is achieved through a directed acyclic graph.
[0075] Inference Layer: Built using a localized model inference framework (such as Ollama), this layer functions as the localized inference engine. It deploys a large language model quantized using GPTQ or AWQ algorithms (such as Llama-3-8B-Instruct-quantized), reducing GPU memory usage while maintaining inference capabilities. All user data is processed locally on servers or at the edge, without flowing to the public cloud, fundamentally ensuring user privacy and security.
[0076] Example 2, as Figures 2 to 5 As shown, based on the system described in Embodiment 1, this embodiment provides a psychological intervention method based on dynamic intent routing and thought chain reasoning. The method is applied to a server or terminal device deployed with a psychological intervention system. The method of this embodiment includes the following steps:
[0077] S1: Receives the raw text input by the user and performs millisecond-level feature scanning through a dual-track detection mechanism.
[0078] The system receives raw text T input by the user through a client (such as a mobile app, web chat window, etc.). This text is received in real time and sent to the routing agent. The routing agent is equipped with a dual-track detection engine, which executes the following sub-steps in parallel:
[0079] S11: Semantic Vectorization Classification Based on BERT-base Model
[0080] The routing agent invokes a lightweight BERT-based Chinese pre-trained model (or selects the appropriate language model based on the user's language) to vectorize the input raw text T, obtaining a 768-dimensional text vector. The system pre-constructs a psychological crisis vector space, which is obtained by collecting a large amount of labeled psychological crisis-related text and calculating its vector mean to obtain multiple cluster center vectors. The routing agent calculates the current text vector. With each cluster center vector cosine similarity The maximum value is taken as the semantic similarity score. This indicates a high semantic similarity to crisis text. Simultaneously, the system incorporates a lightweight sentiment classification model (which can be fine-tuned based on BERT) to score the negative sentiment intensity of the original text T, outputting a sentiment tendency score for the text (denoted as ). (Value range: 0-1).
[0081] S12: High-performance sensitive word matching based on the Aho-Corasick algorithm
[0082] The routing agent loads a pre-compiled high-risk intent lexicon containing thousands of words and phrases related to suicide, self-harm, and despair, assigning a risk weight (0-1) to each term. The system employs the Aho-Corasick automaton algorithm for multi-pattern parallel matching of the original text, enabling it to find all matched high-risk terms in O(n) time complexity. Subsequently, it calculates the instantaneous risk weight total score (denoted as ) based on the risk weights of the matched terms. The calculation formula is: ;in λ is the weighting factor (0 < λ < 1).
[0083] S2: Fusion Decision and Routing
[0084] The routing agent will use the above three metrics ( , , Input a preset threshold judgment matrix, and perform real-time data splitting according to the following rules:
[0085] Red Alert Path Triggering Conditions: If any of the following conditions are met, a red alert will be issued, and traffic will be diverted to a red alert path:
[0086] Condition A: and ;
[0087] Condition B: (A preset safe water level threshold is provided, which can be calibrated based on actual data.)
[0088] Condition C: If an "absolutely high-risk word" (such as "suicide method" or "die immediately") is hit in the word library, the red warning path will be triggered directly, and the threshold calculation will be skipped.
[0089] Yellow Path Triggering Conditions: If a red alert path is triggered, but any of the following conditions are met, traffic will be diverted to the yellow intervention path:
[0090] Condition D: Furthermore, the text contains keywords related to cognitive bias (such as "always", "everyone", "forever" etc.).
[0091] Condition E: The similarity with a certain cognitive bias vector cluster is >0.7;
[0092] Condition F: The user's historical status is marked as "high risk" or "recovery period", requiring professional intervention.
[0093] Green path triggering conditions: If all the above conditions are not met, the user will be redirected to the green path and enter the general dialogue module.
[0094] The entire traffic splitting decision is completed within 100ms, ensuring a smooth user experience. The decision result (path identifier), along with the original text and feature metrics, is encapsulated into a JSON-formatted session state object and passed to subsequent modules.
[0095] S3: If traffic is diverted to a red alert path, a mandatory alert interruption procedure will be triggered.
[0096] When the routing agent outputs a red warning path identifier, the system immediately enters the red path processing module, which performs the following three levels of system intervention:
[0097] Level 1 Action: Command Truncation. The red path processing module sends an emergency stop signal (STOP) to the currently running large language model instance, forcibly halting any ongoing token generation process. Specifically, a global flag is set within the model inference loop. Upon receiving the stop signal, the generation loop immediately exits, discarding any generated but not yet output content. This operation ensures that, in crisis scenarios, the system will not output any inappropriate responses that might exacerbate the user's sense of urgency.
[0098] Level Two Action: Safety Redirection. The red path processing module, through a front-end interface call, forcibly switches the user's client's dialog interface to a preset emergency help interface. This interface no longer displays ordinary dialog input boxes, but instead highlights the following: 24-hour national psychological assistance hotline (e.g., "Hope 24 Hotline: 400-161-9995"); a one-click dial button; emergency self-rescue instructions (e.g., "Please contact professional help immediately; you are not alone"); and recommendations for local emergency medical centers (based on user IP location).
[0099] At the same time, the system automatically sends a preset reassurance message (such as "I notice you may be going through a very difficult time, please allow me to connect you with professional assistance..."), but no longer allows users to continue typing, to avoid AI generating risky content (users cannot continue to send ordinary messages through this interface, they can only click confirmation buttons such as "I understand" or call the hotline directly).
[0100] Level 3 Action: Status Marking. The red path processing module synchronously updates the user's session status in the background database, marking the user_status field as "high risk" and recording the trigger time and reason. Simultaneously, the system sets a 24-hour access restriction window for this user. Within this window, if the user initiates a conversation again, the routing agent will forcibly redirect all their input to the red warning path or yellow intervention path, restricting their access to only the preset red or yellow path processing modules (e.g., displaying the emergency help interface again), and prohibiting them from entering the open domain of the green path, ensuring the continuity and security of the intervention. This status will last for 24 hours, or until manually lifted by a human reviewer in the background.
[0101] S4: If the patient is diverted to the yellow intervention path, activate the thought chain reasoning engine to generate an intervention strategy.
[0102] When the routing agent outputs a yellow intervention path marker, the system passes the current session state object to the yellow path processing module. This module is built on the Dify workflow engine and internally uses a directed acyclic graph to orchestrate multiple logical operator nodes, which are executed sequentially according to preset inference steps.
[0103] S31: Initialize the inference context
[0104] The yellow path processing module receives a session state object, which includes: session_id, user_id, raw text, neg_score, intent label (such as "yellow"), and user profile information loaded from the historical database (such as past cognitive distortion types, intervention records, etc.). All information is integrated into a JSON-formatted state object (StateObject), which is passed between workflow nodes. Each node reads the required fields, processes them, and updates the corresponding fields.
[0105] S32: Identifying Cognitive Distortion Operators
[0106] The workflow first invokes the "Identify Cognitive Distortions" operator node. This node is configured with classification prompt word templates based on the ABC model, employing a four-part structure of role-task-logic-output to guide the large language model in structured analysis. The large language model (e.g., Qwen2.5-7B-Instruct, locally deployed on Ollama) outputs structured XML results based on the prompt word requirements. The yellow path processing module parses this XML and writes the list of cognitive distortion types into the `cognitive_distortion` field of the state object.
[0107] S33: Emotion Mirror Operator
[0108] The workflow invokes the "Emotional Mirroring" operator node, which scores the user's current emotional state. Based on the identified cognitive distortion type, an empathetic response is generated. This operator is also based on cue word templates, requiring the model to respond to the user's emotions in a gentle, accepting tone and simply restate the user's feelings. For example, it might generate: "It sounds like you're very frustrated and disappointed because you failed this exam, and you're even starting to doubt your future. That must be a very heavy feeling."
[0109] The response is not output directly to the user, but is passed to subsequent nodes as part of the context to maintain the continuity of the conversation.
[0110] S34: Cognitive Reorganization Operator
[0111] The workflow invokes the "Cognitive Restructuring" operator node, which retrieves the corresponding CBT intervention prompts from the vector database based on the distortion type in the `cognitive_distortion` field. The vector database pre-stores a large number of cognitive restructuring scripts, Socratic questioning examples, behavioral experiment suggestions, etc., and is indexed according to the cognitive distortion type.
[0112] For example, for the "overgeneralization" distortion, the retrieved introductory text might include:
[0113] "Is it too absolute to conclude that 'my life is over' based on failing one exam? Are there any other possibilities?"
[0114] "Let's take a look at what aspects of your life have gone smoothly, besides failing an exam? How do these facts affect your perspective on 'a lifetime'?"
[0115] The search results, along with the original input and the sentiment mirror response, are assembled into new prompt words. The large language model is then invoked again, requiring it to integrate the above information and generate an intervention script that conforms to the principles of CBT (Conditional Training). The prompt word template emphasizes "step-by-step guidance, avoiding direct preaching." The model output is the final intervention response.
[0116] S35: Update intervention parameters
[0117] After generating a response, the yellow path processing module dynamically adjusts intervention parameters based on the characteristics of the user's input (such as emotional intensity and the number of distortion types), writing these parameters to the `intervention_params` field of the state object for use in the next round of dialogue. The adjustment rules include:
[0118] like If empathy level is increased by 0.1, guidance intensity is decreased by 0.1.
[0119] If multiple distortion types are identified, increase guidance_intensity appropriately;
[0120] If a user repeatedly refuses guidance in the past conversation, reduce guidance_intensity and maintain high empathy.
[0121] S5: If traffic is redirected to the green path, the general dialogue engine will be invoked.
[0122] When the routing agent outputs a green path marker, the system forwards the user input to the general dialogue module. This module uses a lightweight generative model or a retrieval-based dialogue system to handle non-professional scenarios such as casual conversation and simple emotional support. The general dialogue does not involve psychological intervention logic, but it records the dialogue content for subsequent user profile updates.
[0123] S6: Maintain session state via the state coordination bus
[0124] Throughout the processing of all the above paths, the state coordination bus maintains the consistency and synchronization of the session state object. Each time a module completes processing, it writes the updated state object back to the bus for other modules (such as the routing agent in subsequent rounds) to read. The state object also records the user's feedback on the previous round's response (such as whether to continue the dialogue, response length, percentage of positive words, etc.), serving as the basis for adjusting intervention parameters in the next round.
[0125] S7: Dynamic adjustment mechanism for intervention parameters (ongoing)
[0126] After each round of dialogue, the system analyzes the user's acceptance score of the system's response and adjusts the intervention parameters in real time. Specifically, the following operations are performed:
[0127] S71: Collect Feedback Data: Collect user feedback data in real time to the previous system response, including:
[0128] Length of user's response in this round ;
[0129] Average response length of users in history ;
[0130] The percentage of positive words in users' responses this round (Based on sentiment dictionary calculation);
[0131] The percentage of negative words in users' responses this round .
[0132] S72: Calculate the acceptance score: Calculate the acceptance score based on the above data. :
[0133] Rate of change of recovery length ;like This indicates that users are willing to express themselves and have a high level of acceptance.
[0134] Emotional offset ;like This indicates that the user's mood has improved.
[0135] Overall Score , where α, β, and γ are preset weight coefficients, which can be preset or optimized through reinforcement learning (e.g., α=0.4, β=0.6).
[0136] S73: If two consecutive rounds If the price decreases and the decrease exceeds a threshold (e.g., 20%), the system will automatically trigger an intervention parameter adjustment.
[0137] Guidance intensity: Reduces the current value of guidance_intensity by 20%, but not below the minimum value of 0.3;
[0138] Empathy level: Increase the current value of empathy_level by 20%, but not higher than the maximum value of 0.9;
[0139] Focus of the topic: Switching from "cognitive restructuring mode" to "emotional reception mode" to receive emotions.
[0140] If multiple rounds If the condition improves, the intensity of guidance can be gradually restored, and cognitive restructuring can be attempted.
[0141] S74: Parameters Take Effect: The adjusted parameters are written to the session state object, affecting the behavior of the emotional mirroring operator and the cognitive restructuring operator in the next round of dialogue. For example, in the "emotional reception mode," the system will reduce cognitive restructuring questions and use more empathetic and listening responses.
[0142] This embodiment underwent comparative testing in actual deployment, and the results are as follows:
[0143] Crisis identification accuracy: On a test set of 5,000 entries containing high-risk intent, the recall rate of red alert paths reached 98.5%, and the false alarm rate was less than 0.5%.
[0144] First response time: The average first response time (from user input to interface switching) for the red alert path is 120ms, for the yellow intervention path it is 850ms (including inference time), and for the green path it is 300ms.
[0145] Intervention logical coherence: Ten psychological counselors were invited to conduct blind evaluations of 50 sets of dialogues using the CBT professional rating scale (1-5 points). The average score in this embodiment was 4.2 points, while the baseline general model score was 3.0 points, an improvement of 40%.
[0146] This invention constructs a multi-level crisis detection and response system through a dynamic intent routing mechanism, fundamentally solving the security risks of slow response or even missed reporting in traditional psychological intervention systems under extreme circumstances.
[0147] Traditional solutions often rely on a single model for intent classification, resulting in a high false negative rate in crisis text recognition. This invention employs a dual-track detection mechanism combining "BERT-based semantic vectorization classification" and "Aho-Corasick sensitive word filtering," achieving complementary verification at the semantic and keyword levels. Semantic vectorization can identify expressions like "I want to end this" that, while not containing explicit high-risk words, convey a crisis intent, while sensitive word filtering accurately captures specific behavioral descriptions. The combination of these two approaches significantly improves the recall rate.
[0148] Furthermore, traditional systems typically only output pre-set scripts after identifying a crisis, failing to intervene in the model generation process and posing a risk of outputting inappropriate content. This invention designs a three-tiered system intervention mechanism: "instruction truncation—interface redirection—status marking," constructing a complete crisis intervention closed loop. The instruction truncation mechanism sends an interrupt signal to the large language model in the process of generation within milliseconds, forcibly halting token generation. The security redirection mechanism forcibly switches the user interface to an emergency help interface, ensuring users can access professional assistance channels immediately during a crisis. The status marking mechanism marks users as "high-risk" at the database level and sets a 24-hour access restriction window. This mechanism enables continuous tracking across sessions, ensuring users cannot access open-domain conversations during the sensitive period after a crisis and can only receive professional guidance, effectively preventing secondary risks.
[0149] This invention establishes a refined risk quantification model, including multiple dimensions such as continuous emotional tendency values, semantic similarity scores, and real-time risk weights. By setting dual verification standards and weighted algorithms, the system can perform refined triage of user inputs at different risk levels, accurately distinguishing between "ordinary emotional venting—cognitive bias expression—emergency crisis help," thus laying a technical foundation for subsequent differentiated interventions.
[0150] This invention, through a thought chain reasoning engine and workflow orchestration technology, guides a large language model to reason according to the logical steps of professional psychological intervention, significantly improving the quality and credibility of the generated content. Traditional general-purpose models employ an end-to-end generation method, where the reasoning process is invisible and uncontrollable. This invention decomposes the psychological intervention process into multiple logical operators, such as "identifying cognitive distortion—emotional mirroring—cognitive restructuring," with each operator designed with a specific prompt word template, requiring the model to output structured intermediate results. This design produces the following technical effects:
[0151] The reasoning process is traceable: the system can record intermediate information such as the type of cognitive distortion, confidence score, and original text basis identified in each round of intervention, providing complete data support for subsequent intervention strategy adjustments and manual review.
[0152] Controllable output quality: Through step-by-step guidance, the model follows a preset logical framework at each step, avoiding the drawbacks of traditional models such as "skipping steps in reasoning" or "direct preaching".
[0153] Precise knowledge retrieval: The cognitive restructuring operator accurately retrieves the corresponding CBT intervention prompts from the vector database based on the identified cognitive distortion type, ensuring the accurate retrieval of professional knowledge and avoiding the "misattribution" errors that may occur in general models.
[0154] Furthermore, this invention maintains a unified session state object through a state collaboration bus, enabling parameter pass-through and state updates between multiple rounds of dialogue. Unlike the "fragmented retrieval" processing method in existing technologies, the state object of this invention includes information such as the user's historical cognitive distortion type, intervention parameters, and emotional change trajectory. This allows for tracking the cognitive patterns exhibited by the user in different sessions, providing a data foundation for personalized intervention. Moreover, the intervention parameters (guidance intensity, empathy level) are smoothly adjusted between dialogue rounds, avoiding the abruptness of traditional systems where "one round is deeply guided, the next round becomes casual conversation," ensuring the continuity of the intervention process.
[0155] This invention designs a dynamic adjustment mechanism for intervention parameters based on user acceptance scores. The system analyzes user feedback on the previous round of responses in real time (response length, percentage of positive words, etc.), calculates the acceptance score, and automatically adjusts the guidance intensity and empathy level accordingly. When users show resistance (acceptance scores continuously decline), the system automatically reduces the guidance intensity and increases the empathy factor, switching from a "cognitive restructuring mode" to an "emotional connection mode," avoiding user churn caused by forced guidance. Furthermore, different users have different levels of acceptance of intervention intensity; the dynamic adjustment mechanism can adaptively find the most suitable combination of intervention parameters for the current user, achieving the optimal balance point for individualized intervention.
[0156] Traditional systems typically couple intent recognition with content generation, resulting in initial response time limited by the speed of large model generation. This invention deploys a dynamic intent routing module at the forefront of the Dify workflow, running independently as an edge gateway layer. It employs an asynchronous concurrent mechanism for feature scanning, completing routing decisions without waiting for the main model to be generated. In the feature scanning phase, this invention uses a lightweight BERT-based model (110M parameters) instead of directly calling a large language model (7B or more parameters), significantly reducing computational overhead. Simultaneously, the inference layer uses quantization techniques from the Ollam framework, quantizing the large language model to 4-bit or 8-bit, reducing GPU memory usage by approximately 70% while maintaining generation quality.
[0157] This invention utilizes the Dify workflow engine to build a modular architecture, encapsulating complex psychological intervention processes into visual nodes. Through the visual orchestration of directed acyclic graphs, system developers can intuitively see the data flow path, the input and output of each node, and the transmission process of state objects. When abnormal behavior occurs in the system, specific nodes can be quickly located for debugging, significantly reducing the maintenance cost of complex AI systems. Each logical operator node (identifying cognitive distortion, emotional mirroring, and cognitive restructuring) is encapsulated as an independent module, allowing for rapid orchestration of new intervention processes via drag-and-drop. For example, to add a "behavioral activation" intervention module, simply add an operator node and insert it into the workflow; no modification to other module code is required.
[0158] The above embodiments are only used to illustrate the technical solutions of the present invention, and are not intended to limit it. Although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that modifications can still be made to the technical solutions described in the foregoing embodiments, or equivalent substitutions can be made to some of the technical features. Such modifications or substitutions do not cause the essence of the corresponding technical solutions to deviate from the spirit and scope of the technical solutions of the embodiments of the present invention.
Claims
1. A psychological intervention method based on dynamic intention routing and thought chain reasoning, characterized in that: Includes the following steps: S1: Receives the original text input by the user, performs millisecond-level feature scanning on the original text through a dual-track detection mechanism consisting of a semantic similarity calculation model and a sensitive word matching algorithm, and generates a sentiment tendency score and crisis risk weight. S2: Input the emotional tendency score and crisis risk weight into the preset threshold judgment matrix, and according to the judgment result, the original text is diverted in real time to one of the red warning path, yellow intervention path or green general path; S3: If the traffic is diverted to the red warning path, the forced warning interruption procedure will be triggered, and three levels of system intervention actions will be performed: instruction truncation, interface redirection, and status marking. S4: If the patient is diverted to the yellow intervention path, the thought chain reasoning engine will be activated. Following the preset psychological counseling logic sequence, the cognitive distortion operator, emotional mirroring operator, and cognitive reorganization operator will be called in sequence to drive the large language model to generate step-by-step, traceable psychological intervention strategies. S5: If the traffic is diverted to the green universal path, the universal dialogue engine will be invoked to generate open domain dialogue; S6: Based on the user's feedback to the previous round of responses, calculate the acceptance score, and dynamically adjust the intervention parameters, including guidance intensity and empathy level, according to the acceptance score. S7: Based on the adjusted intervention parameters, output the final psychological intervention script.
2. The psychological intervention method based on dynamic intention routing and thought chain reasoning according to claim 1, characterized in that: The dual-track detection mechanism in step S1 includes: The first detection track uses the BERT-base lightweight model to vectorize the original text, calculates the cosine similarity between the encoded text vector and the preset psychological crisis vector space, and outputs the semantic similarity score. The second probe track uses a high-performance sensitive word filtering operator built with the Aho-Corasick algorithm to perform multi-pattern parallel matching on the original text and output a list of high-risk intent words and real-time risk weights. The fusion decision unit, connected to the first and second probe tracks, is used to perform weighted fusion based on the semantic similarity score, sentiment tendency score, and immediate risk weight to generate the final routing decision signal.
3. The psychological intervention method based on dynamic intention routing and thought chain reasoning according to claim 1, characterized in that: The sentiment score uses a continuous value from 0 to 1, generated based on the confidence score of the negative sentiment intensity of the text using a large language model; the threshold judgment matrix includes a dual verification standard: First verification criterion: When the semantic similarity is greater than the first threshold and the sentiment score is greater than the second threshold, a red warning signal is automatically generated; The second verification standard is to use a weighted algorithm to calculate the real-time risk weight for words in the preset high-risk intent word library. When the sum of the real-time risk weights exceeds the preset safety level threshold, a red warning signal is automatically generated.
4. The psychological intervention method based on dynamic intention routing and thought chain reasoning according to claim 1, characterized in that: In step S3, the mandatory early warning interruption procedure includes the following three levels of system intervention actions: Level 1 action: Instruction interception, sending a STOP interrupt signal to the large language model instance that is currently performing the generation task, forcibly terminating the generation process of the current token sequence; The second level of action: safety redirection, which forcibly switches the user interface to the preset emergency help interface through the front-end interface call, and displays the 24-hour psychological assistance hotline and emergency guidance script on the interface. Level 3 action: Status marking. Synchronously mark the corresponding user's session status as high-risk in the background database, and restrict the user to access only the professional guidance functions in the preset red path processing module or yellow path processing module within a preset time window, and prohibit them from entering the open domain dialogue of the green path.
5. A psychological intervention method based on dynamic intention routing and thought chain reasoning according to claim 1, characterized in that: In step S4, the thought chain reasoning engine is built on a workflow engine based on a directed acyclic graph, and uses a directed acyclic graph to visualize and orchestrate multiple logical operator nodes. The logical operator node includes at least: The cognitive distortion operator is configured with classification prompt word templates based on the ABC model and few-shot learning examples to identify and classify irrational beliefs in user discourse and output structured cognitive distortion type labels. The Emotion Mirroring Operator is used to generate empathetic response templates based on the user's emotional state. A cognitive restructuring operator is used to retrieve and call up corresponding cognitive restructuring guidance instructions from a psychology knowledge base based on the cognitive distortion type label, and generate an intervention strategy. Data and parameters are passed between logical operator nodes through JSON-formatted session state objects.
6. A psychological intervention method based on dynamic intention routing and thought chain reasoning as described in claim 5, characterized in that: The prompt word template for recognizing cognitive distortion operators includes: The Role field is used to set the role of the large language model as a professional psychological tester. The Task field is used to instruct the large language model to identify logical fallacies in user speech and match them with preset standard cognitive distortion types. The Logic field indicates that the large language model follows the ABC model, with a focus on identifying irrational components in belief B. The Output field is used to instruct the large language model to convert the recognition results into a preset structured data format, which includes cognitive distortion type labels, confidence scores, and original text reference fragments.
7. A psychological intervention system based on dynamic intention routing and thought chain reasoning, characterized in that: include: The routing agent, deployed at the system input end, is equipped with a dual-track detection engine to perform parallel feature scanning on the original text input by the user. Based on the preset sentiment tendency scoring model and crisis threshold matrix, the text is diverted in real time to one of the red warning path, yellow intervention path, or green general path. The red path processing module is connected to the routing agent and is equipped with a forced warning interruption engine. When the text is diverted to the red warning path, it sends an interruption signal to the large language model inference instance, forces the user interface to switch to the emergency help interface, and marks the corresponding user status as high-risk in the background database. The yellow path processing module is connected to the routing agent and is equipped with a thought chain reasoning engine. The thought chain reasoning engine contains multiple serial logical operator nodes, which are used to guide the large language model to perform reasoning step by step according to the preset psychological intervention steps and generate a structured intervention strategy. The green path processing module is connected to the routing agent and is configured with a general dialogue engine for generating open-domain dialogue when the text is diverted to the green general path. The state coordination bus is connected to the routing agent, the red path processing module, the yellow path processing module, and the green path processing module respectively. It is used to maintain a unified session state object and realize parameter pass-through and collaborative work among multiple modules.
8. A psychological intervention system based on dynamic intention routing and thought chain reasoning according to claim 7, characterized in that: It also includes a dynamic adjustment unit for intervention parameters, connected to the yellow path processing module, for: Real-time collection of user feedback data on the previous round of system responses; calculation of an acceptance score reflecting the user's acceptance level based on the feedback data; the acceptance score includes at least one or more of the following: response length change rate and positive word ratio. When the acceptance score continuously declines and the decline exceeds a preset threshold, the set of intervention parameters is automatically adjusted. The set of intervention parameters includes at least guidance intensity, empathy level, and topic focus. The adjustment operations include: reducing the guidance intensity value and increasing the empathy level value, so as to achieve a smooth transition of the system from the cognitive restructuring mode to the emotional acceptance mode.
9. A psychological intervention system based on dynamic intention routing and thought chain reasoning according to claim 7, characterized in that: The system is deployed based on a layered architecture: The orchestration layer is built using a visual workflow orchestration framework and is used to undertake the central function of the system. It encapsulates the routing agent, red path processing module, yellow path processing module and green path processing module as independent visual nodes, and realizes the orchestration of data flow and control flow between nodes through a directed acyclic graph. The inference layer is built using a localized model inference framework to undertake the functions of the localized inference engine. It deploys a quantized large language model, ensuring that user privacy data does not flow to the public cloud through localized deployment, and achieves low-latency inference response with limited hardware resources through model quantization technology.