An electronic medical record automatic generation method and system based on agent hierarchical memory
By constructing an intelligent agent hierarchical memory architecture and a memory feedback learning closed loop, the problems of continuous generation and memory management of cross-visit medical records are solved, realizing the continuity, accuracy and traceability of medical records and meeting medical compliance requirements.
Patent Information
- Application Number
- CN202611698840.9
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-10-30
- Publication Date
- 2026-11-27
AI Technical Summary
Existing technologies cannot achieve continuous generation of medical records across different medical visits, lack dynamic memory management, lack a feedback-based memory correction mechanism, and lack traceability and hallucination suppression measures for generated medical record content.
A hierarchical memory architecture for intelligent agents is constructed, including a working memory layer, an episodic memory layer, and a long-term semantic memory layer, to realize the writing, retrieval, updating, forgetting, and consolidation of memories. Memory anchoring and consistency comparison are adopted, combined with source confidence grading and conflict resolution mechanisms, to construct a memory feedback learning closed loop.
It enables continuous generation of medical records across different medical visits, ensuring the real-time nature and security of the medical record memory, improving the accuracy and traceability of generated medical records, avoiding errors, omissions, and hallucinations, and meeting medical compliance requirements.
Smart Images

Figure CN123182886A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of software, and in particular to a method and system for automatically generating electronic medical records based on agent-based hierarchical memory. Background Technology
[0002] Electronic medical records are the core medium for medical institutions to record the entire process of patient diagnosis and treatment. Traditional methods of generating medical records mainly rely on manual input by doctors or voice transcription followed by manual proofreading, which has problems such as long writing time, non-standard format, and missing information.
[0003] In existing technologies, several solutions have emerged that apply large models or intelligent agents to medical document generation, mainly including the following technical approaches: (1) RAG-based medical record generation method. This method retrieves relevant text fragments from external knowledge bases or historical medical record databases and concatenates them into the prompts of a large model for generation. Its shortcomings are: RAG only performs static retrieval and does not maintain cross-session memory state, so it cannot use patients' historical medical information to generate continuous medical records; the ranking of retrieval results only considers text relevance and does not consider the timeliness and reliability of medical information sources.
[0004] (2) A medical record quality control method based on large model fine-tuning. This method improves the quality of generated data by fine-tuning the medical record corpus of the large model. Its shortcomings are: fine-tuning solidifies knowledge in the model parameters, making it impossible to maintain dynamic memory for individual patients. Each generation is an independent single reasoning and does not have the ability to connect memories across medical visits.
[0005] (3) Medical record generation method based on speech transcription. This method transcribes the doctor-patient dialogue into text and then organizes it into a medical record using a large model. Its shortcomings are: it only processes the current conversation information and lacks the memory and utilization of long-term information such as the patient's historical condition, medication history, and allergy history.
[0006] (4) Agent-based EMR data governance method. This method introduces an agent mechanism to perform data governance on existing EMRs, but does not build a hierarchical memory architecture, nor is it used for medical record generation scenarios.
[0007] (5) Some existing general-purpose intelligent agent memory schemes adopt a three-layer memory architecture of "historical dialogue layer - structured event layer - pattern induction layer" or a three-level storage of "task memory - dialogue memory - state memory". However, the above schemes are all designed for general dialogue scenarios and have the following inherent defects that are not compatible with medical scenarios: First, the memory content is general text and is not coded and normalized according to medical terminology standards, and different expressions of the same disease cannot be associated; Second, the reliability of the source of medical information is not distinguished, and the patient's oral account and test report are treated equally; Third, the forgetting mechanism adopts a uniform time decay, which may lead to the erroneous forgetting of safety-critical information such as allergy history; Fourth, no memory anchoring and verification mechanism is provided for the hallucination problem generated by medical records.
[0008] (6) Although existing intelligent agent solutions for medical document generation have introduced large model intelligent agents, they have not built a hierarchical memory architecture, have not realized memory lifecycle management, and have not introduced a memory feedback learning mechanism. As a result, the generated medical records are still insufficient in terms of continuity, personalization and accuracy.
[0009] In summary, the existing technology has the following technical problems: First, it cannot achieve continuous generation of medical records across different medical visits. The existing solution generates each medical record independently, without maintaining the patient's historical medical records, resulting in the inability to reflect the evolution of the condition, medication adjustments, and trends in test results between different medical visits in the medical records.
[0010] Second, the medical record generation process lacks dynamic memory management. Existing solutions do not have the ability to manage the lifecycle of memory, including writing, retrieving, updating, forgetting, and consolidating. Furthermore, the general forgetting mechanism is not adapted to the differences in the importance of medical information, posing a risk of mistakenly forgetting safety-critical information.
[0011] Third, there is a lack of a feedback-based memory correction mechanism. After doctors modify the medical records generated by the existing system, the modified information cannot be written back to the memory bank to optimize subsequent generation strategies, leading to the repeated occurrence of the same errors.
[0012] Fourth, the medical records generated by large models lack traceability and hallucination suppression mechanisms. There is no anchoring relationship between the generated content and the actual source of memory, making it difficult to systematically detect and intercept erroneous statements. Summary of the Invention
[0013] To address the aforementioned technical problems, this invention provides an automatic electronic medical record generation method based on agent-level hierarchical memory, comprising: A hierarchical memory architecture for intelligent agents is constructed, comprising a working memory layer, a contextual memory layer, and a long-term semantic memory layer. The working memory layer is used to store real-time interaction information in the current medical session, the contextual memory layer is used to store historical medical records according to medical events, and the long-term semantic memory layer is used to store patient-level semantic knowledge after induction and abstraction. When a request to generate a medical record for the current visit is received, the real-time interaction information of the current session is extracted from the working memory layer, historical medical records related to the current visit are retrieved from the context memory layer, and patient-level semantic knowledge is retrieved from the long-term semantic memory layer. The three-layer retrieval results are then merged and sorted to form a memory-enhanced context. Based on the memory enhancement context and current medical information, the large language model is invoked to generate an electronic medical record draft field by field according to the preset medical record structure template. After each field is generated, the generation result of the field is written back to the working memory layer. When each field is generated, the memory anchor point identifier on which the generated content is based is output synchronously, and the key medical data in the generated content is compared with the corresponding data in the anchored memory entry. Key medical data statements that cannot be anchored to any memory entry and do not belong to the newly entered information of this medical visit are marked as items to be confirmed by the doctor. The key medical record information confirmed by the doctor during this visit is written into the contextual memory layer as a new visit event, and the patient-level semantic knowledge in the long-term semantic memory layer is updated based on the new diagnosis, medication adjustment and abnormal test results of this visit.
[0014] As a technical solution of the present invention, each historical medical record in the context memory layer is stored in the form of a quintuple of (visit time, treatment event, key medical entity, source identifier, and memory confidence level); the key medical entity is stored in a dual form of standard terminology encoding and original expression, wherein the standard terminology encoding includes the ICD-10 code corresponding to the diagnosis, the LOINC code corresponding to the test item, and the ATC code corresponding to the drug; the memory confidence level is determined by the information source type according to a preset source confidence level mapping, wherein the memory confidence level corresponding to the test or examination report type, the doctor's structured input, the doctor's oral transcription, and the patient's oral statement decreases in that order.
[0015] As a technical solution of the present invention, the retrieval of historical medical records related to the current medical visit in the context memory layer adopts a two-factor weighted retrieval strategy. The retrieval score of the memory entry is calculated by the following formula: Score(m)=α·Sim(e_q,e_m)+(1-α)·exp(-λ·Δt_m); where e_q is the query entity embedding vector obtained by medical entity recognition and terminology encoding of the current complaint, e_m is the embedding vector of key medical entities in the memory entry, Sim is the cosine similarity, Δt_m is the time interval between the memory entry time and the current time, λ is the time decay coefficient, and α is the entity similarity weight factor, with a value range of 0.6 to 0.8; the top K entries are selected as the retrieval results in descending order of retrieval score.
[0016] As a technical solution of the present invention, the fusion sorting process further includes memory conflict resolution: conflict detection is performed on the three-layer retrieval results. When there are semantically conflicting memory entries, if the difference in memory confidence between the two memories is greater than a preset conflict judgment threshold, the memory with higher confidence is accepted and the memory with lower confidence is marked as pending verification. If the difference is not greater than the conflict judgment threshold, both conflicting memories are retained in the memory enhancement context and a conflict mark is added. The fusion sorting is performed as follows: the memory carrying the security mark is forced to the top, and the remaining memories are arranged in descending order according to the product of memory confidence and retrieval score. The memory fragments are routed and labeled according to the medical record field type, and the applicable medical record fields for each memory fragment are marked.
[0017] As a technical solution of the present invention, the contextual memory layer is equipped with a multi-factor forgetting function based on time decay and medical importance weight. The memory retention of a memory entry is calculated by the following formula: R(m)=exp(-λ·Δt)·W_med(m); where Δt is the time interval between the memory entry time and the current time, λ is the time decay coefficient, and W_med(m) is the medical importance weight, which is determined by the type of medical entity contained in the memory entry. Memory entries corresponding to allergy history, critical value records, and major diagnoses are marked as non-forgettable memories, and their memory retention is always 1.0, and they do not participate in the forgetting determination. When the memory retention of other memory entries is lower than the preset forgetting threshold, the corresponding memory entries are deleted or downgraded and migrated to the long-term semantic memory layer.
[0018] As a technical solution of the present invention, the working memory layer is provided with a capacity threshold. When the number of stored entries reaches the capacity threshold, a two-step hierarchical compression is performed: First, the retention value V(m) = γ1·U(m) + γ2·S(m) + γ3·I(m) is calculated for each working memory entry, where U(m) is the clinical urgency, S(m) is the safety marker, I(m) is the information measure, and γ1, γ2, and γ3 are weighting factors. Entries with a retention value lower than the discard threshold are directly discarded. Second, the active priority Pri(m) = β1·U(m) + β2·S(m) + β3·Rec(m) is calculated for the entries that pass the first step, where Rec(m) is the recency factor, and β1, β2, and β3 are weighting factors. Entries with an active priority lower than the active threshold are summarized, migrated to the context memory layer for archiving and storage, and deleted from the working memory layer.
[0019] As a technical solution of the present invention, the key medical data includes drug name and dosage, diagnostic code, test value and allergen; the consistency comparison also includes: intercepting key medical data that is inconsistent with the corresponding data in the anchored memory entry, and triggering the regeneration of the field or manual intervention.
[0020] As one technical solution of the present invention, it further includes a memory feedback learning step: receiving the doctor's modification operation on the electronic medical record draft, recording the text differences before and after the modification, the medical record fields corresponding to the modification location, and the memory anchor point identifier to which the modified content is anchored; locating the source memory entry in the memory bank according to the text differences and the memory anchor point identifier, and determining the modification type; if the modification type is fact correction, performing error correction update on the source memory entry, and updating the memory confidence of the entry to the confidence level of the doctor's input; if the modification type is supplementing missing information, writing the supplementary information as a new memory entry into the corresponding memory layer after entity recognition and terminology encoding; and updating the verification rules and prompt word weights in the medical record generation strategy according to the historical error correction records.
[0021] As one technical solution of the present invention, it further includes: performing de-identification processing on the entries written to the three-layer memory, replacing the patient's direct identifier with a hashed patient unique identifier; each memory entry carries source metadata including a visit identifier, a source document identifier, a write time, an original text position pointer, and a write method; when outputting electronic medical records or exporting memory content, performing field-level desensitization according to the role permissions of the output scenario; supporting backtracking from any field of the generated medical record through the memory anchor identifier to the source memory entry, and then backtracking to the original document through the source metadata.
[0022] This invention also provides an automatic electronic medical record generation system based on agent-level hierarchical memory, comprising: The hierarchical memory management module is used to build and maintain a working memory layer, a contextual memory layer, and a long-term semantic memory layer. The working memory layer is used to store real-time interactive information in the current medical session, the contextual memory layer is used to store historical medical records according to medical events, and the long-term semantic memory layer is used to store patient-level semantic knowledge after induction and abstraction. The memory retrieval fusion module is used to extract real-time interaction information of the current session from the working memory layer when a request to generate medical records for the current visit is received, retrieve historical medical records related to the current visit from the context memory layer, retrieve patient-level semantic knowledge from the long-term semantic memory layer, and fuse and sort the three-layer retrieval results to form a memory-enhanced context. The medical record generation module is used to generate an electronic medical record draft field by field according to a preset medical record structure template by calling a large language model based on the memory enhancement context and the current medical visit information. After each field is generated, the generation result of the field is written back to the working memory layer. The medical record generation module includes an anchoring output unit and a consistency verification unit. The anchoring output unit is used to output the memory anchor identifier on which the generated content of each field is based when each field is generated. The consistency verification unit is used to compare the key medical data in the generated content with the corresponding data in the anchored memory entries, and to mark key medical data statements that cannot be anchored to any memory entry and do not belong to the newly entered information of this medical visit as items to be confirmed by the doctor. The hierarchical memory management module is also used to write key medical record information confirmed by the doctor during this visit into the contextual memory layer as a new visit event, and to update the patient-level semantic knowledge in the long-term semantic memory layer based on the new diagnosis, medication adjustment and abnormal test results during this visit.
[0023] Compared with the prior art, the beneficial effects of the present invention are as follows: (1) Achieve continuous generation of medical records across medical visits. By storing historical medical events in the context memory layer and storing patient-level semantic knowledge in the long-term semantic memory layer, the agent can retrieve and utilize the patient's historical medical information when generating the current medical record, so that the medical record can reflect the evolution of the condition, medication adjustment and test result trend, thus solving the problem of medical record fragmentation caused by single independent reasoning in the existing scheme.
[0024] (2) Realize full life cycle management of memory. This invention constructs five life cycle stages of memory: writing, retrieval, updating, forgetting, and consolidation. The forgetting strategy is combined with medical importance weights to ensure that critical safety information such as allergy history is not mistakenly forgotten while maintaining the real-time nature of the memory bank, thus avoiding medical safety risks caused by the forgetting mechanism.
[0025] (3) Ensure the reliability of memory. By using source confidence grading and conflict resolution mechanisms, the reliability differences between test reports, doctor's data entry and patient's oral statements are distinguished. When there is a conflict between the patient's oral statement and the historical record, the confidence judgment or conflict marking is automatically executed to improve the factual accuracy of the generated medical records.
[0026] (4) Achieve suppression and traceability of generated hallucinations. By verifying the consistency of memory anchored output and key medical data, the system systematically intercepts fictitious key statements such as medication dosage and diagnosis; and by using the memory traceability chain, it achieves two-way traceability from generated content to original documents, meeting medical audit and compliance requirements.
[0027] (5) Achieve a closed-loop learning feedback mechanism. By capturing the doctor's modifications to the draft medical record, the source memory entry is automatically located and error correction and updates are performed. At the same time, the generation strategy is updated, so that the system can continuously self-optimize during use and avoid the recurrence of the same error.
[0028] (6) Achieve cross-expression association of medical terms. The memory stores the terms in both standard term codes and original expressions, so that different expressions such as "myocardial infarction" and "myocardial infarction", "complete blood count" and "complete blood cell count" can be automatically associated during retrieval, thereby improving the recall rate of memory retrieval and the standardization of medical terminology.
[0029] (7) Built-in medical privacy protection. De-identification is performed during the memory storage stage, and field-level de-identification is performed according to role permissions during the output stage to meet medical data compliance requirements. Attached Figure Description
[0030] Figure 1 This is an overall flowchart of the method of the present invention; Figure 2 A schematic diagram of a hierarchical memory architecture for intelligent agents; Figure 3 A flowchart illustrating the learning loop for memory feedback; Figure 4 This is a flowchart illustrating the process of memory anchoring and consistency verification. Detailed Implementation
[0031] The terms “first,” “second,” “third,” “fourth,” etc. (if present) in the specification, claims, and accompanying drawings of this invention are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence. It should be understood that such data can be interchanged where appropriate so that the embodiments described herein can be implemented in orders other than those illustrated or described herein. Furthermore, the terms “comprising” or “having,” and any variations thereof, are intended to cover a non-exclusive inclusion; for example, a process, method, system, product, or apparatus that comprises a series of steps or units is not necessarily limited to those steps or units explicitly listed, but may include other steps or units not explicitly listed or inherent to such processes, methods, products, or apparatus.
[0032] like Figure 1 The present invention provides an automatic electronic medical record generation method based on agent hierarchical memory, including steps S1 to S7.
[0033]
Step S1: Construct a hierarchical memory architecture for intelligent agents
[0034] S11 (Working Memory Layer): The working memory layer stores real-time interactive information from the current medical session, including the current chief complaint, fragments of present medical history, physical examination data, and immediate medical orders. The working memory layer has a capacity threshold N_max (preferably 50 entries). When the number of stored entries reaches the capacity threshold, a memory compression operation is triggered. The memory compression operation employs a two-step hierarchical processing strategy: Step 1, Retention Value Determination: Calculate the retention value V(m) for each working memory entry m, using the following formula: V(m) = γ1·U(m) + γ2·S(m) + γ3·I(m) Wherein, U(m) represents the clinical urgency level (e.g., 1.0 for emergency-related items such as chest pain and altered consciousness, and 0.3 for routine descriptions), S(m) represents the safety marker (1.0 for items involving allergies or critical values, and 0 otherwise), and I(m) represents the information measure (1.0 for items containing specific values or clear diagnoses, and 0.4 for vague descriptions); γ1, γ2, and γ3 are preset weighting factors that satisfy γ1+γ2+γ3=1, with system default values of γ1=0.35, γ2=0.40, and γ3=0.25; the default value of the discard threshold θ_d is 0.30, meaning that when V(m) < 0.30, the item is judged to have no medical value and is directly discarded; this threshold can be adjusted according to the strictness of the medical scenario, set to 0.25-0.35 for outpatient scenarios and 0.20-0.30 for inpatient scenarios due to higher information density; when V(m) is not lower than θ_d, proceed to the second step; The second step is to determine the hierarchical affiliation: Calculate the active priority Pri(m) for the entries that passed the first step, using the following formula: Pri(m) = β1·U(m) + β2·S(m) + β3·Rec(m) Wherein, Rec(m) is the recency factor Rec(m)=exp(-μ·Δt_m), Δt_m is the time interval since the entry was written, and μ is the recency decay coefficient; β1, β2, and β3 are preset weight factors that satisfy β1+β2+β3=1, preferably β1=0.4, β2=0.4, and β3=0.2; when Pri(m) is not lower than the activity threshold θ_k (preferably 0.50, in the range of 0.40-0.60), the entry is determined to still be in active use and will continue to be retained in the working memory layer; when Pri(m) is lower than θ_k, the entry is summarized and migrated to the context memory layer for archiving and storage, and the original entry is deleted from the working memory layer; The core design intent of the above two-step strategy is that high-priority entries are left in the working memory layer for immediate use in current generation, while medium- and low-priority entries that still have medical value are archived in the context memory layer for long-term storage rather than being discarded.
[0035] S12 (Contextual Memory Layer): The contextual memory layer is used to store historical medical records according to medical events. Each contextual memory is stored in the form of a structured 5-tuple: (medical time, medical event, key medical entity, source identifier, memory confidence). The key medical entity is stored in a dual form of "standard terminology code + original expression". The standard terminology code includes the ICD-10 code corresponding to the diagnosis, the LOINC code corresponding to the test item, and the ATC / medical insurance code corresponding to the drug. The memory confidence is determined by the information source type. The preset source confidence mapping table is as follows: 0.95 for test / examination report type, 0.90 for doctor's structured input, 0.80 for doctor's oral transcription, and 0.60 for patient oral. The contextual memory layer employs a multi-factor forgetting function based on time decay and medical importance weights, calculating memory retention using the following formula: R(m) = exp(-λ·Δt) · W_med(m) Where Δt is the time interval between the memory entry time and the current time, λ is the time decay coefficient; W_med(m) is the medical importance weight, which is determined by the type of medical entity contained in the memory entry: the W_med value of memory entries corresponding to allergy history, critical value records, and major diagnoses is 1.0 and is marked as non-forgettable memory, its retention rate is always 1.0, and it does not participate in the forgetting judgment; the W_med value of routine follow-up visit events is 0.5; the W_med value of general description entries is 0.3; when R(m) is lower than the preset forgetting threshold θ_f (preferred value is 0.15, range 0.10-0.20), the corresponding memory entry is subjected to forgetting deletion or downgrade migration to the long-term semantic memory layer, except for the non-forgettable memory.
[0036] S13 (Long-term Semantic Memory Layer): The long-term semantic memory layer is used to store patient-level semantic knowledge after inductive abstraction, including chronic disease history, allergy history, long-term medication list and baseline test indicators; the long-term semantic memory layer adopts a hybrid storage structure of medical knowledge graph and vector index, wherein the medical knowledge graph stores the medical relationships between entities with standard terminology encoding as nodes, such as the "disease-complication" relationship and the "drug-contraindication" relationship, and the vector index is used for semantic approximate retrieval, supporting semantic retrieval and graph reasoning; S14 (Privacy Desensitization Storage): De-identification processing is performed on entries written to the three-layer memory, replacing the patient's direct identifier with a hashed patient unique identifier, while the medical entity content retains its original meaning; each memory entry carries source metadata, which includes the visit identifier, source document identifier, write time, original text position pointer, and write method, forming a memory traceability chain.
[0037]
Step S2: Three-layer memory collaborative retrieval and fusion
[0038] S21: Extract real-time interaction information of the current session from the working memory layer as immediate context; S22: Based on the current chief complaint and patient identifier, retrieve historical medical records related to the current visit from the episodic memory layer. Employ a two-factor weighted retrieval strategy based on medical entity similarity and temporal proximity. The retrieval score for memory item m is calculated using the following formula: Score(m) = α·Sim(e_q, e_m) + (1-α)·exp(-λ·Δt_m) Where e_q is the query entity embedding vector obtained after medical entity recognition and terminology encoding of the current chief complaint, e_m is the embedding vector of the key medical entity in the memory entry m, and Sim(·,·) is the cosine similarity; since entities are stored with standard terminology encoding, the same medical concept with different expressions (such as "myocardial infarction" and "myocardial infarction") are mapped to the same or similar codes, realizing cross-expression retrieval matching; Δt_m is the time interval between the memory entry time and the current time, λ is the time decay coefficient; α is the entity similarity weight factor, with a value range of 0.6 to 0.8; the top K results are taken as search results in descending order of Score(m).
[0039] S23: Retrieve patient-level semantic knowledge from the long-term semantic memory layer based on the patient identifier to obtain chronic disease history, allergy history, long-term medication list and baseline test indicators; S24 (Memory Conflict Resolution): Conflict detection is performed on the three-layer retrieval results. When there are semantically conflicting memory entries: if the confidence difference between the two memories is greater than the preset conflict judgment threshold Δc, the high-confidence memory is accepted and the low-confidence memory is marked as pending verification; if the confidence difference is not greater than the threshold, both conflicting memories are retained in the memory enhancement context and a conflict mark is added for outputting conflict prompts to the doctor during subsequent generation. S25 (Fusion Ranking): The retrieval results from the working memory layer, the contextual memory layer, and the long-term semantic memory layer are merged and ranked according to the strategy of "security priority, confidence weighting, and field relevance routing": memories with security tags are forced to the top; the remaining memories are arranged in descending order according to the product of memory confidence and retrieval score; and each memory fragment is routed and labeled according to the medical record field type, and the applicable medical record fields for each memory fragment are labeled to form a memory-enhanced context.
[0040]
Step S3: Field-by-Field Medical Record Generation with Memory Anchoring
[0041] [Step S4: Memory Update and Consolidation] S41: Write the key information of the medical record generated during this visit into the context memory layer as a new visit event. When writing, perform the medical entity recognition, terminology encoding and confidence labeling described in S11. S42: Analyze the new diagnoses, medication adjustments, and abnormal test results during this visit. If it is determined that there is a new chronic disease, confirmed allergy, or change in long-term medication, update the corresponding patient-level semantic knowledge in the long-term semantic memory layer. Allergy information confirmed by the doctor is marked as non-forgettable memory. S43: Perform memory compression on the working memory layer: According to the two-step hierarchical processing strategy described in S11, the first step is to directly discard entries whose retention value V(m) is lower than the discard threshold. The second step is to summarize the entries whose Pri(m) is lower than the activity threshold and then migrate them to the context memory layer for archiving and storage, thereby releasing the working memory capacity. S44 (Forgetting Execution): Periodically traverse the contextual memory layer, calculate the retention rate of each memory entry according to the forgetting function described in S12, and perform forgetting deletion or downgrade migration on entries with a retention rate lower than the forgetting threshold, except for non-forgettable memories.
[0042]
Step S5: Memory Feedback Learning
[0043]
Step S6: Desensitized Output and Source Tracing
[0044]
Step S7: System Integration Development
[0045] Example 1: Automatic Generation of Outpatient Medical Records Taking the cardiology outpatient department of a top-tier hospital as an example, the specific implementation process of the method of the present invention is explained.
[0046] Step S1: The system pre-constructs a hierarchical memory architecture for patient P, a 65-year-old male with a 10-year history of hypertension. The long-term semantic memory layer stores: hypertension (ICD-10 code I10, confidence level 0.95, sourced from previous discharge summaries), amlodipine 10mg / day + irbesartan 150mg / day (ATC / medical insurance code C08CA01 / C09CA03, long-term medication), penicillin allergy (non-forgettable memory, W_med=1.0, confidence level 0.95, sourced from structured data entry by the doctor), and baseline blood pressure 145 / 90 mmHg. The contextual memory layer stores the patient's three most recent medical visits. Examples of quintuples are as follows: (2026-06-15, Blood pressure check, [Blood pressure 150 / 95 mmHg], Visit ID-20260615-003, 0.95), (2026-07-20, Irbesartan added, [Irbesartan 150 mg], Visit ID-20260720-011, 0.90).
[0047] Step S2: Patient P returned to the clinic on August 18, 2026, complaining of "dizziness and fatigue for one week." The agent performs memory retrieval: S21, the working memory layer receives and stores the current chief complaint and the physical examination data entered by the doctor (blood pressure 155 / 95 mmHg, heart rate 82 beats / min), which is sourced from the doctor's structured input, with a confidence level of 0.90; S22, after the chief complaint is identified by medical entity, it is mapped to ICD-10 code (dizziness R42 and fatigue R53.9 are the basic codes, and ICD-10 related memories are expanded by combining the patient's history of hypertension). The above-mentioned historical medical records are retrieved in the contextual memory layer by two-factor weighted scoring, and the top 3 records are selected in descending order of score. S23, retrieved information on hypertension history, combination drug regimens and penicillin allergy in the long-term semantic memory layer, among which allergy memory carries a safety marker; S24, Conflict Detection: The patient's statement "I am taking amlodipine besylate" is consistent with the long-term medication list in the memory bank, "Amlodipine 10mg / day + Irbesartan 150mg / day," and is determined to be the same medication (ATC / Medical Insurance Code C08CA01) after terminology code comparison, thus not constituting a conflict. If the patient's statement is "I am taking nifedipine," then the inconsistency with the medication in the memory bank constitutes a semantic conflict. Since the difference of 0.30 between the patient's statement confidence level of 0.60 and the doctor's recorded confidence level of 0.90 is greater than the threshold Δc=0.2, the memory bank record is accepted, and the patient's statement is marked as pending verification. S25, Fusion sorting: Penicillin allergy memory is forced to the top due to carrying a safety marker, and the remaining memories are sorted in descending order by confidence level × search score. Medication memory is routed to the treatment plan field, and historical blood pressure memory is routed to the current medical history and auxiliary examination fields to form a memory enhancement context.
[0048] Step S3: The agent calls the medical record generation language model and generates data field by field according to the outpatient medical record template. Chief complaint field: Use the chief complaint text "dizziness and fatigue for one week" from working memory, with the anchor point being the memory entry for this session; Present Illness Field: Combining current physical examination data in working memory and historical blood pressure trends in contextual memory, the field generates "Patient has a 10-year history of hypertension, and blood pressure has been poorly controlled in the past three months, fluctuating between 142-155 / 88-95 mmHg. One week ago, dizziness and fatigue occurred...", with the anchor point being three historical medical visit memory entries. Past medical history field: "10-year history of hypertension, history of penicillin allergy" is generated from the long-term semantic memory layer, with the anchor points being I10 encoded memory and allergy memory; Diagnostic field: Generate "Hypertension Grade 3 (Very High Risk)", anchored to I10 encoding memory; Treatment plan field: Based on long-term medication memory, the generated content is "Adjust antihypertensive regimen: Amlodipine 10mg / day + Irbesartan 150mg / day, with recommended addition of hydrochlorothiazide 12.5mg / day"; Consistency check: The generated content's amlodipine dose of 10mg is consistent with the anchored memory, and the hydrochlorothiazide 12.5mg is a newly added medical order (existing in the immediate medical order entry in working memory), and the check passed; The generated content's prompt to avoid using penicillin-type drugs is anchored to the allergy memory; If the generative model outputs "It is recommended to add valsartan 80mg / day" but there is no such new medical order in the working memory, the statement cannot be anchored to any memory, is marked as an item to be confirmed by the doctor and highlighted in the draft, thus achieving hallucination suppression.
[0049] Step S4, Memory Update and Consolidation: The current medical event (addition of hydrochlorothiazide, blood pressure 155 / 95 mmHg) is written into the contextual memory layer after being confirmed by the doctor, with a confidence level of 0.95 (the source of the medical record confirmed by the doctor); it is determined that hydrochlorothiazide is a change in long-term antihypertensive drugs, and the long-term medication list in the long-term semantic memory layer is updated; the working memory layer capacity has not reached the threshold, so compression is not triggered.
[0050] Step S5, Memory Feedback Learning: After reviewing the draft, the doctor changes the diagnosis field to "Hypertension Grade 3 (Very High Risk)" (originally "Extremely High Risk"). The system determines this as a format standard adjustment, does not modify the source memory, but updates the diagnostic grading verification rules in the generation strategy. The doctor adds "It is recommended to have a cardiac ultrasound to assess cardiac function" to the treatment plan field. The system determines this as supplementing missing information and writes it as a new memory entry into the contextual memory layer.
[0051] Example 2: Continuous Generation and Memory Compression of Inpatient Medical Records Take a hospital's respiratory medicine ward as an example. Patient Q is admitted to the hospital for "severe pneumonia," and a medical record needs to be generated daily during the hospitalization.
[0052] The working memory layer stores ward round information for the day (symptom changes, test results for the day, and adjustments to medical orders), with a capacity threshold of N_max=50 entries; the contextual memory layer stores disease events on a daily basis; and the long-term semantic memory layer stores the underlying disease (type 2 diabetes, ICD-10 code E11) and the admission diagnosis (severe pneumonia J15.9).
[0053] When generating daily medical records, the agent retrieves the previous day's medical records from the contextual memory layer, retrieves the underlying diseases from the long-term semantic memory layer, and obtains the ward round data for the day from the working memory layer, and integrates them to generate the daily medical records. The process is the same as in Implementation Example 1.
[0054] When the working memory layer reaches its capacity threshold, memory compression is triggered: the two-step hierarchical processing strategy described in S11 is executed. In the first step, items with no medical value, such as "the doctor asked how the weather is today," are directly discarded because their retention value V(m) is lower than the discard threshold θ_d. In the second step, "the patient complained of poor sleep at night" (U=0.3, S=0, I=0.4, V=0.33>θ_d, passing the first step) but Pri(m) is lower than the active threshold θ_k due to the long writing time, is summarized as "poor sleep during hospitalization" and migrated to the context memory layer for archiving and storage. Meanwhile, "blood oxygen saturation dropped to 88% (critical value, S=1.0, U=1.0, I=1.0)" continues to be retained in the working memory layer because Pri(m) is extremely high.
[0055] When test results show an abnormal trend (such as CRP rising for three consecutive days: 48→76→112mg / L), the agent retrieves the trend in the context memory layer, automatically generates a trend analysis description "progressive increase in inflammatory markers, CRP rising from 48mg / L to 112mg / L" in the auxiliary examination field of the medical record, and triggers the update of the baseline of test indicators in the long-term semantic memory layer.
[0056] Thirty days after discharge, the system periodically performs a forgetting traversal: routine ward round descriptive entries (W_med=0.3) are downgraded and migrated to the vector index of the long-term semantic memory layer because their retention rate is lower than the threshold θ_f; while the patient's memory of "positive penicillin skin test" during hospitalization is a non-forgettable memory of allergies (W_med=1.0), with a retention rate of 1.0, and is permanently retained.
[0057] Example 3: Memory Conflict Resolution Scenario Patient R visited the endocrinology department, complaining of "diabetes follow-up." Long-term semantic memory records indicated her long-term medication as "metformin 0.5g twice daily (ATC / Medical Insurance Code A10BA02, sourced from the previous outpatient doctor's entry, confidence level 0.90)." During this visit, the patient verbally stated, "I am currently taking metformin extended-release tablets 1g once daily, and glimepiride."
[0058] Conflict Detection: The patient's verbal description of the medication regimen is inconsistent with the long-term medication list in the memory bank in terms of both drugs and dosages, constituting a semantic conflict. The confidence difference is calculated: 0.90 - 0.60 = 0.30 > Δc = 0.2. The system accepts the memory bank record, while marking the patient's verbal description as pending verification. When generating the treatment plan field, a conflict warning is output to the doctor: "The patient's self-reported medication (metformin extended-release tablets 1g qd + glimepiride) is inconsistent with the record (metformin 0.5g bid). Please verify the current actual medication."
[0059] After verification, the doctor confirmed that the patient's medication had been adjusted at another hospital. Fact correction was performed through the feedback learning module: the medication memory in the long-term semantic memory layer was updated to "metformin extended-release tablets 1g qd + glimepiride 2mg qd", the confidence level was updated to the doctor's input level of 0.90, the error correction reason label was recorded as "medication adjustment at another hospital", and the error correction record was updated to the generation strategy - the subsequent addition of a "verification with patient self-report" validation rule to the medication field.
[0060] System Implementation Examples This invention also provides an automatic electronic medical record generation system based on agent-level hierarchical memory, comprising: The hierarchical memory management module is used to build and maintain the working memory layer, the contextual memory layer, and the long-term semantic memory layer. It performs memory writing, retrieval, updating, forgetting, and consolidation operations, including a terminology normalization unit (medical entity recognition and ICD-10 / LOINC / ATC / medical insurance code mapping) and a forgetting calculation unit (multi-factor forgetting function and non-forgettable memory management). The memory retrieval fusion module is used to perform two-factor weighted retrieval, conflict detection and resolution, security priority and confidence weighted fusion sorting and field routing annotation, and generate memory-enhanced context; The medical record generation module is used to generate electronic medical record drafts field by field according to the medical record structure template based on the memory enhancement context. It includes an anchored output unit (binding the generated content with the memory anchor identifier) and a consistency verification unit (comparison of key medical data, marking pending confirmation and interception regeneration). The memory feedback learning module is used to receive doctor's modification operations, locate the source memory entries through anchor points, perform error correction and update, and update the medical record generation strategy; The privacy desensitization module is used for de-identification processing during the memory storage stage and field-level desensitization during the output stage; The source auditing module is used to maintain a memory source chain composed of source metadata, supporting bidirectional source query from generated content to original documents.
[0061] Experimental results (200 outpatients from a tertiary hospital) Table 1 presents data from a comparative experiment conducted within the company on 200 patients with ≥2 historical medical records selected from the outpatient department of a tertiary hospital. The data compares four core indicators of the three methods.
[0062] Table 1
[0063] [Indicator Definition and Statistical Explanation] ① Cross-visit information citation rate: The proportion of generated medical records that correctly cite key information from the patient's previous visits (such as previous diagnoses, medication adjustments, and test trends). LLM, which generates records directly, relies solely on the current conversation due to the lack of historical context, resulting in an extremely low citation rate (12.5%). RAG can recall some historical records through vector retrieval, but suffers from retrieval noise and semantic drift. This invention achieves high-precision cross-visit information association through a three-layer memory collaboration + standard terminology encoding matching + time decay weighting.
[0064] ② Completeness of Past Medical History: The "Past Medical History" field, generated through manual review, reflects the completeness of the patient's actual past medical history, including diseases, surgeries, and injuries. The long-term semantic memory layer of this invention is specifically designed to maintain patient-level summaries of chronic diseases, allergies, and surgical histories.
[0065] ③ Accuracy of key medical data: The consistency rate of three key data points extracted from the generated medical record—drug name and dosage, ICD-10 diagnostic code, and test values—with the original document / medical order. The memory anchoring verification mechanism of this invention automatically marks untraceable key data as requiring confirmation, effectively suppressing hallucinations.
[0066] ④ Allergy history forgetting rate: Among the 200 patients, 18 had a history of allergies. The proportion of omissions or errors in allergy information in the medical records generated by each method was statistically analyzed. In this invention, allergy-related entries are marked as non-forgettable memories (W_med=1.0, retention rate is constant 1.0), theoretically with a forgetting rate of 0%.
[0067] ⑤ Comprehensive score calculation formula: Score = 0.25×citation rate + 0.30×completeness rate + 0.35×accuracy rate + 0.10×(1-forgetting rate), with a maximum score of 100 points for each item.
[0068] Detailed data for each indicator is shown in Table 2.
[0069] Table 2
[0070] * Note: The sample size for the allergy history forgetting rate was 18 out of 200 patients who had recorded their allergy history; ** The allergy history forgetting rate of this invention is 0% (18 / 18 all correctly retained), no statistical test is required; *** p<0.001 indicates extremely significant difference (paired t-test, two-sided).
[0071] 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 method for automatically generating electronic medical records based on agent-level hierarchical memory, characterized in that, include: A hierarchical memory architecture for intelligent agents is constructed, comprising a working memory layer, a contextual memory layer, and a long-term semantic memory layer. The working memory layer is used to store real-time interaction information in the current medical session, the contextual memory layer is used to store historical medical records according to medical events, and the long-term semantic memory layer is used to store patient-level semantic knowledge after induction and abstraction. When a request to generate a medical record for the current visit is received, the real-time interaction information of the current session is extracted from the working memory layer, historical medical records related to the current visit are retrieved from the context memory layer, and patient-level semantic knowledge is retrieved from the long-term semantic memory layer. The three-layer retrieval results are then merged and sorted to form a memory-enhanced context. Based on the memory enhancement context and current medical information, the large language model is invoked to generate an electronic medical record draft field by field according to the preset medical record structure template. After each field is generated, the generation result of the field is written back to the working memory layer. When each field is generated, the memory anchor point identifier on which the generated content is based is output synchronously, and the key medical data in the generated content is compared with the corresponding data in the anchored memory entry. Key medical data statements that cannot be anchored to any memory entry and do not belong to the newly entered information of this medical visit are marked as items to be confirmed by the doctor. The key medical record information confirmed by the doctor during this visit is written into the contextual memory layer as a new visit event, and the patient-level semantic knowledge in the long-term semantic memory layer is updated based on the new diagnosis, medication adjustment and abnormal test results of this visit.
2. The method for automatically generating electronic medical records based on agent-level hierarchical memory according to claim 1, characterized in that, Each historical medical record in the contextual memory layer is stored in a five-tuple format: visit time, treatment event, key medical entity, source identifier, and memory confidence level. The key medical entity is stored in a dual format of standard terminology encoding and original expression. The standard terminology encoding includes the ICD-10 code corresponding to the diagnosis, the LOINC code corresponding to the test item, and the ATC code corresponding to the drug. The memory confidence level is determined by the information source type according to a preset source confidence level mapping, wherein the memory confidence level corresponding to test or examination report type sources, doctor structured input, doctor dictation transcription, and patient dictation decreases in that order.
3. The method for automatically generating electronic medical records based on agent-level hierarchical memory according to claim 2, characterized in that, The retrieval of historical medical records related to the current visit in the context memory layer adopts a two-factor weighted retrieval strategy. The retrieval score of the memory entry is calculated by the following formula: Score(m)=α·Sim(e_q,e_m)+(1-α)·exp(-λ·Δt_m); where e_q is the query entity embedding vector obtained by medical entity recognition and terminology encoding of the current chief complaint, e_m is the embedding vector of key medical entities in the memory entry, Sim is the cosine similarity, Δt_m is the time interval between the memory entry time and the current time, λ is the time decay coefficient, and α is the entity similarity weight factor, with a value range of 0.6 to 0.8; the top K entries are selected as the retrieval results in descending order of retrieval score.
4. The method for automatically generating electronic medical records based on agent-level hierarchical memory according to claim 2, characterized in that, The fusion sorting process includes memory conflict resolution: conflict detection is performed on the three-layer retrieval results. When there are semantically conflicting memory entries, if the difference in memory confidence between the two memories is greater than a preset conflict judgment threshold, the memory with higher confidence is accepted and the memory with lower confidence is marked as pending verification. If the difference is not greater than the conflict judgment threshold, both conflicting memories are retained in the memory enhancement context and a conflict mark is added. The fusion sorting is performed as follows: memories carrying security marks are forced to the top, and the remaining memories are arranged in descending order according to the product of memory confidence and retrieval score. The memory segments are routed and labeled according to the medical record field type, and the applicable medical record fields for each memory segment are marked.
5. The method for automatically generating electronic medical records based on agent-level hierarchical memory according to claim 1, characterized in that, The contextual memory layer is equipped with a multi-factor forgetting function based on time decay and medical importance weight. The memory retention of a memory entry is calculated by the following formula: R(m)=exp(-λ·Δt)·W_med(m); where Δt is the time interval between the memory entry time and the current time, λ is the time decay coefficient, and W_med(m) is the medical importance weight, which is determined by the type of medical entity contained in the memory entry. Memory entries corresponding to allergy history, critical value records, and major diagnoses are marked as non-forgettable memories, and their memory retention is always 1.0, and they do not participate in the forgetting determination. When the memory retention of other memory entries is lower than the preset forgetting threshold, the corresponding memory entries are deleted or downgraded and migrated to the long-term semantic memory layer.
6. The method for automatically generating electronic medical records based on agent-level hierarchical memory according to claim 1, characterized in that, The working memory layer has a capacity threshold. When the number of stored entries reaches the capacity threshold, a two-step hierarchical compression is performed: First, the retention value V(m) = γ1·U(m) + γ2·S(m) + γ3·I(m) is calculated for each working memory entry, where U(m) is the clinical urgency, S(m) is the safety marker, I(m) is the information measure, and γ1, γ2, and γ3 are weighting factors. Entries with a retention value lower than the discard threshold are directly discarded. Second, the active priority Pri(m) = β1·U(m) + β2·S(m) + β3·Rec(m) is calculated for the entries that passed the first step, where Rec(m) is the recency factor, and β1, β2, and β3 are weighting factors. Entries with an active priority lower than the active threshold are summarized, migrated to the context memory layer for archiving, and then deleted from the working memory layer.
7. The method for automatically generating electronic medical records based on agent-level hierarchical memory according to claim 1, characterized in that, The key medical data includes drug name and dosage, diagnostic code, test value and allergen; the consistency comparison also includes: intercepting key medical data that is inconsistent with the corresponding data in the anchored memory entry, and triggering the regeneration of the field or manual intervention.
8. The method for automatically generating electronic medical records based on agent-level hierarchical memory according to claim 1, characterized in that, It also includes a memory feedback learning step: receiving the doctor's modification operation on the electronic medical record draft, recording the text differences before and after the modification, the medical record fields corresponding to the modification location, and the memory anchor point identifier to which the modified content is anchored; locating the source memory entry in the memory bank based on the text differences and the memory anchor point identifier, and determining the modification type; if the modification type is fact correction, performing error correction update on the source memory entry, and updating the memory confidence of the entry to the confidence level of the doctor's input; if the modification type is supplementing missing information, writing the supplementary information as a new memory entry into the corresponding memory layer after entity recognition and terminology encoding; and updating the verification rules and prompt word weights in the medical record generation strategy based on historical error correction records.
9. The method for automatically generating electronic medical records based on agent-level hierarchical memory according to claim 1, characterized in that, It also includes: performing de-identification processing on entries written to the three-layer memory, replacing the patient's direct identifier with a hashed patient unique identifier; each memory entry carries source metadata including visit identifier, source document identifier, write time, original text position pointer and write method; when outputting electronic medical records or exporting memory content, performing field-level desensitization according to the role permissions of the output scenario; supporting backtracking from any field of the generated medical record to the source memory entry through the memory anchor identifier, and then backtracking to the original document through the source metadata.
10. An automatic electronic medical record generation system based on agent-level hierarchical memory, characterized in that, include: The hierarchical memory management module is used to build and maintain a working memory layer, a contextual memory layer, and a long-term semantic memory layer. The working memory layer is used to store real-time interactive information in the current medical session, the contextual memory layer is used to store historical medical records according to medical events, and the long-term semantic memory layer is used to store patient-level semantic knowledge after induction and abstraction. The memory retrieval fusion module is used to extract real-time interaction information of the current session from the working memory layer when a request to generate medical records for the current visit is received, retrieve historical medical records related to the current visit from the context memory layer, retrieve patient-level semantic knowledge from the long-term semantic memory layer, and fuse and sort the three-layer retrieval results to form a memory-enhanced context. The medical record generation module is used to generate an electronic medical record draft field by field according to a preset medical record structure template by calling a large language model based on the memory enhancement context and the current medical visit information. After each field is generated, the generation result of the field is written back to the working memory layer. The medical record generation module includes an anchoring output unit and a consistency verification unit. The anchoring output unit is used to output the memory anchor identifier on which the generated content of each field is based when each field is generated. The consistency verification unit is used to compare the key medical data in the generated content with the corresponding data in the anchored memory entries, and to mark key medical data statements that cannot be anchored to any memory entry and do not belong to the newly entered information of this medical visit as items to be confirmed by the doctor. The hierarchical memory management module is also used to write key medical record information confirmed by the doctor during this visit into the contextual memory layer as a new visit event, and to update the patient-level semantic knowledge in the long-term semantic memory layer based on the new diagnosis, medication adjustment and abnormal test results during this visit.
