Editor’s introduction
The study evaluates EHR-RAG, a retrieval-augmented framework designed to improve clinical prediction from long-horizon structured electronic health records. It compares performance across four clinical tasks, including acute myocardial infarction and anemia diagnosis, using metrics like macro-F1. EHR-RAG outperforms existing LLM-based methods, showing stronger identification of risk signals in acute MI and improved accuracy across anemia severity levels. The framework incorporates event- and time-aware retrieval, iterative query refinement, and dual-path reasoning to maintain clinical context and temporal dynamics.
Introduction
Electronic Health Records (EHRs) are digital longitudinal patient records composed of structured clinical events such as diagnoses, medications, laboratory results, and procedures. Unlike free-text clinical notes, structured EHR data are systematically collected, standardized across care settings, and less subjective in description, making them a reliable and widely available foundation for clinical decision making. Beyond individual events, structured EHRs encode rich temporal and categorical information, including event types, ordering, recurrence patterns, and long-term clinical trajectories, that underpins clinical decision-making across the full course of clinical care. For many non-acute or chronic conditions, patients accumulate long-horizon EHRs spanning years of irregular visits and thousands of heterogeneous events. These trajectories are common in real-world healthcare but difficulty to interpret, even for clinicians, and recent studies have highlighted both their modeling challenges and clinical importance. Effective clinical prediction in this setting requires reasoning over long temporal spans while preserving event-type structure and clinical dependencies.
Traditional machine learning (ML) methods have been widely studied for EHR-based prediction tasks, including length-of-stay estimation, readmission prediction, and medication recommendation. More recently, large language models (LLMs) have shown promise in clinical reasoning due to their strong generalization capabilities to new task and their capability to perform multi-step reasoning to provide rationale instead of only final answer to make it more trustworthy for clinician’s decision making. However, LLMs cannot natively process long-horizon structured EHRs: their fixed context windows are quickly exceeded by multi-visit patient histories, and naive event serialization obscures temporal structure and discards clinically relevant context.
Existing approaches address this limitation primarily through heuristic truncation, such as retaining only recent events or selecting events associated with high-frequency codes. While retrieval-augmented generation (RAG) offers a mechanism to selectively retrieve relevant events, existing RAG-based methods typically retrieve isolated subsets of the patient history primarily to satisfy context-length constraints. As a result, vanilla RAG in clinical settings often suffers from low retrieval quality, incomplete evidence coverage, and reduced robustness when reasoning over long-horizon EHRs. Despite the prevalence and importance of such data, to the best of our knowledge, no existing RAG framework is explicitly designed to handle their longitudinal, multi-event nature.
In this work, we study clinical prediction with long-horizon structured EHR data and propose EHR-RAG, an enhanced retrieval-augmented framework tailored for this setting. EHR-RAG is built around three components designed to improve retrieval quality, completeness, and robustness under strict context constraints: (a) Event- and Time-Aware Hybrid EHR Retrieval (ETHER), which preserves event-type structure and temporal dynamics during retrieval; (b) Adaptive Iterative Retrieval (AIR), which progressively refines retrieval queries to expand evidence coverage while respecting context limits; and (c) Dual-Path Evidence Retrieval and Reasoning (DER), which jointly retrieves and reasons over both factual patient history and counterfactual evidence to improve robustness. Together, these designs enable reliable long-horizon clinical reasoning with LLMs. We evaluate EHR-RAG against a range of baseline methods on a long-horizon EHR benchmark. Experimental results demonstrate consistent Macro-F1 improvements across all four clinical prediction tasks, with gains of 3.63% on Long Length of Stay, 11.28% on 30-day Readmission, 16.46% on Acute Myocardial Infarction, and 7.66% on Anemia relative to the strongest LLM-based baselines. Overall, EHR-RAG achieves an average Macro-F1 improvement of 10.76%.
Related Work
Clinical Predictive Models. Structured EHR data has supported the development of a wide range of machine learning models for different clinical prediction tasks. Models such as RETAIN, GRAM, and KerPrint are specifically designed to capture complex temporal and hierarchical patterns within structured EHRs and have shown strong performance across multiple predictive settings. In parallel, recent efforts have focused on scaling clinical prediction through large foundation models, including CLMBR-T-Base, Virchow, and MIRA. However, traditional predictive models—ranging from task-specific architectures to supervised foundation model training—remain inflexible, requiring labeled data for every downstream task and often failing to generalize beyond the distribution on which they were trained. These limitations are especially problematic in the dynamic and heterogeneous healthcare environment.
LLM-based Clinical Prediction. Recently, the paradigm of clinical prediction has begun to shift toward the use of LLMs. LLMs offer greater adaptability and generalization than traditional supervised models, with the capacity to interpret diverse medical information and support more versatile clinical decision-making. Several studies apply LLMs directly to clinical prediction tasks, while others employ LLMs as encoders for structured EHR data. Additional efforts explore training or adapting LLMs for specific downstream healthcare tasks, and recent work introduces LLM-driven agents to assist with clinical reasoning and EHR interaction. Despite these advances, few studies have addressed long-horizon EHR prediction, leaving substantial challenges in enabling LLMs to interpret complex, multi-visit longitudinal patient histories. Our work extends this line of research by developing an LLM-based approach specifically tailored for long-horizon EHR prediction.
Retrieval-Augmented Generation with LLM. RAG has emerged as an effective technique for enhancing LLMs with external knowledge beyond their limited context window. A variety of retrieval strategies have been proposed to help LLMs accurately access additional relevant information, leading to improved performance across diverse tasks and settings. In the healthcare domain, where clinical information is often overwhelming in volume and complexity, RAG has become increasingly popular for grounding LLM outputs in accurate task-relevant evidence. Some studies use RAG to inject medical knowledge and improve healthcare applications, while others employ RAG to mitigate long-context limitations. For example, REALM enhances multimodal EHR analysis using LLMs, and EMERGE integrates RAG into multimodal EHR predictive modeling. Additional work has investigated RAG-based methods for clinical trial and patient matching.However, most of these approaches focus on unstructured EHR data such as clinical notes, rather than structured tabular EHR, which exhibits distinct temporal dynamics and event-type structure. Moreover, vanilla RAG pipelines often suffer from incomplete evidence retrieval in clinical settings. Our work aims to fill this gap by designing a RAG framework specifically tailored for long-horizon structured EHR data.
Event- and Time-Aware Hybrid EHR Retrieval
Prior work has explored incorporating temporal information to improve retrieval quality, for example by introducing time-aware relevance weighting or decay functions. However, in clinical settings, temporal importance is not strictly monotonic: while recent events are often critical, early events corresponding to disease onset or initial admission can be equally informative. This observation motivates a U-shaped time-aware retrieval strategy that explicitly emphasizes both recent and early clinical evidence.
Adaptive Iterative Retrieval
Single-pass retrieval is often insufficient for long-horizon EHRs, where relevant clinical evidence may be temporally dispersed or only indirectly related to the initial query. To address this limitation, we progressively expands evidence coverage in a controlled and targeted manner.
This iterative process continues until the evidence is deemed sufficient or a predefined iteration limit is reached. By incrementally expanding the evidence set in a targeted manner, AIR improves retrieval recall while preventing uncontrolled context growth, which is critical for effective long-horizon clinical reasoning.
Experimental Setup
To systematically evaluate our proposed method and compare it against baseline approaches under long-horizon clinical prediction settings, we conduct all experiments on the EHRSHOT benchmark. Unlike commonly used EHR dataset, such as MIMIC-III/IV, which are largely restricted to ICU or emergency department settings, EHRSHOT captures longitudinal patient records across general hospital care. As a result, patient records in EHRSHOT often span multiple decades and contain thousands of clinical events. On average, EHRSHOT includes 2.3× more clinical events and 95.2× more encounters per patient than MIMIC-IV, making it substantially more challenging and better suited for evaluating long-horizon clinical reasoning.
We select four representative prediction tasks from EHRSHOT: Long Length of Stay, 30-day Readmission, Acute Myocardial Infarction (Acute MI), and Anemia. The first two tasks fall under the Operational Outcomes category, Anemia belongs to Anticipating Lab Test Results, and Acute MI is categorized as Assignment of New Diagnoses. The first three tasks are binary classification problems, while Anemia is a four-class classification task. Together, these tasks span diverse clinical objectives and temporal reasoning scenarios, enabling a comprehensive evaluation of long-horizon reasoning on structured EHR data. We report Accuracy, Macro-F1, and per-class F1 scores, as most clinical classification tasks are inherently imbalanced.
We conduct experiments using three LLMs that span both proprietary and open-source settings: GPT-5, Claude-Opus-4.5, and LLaMA-3.1-8B. These models cover a broad range of architectures, training scales, model sizes, and accessibility levels, allowing us to assess the robustness of EHR-RAG across different LLM backbones. Additional details of the experimental setup are provided in Appendix A.
Main Results
(iii) Baseline analysis. We observe that vanilla RAG can underperform direct generation in some cases, suggesting that retrieving events solely based on semantic similarity, without explicitly modeling recency and temporal context, may omit clinically critical recent evidence and lead to degraded performance. Uniform RAG exhibits unstable behavior, performing well in some cases but poorly in others, suggesting that while information across the patient history contains useful signals, indiscriminate retrieval lacks robustness. Rule-based RAG yields moderate improvements but introduces systematic bias by prioritizing high-frequency events, which can skew predictions toward dominant classes. ReAct RAG occasionally provides marginal gains over RAG by enabling iterative retrieval and broader evidence coverage; however, it does not consistently translate additional retrieval steps into reliable performance improvements.
(iv) Overall comparison. Across all four tasks, EHR-RAG consistently outperforms direct generation, vanilla RAG, and other retrieval baselines. These results highlight the importance of jointly modeling event-type structure, temporal dynamics, and evidence diversity through event- and time-aware retrieval, adaptive iterative refinement, and dual-path evidence retrieval and reasoning for accurate and reliable long-horizon clinical prediction from structured EHR data. Overall, these findings demonstrate that effective long-horizon EHR reasoning requires structured, temporally aware, and diversity-preserving retrieval mechanisms rather than generic or heuristic RAG strategies. Appendix B presents a qualitative case study comparing EHR-RAG with direct generation and vanilla RAG.
Ablation Analysis of Key Components
(ii) Comparison with vanilla RAG. Vanilla RAG performs substantially worse than all EHR-RAG variants, with especially severe degradation on Anemia (14.93 accuracy and 23.63 Macro-F1 points). This confirms that naive retrieval alone is insufficient for long-horizon structured EHR reasoning, and motivates the need for the proposed event-aware, iterative, and dual-path design.
Performance Across Different LLM Backbones
(ii) Larger gains on smaller models. While GPT-5 achieves the highest absolute performance, the relative improvements introduced by EHR-RAG are more pronounced for LLaMA-3.1-8B. Compared to the strongest baseline, EHR-RAG improves Macro-F1 by over 6 points on both models, suggesting that its design can partially mitigate the limitations of smaller model capacity.
Comparison with Traditional ML Baselines
(ii) Comparison with representation-based ML models. As expected, CLMBR-based LR generally outperforms count-based features, particularly as the number of training samples increases, reflecting the advantage of pretrained foundation models in capturing general clinical representations. However, even in medium- and full-data settings, EHR-RAG achieves comparable or superior Macro-F1 scores across all tasks. This suggests that retrieval-augmented LLM reasoning can effectively integrate heterogeneous and temporally distributed clinical evidence beyond what is captured by fixed patient representations.
(iii) Robustness on long-horizon and imbalanced tasks. The advantages of EHR-RAG are most pronounced on long-horizon and class-imbalanced tasks, such as Acute MI and Anemia. In these settings, ML baselines struggle to capture sparse yet clinically meaningful signals distributed over extended patient histories. In contrast, EHR-RAG leverages strong generalization and zero-shot reasoning capabilities to surface and aggregate relevant evidence, leading to more robust performance.
Overall, these results demonstrate that EHR-RAG not only outperforms traditional ML baselines in low-resource settings, but also remains competitive or superior even when large amounts of labeled data are available, underscoring its effectiveness as a general-purpose framework for long-horizon EHR prediction.
Conclusion
In this paper, we introduce EHR-RAG, an enhanced retrieval-augmented framework designed to bridge long-horizon EHRs and LLMs. EHR-RAG addresses key challenges posed by long-horizon EHR data, including context window limitations, temporal fragmentation, and incomplete evidence retrieval, through a combination of event- and time-aware hybrid EHR retrieval, adaptive iterative refinement, and dual-path evidence retrieval and reasoning. Extensive experiments demonstrate that EHR-RAG consistently outperforms other LLM-based baselines across diverse long-horizon clinical prediction tasks. Overall, our results show that carefully designed retrieval and reasoning mechanisms can enable LLMs to effectively interpret long-horizon structured EHR data even under strict context constraints. We believe EHR-RAG represents a practical step toward more reliable and data-efficient clinical prediction systems, and provides a foundation for future work on scalable, evidence-grounded reasoning over longitudinal healthcare data.
Impact Statement
This work aims to advance large language model for reasoning over long-horizon electronic health records through retrieval-augmented generation. While our framework is developed using publicly accessible, de-identified data, we acknowledge that work involving clinical information raises considerations around privacy, fairness, and the appropriate use of AI-assisted decision support. Our method is designed as a research contribution rather than a deployed clinical system, and it does not make autonomous treatment recommendations. Instead, it seeks to improve technical robustness in temporal retrieval and reasoning, which may support future development of safer and more interpretable clinical AI tools.
Clinical Scenario
Clinical Context. Initially admitted on 2014-11-27 for subarachnoid hemorrhage (SAH) due to ruptured intracranial aneurysm; discharged 2014-11-28 after conservative management. Readmitted on 2014-12-04 for elective intracranial aneurysm clipping. The microsurgical procedure was completed successfully, followed by routine postoperative monitoring in the neurological intensive care unit.
B.2.1 Coarse Retrieval
Using medical priors for postoperative neurologic and respiratory monitoring, ETHER retrieves candidates spanning: neurologic status (e.g., GCS), respiratory parameters (e.g., PEEP, FiO2, airway pressure), arterial blood gases (pH, PaCO2, PaO2), hemodynamics (blood pressure), and coagulation markers (INR, aPTT), as well as additional candidates including vasopressor use, ventilation settings, pain, and sedation metrics.
B.2.3 Retrieved Clinical Evidence
Respiratory and Blood Gas Trends. Expected postoperative disturbances with rapid normalization: mild acidosis (pH 7.24) and hypercapnia (PaCO2 52 mmHg) improve within two hours (pH 7.34, PaCO2 46.5 mmHg). Oxygenation remains adequate; FiO2 is weaned from 60% to 50%, indicating improving respiratory status with minimal ventilatory support.


