Condensation, context engineering, and model selection
Question answering in WA Health Summary pairs deterministic FHIR R4 record preparation with single-pass open-weight model generation. The engine cleans and condenses the chart in code, attaches bounded question-specific context in a separate prompt region, and routes requests across three Gemma 4 model sizes. System wiring is documented under Architecture, and benchmark readouts are published under Reports.
Exploratory applied research · University of Washington Clinical Informatics Research Group
Core design choices
Deterministic FHIR preparation. Extraction, deduplication, condensation, and passage retrieval execute in standard Python before the model is called, presenting a clean numbered ledger instead of raw FHIR JSON.
Verbatim-first condensation. Records that fit the target chart budget are rendered in full; larger histories are reduced monotonically while preserving the HL7 International Patient Summary (IPS) safety core and logging every omission in a manifest.
Two-region prompt layout. System instructions, the condensed chart, and unsaved draft overlays form a question-invariant prefix for KV-cache reuse; optional enrichers append strictly to the user turn suffix.
Single-pass generation. Question-aware retrieval runs ahead of generation rather than inside multi-step tool-calling loops, keeping latency predictable and every module independently toggleable.
Portable open-weight models. Three Gemma 4 tiers share one tokenizer and prompt contract across university GPU servers and local workstations behind a standard OpenAI /v1 interface.
Multi-clinic FHIR R4 exports range from a few dozen resources to several thousand entries containing JSON wrapper boilerplate, repeated routine observations, Base64-encoded notes, and conflicting medication lists across clinics.
Patient-mediated use
Users are patients and caregivers preparing for visits. Responses must separate active from stopped entries, avoid prescribing or dose-change instructions, and state explicitly when requested records are absent or outside the visible scope.
Resource-level traceability
Every clinical claim needs a direct link back to the originating FHIR resource, date, and organization so patients and clinicians can inspect the source record. Pre-summarizing the chart with an LLM breaks that 1-to-1 link.
Self-hosted execution
Keeping health records inside university or user-controlled environments requires open-weight models with modest memory footprints and per-user authorization enforced outside the model.
Context Engineering
Prompt structure and grounding rules
wahs-engine splits the prompt into a question-invariant system prefix and a question-specific turn suffix.
Region 1 · System prefix
Instructions, condensed chart, and draft overlays
Line [1] renders patient demographics, line [2] renders the Completeness Manifest (active tier, included counts, and any folded, excerpted, or omitted counts), and lines [3]..[N] render dated, source-labeled clinical entries, followed by any unsaved client draft notes or flags ([P1]..[PM]).
Because Region 1 depends only on the patient's datasets, active scope, model tokenizer, prompt template, and target chart budget, follow-up questions hit the same prefix cache key and reuse cached GPU KV states.
Region 2 · Turn suffix
Conversation history and enricher output
Prior turns and the current user question sit in messages[], with enabled enricher blocks appended to the active user turn inside a shared 2,048-token ceiling.
Keeping question-dependent context in Region 2 leaves the condensed chart untouched and lets individual enrichers be toggled on or off without altering Region 1.
System prompt rules (wahs-default.txt)
Rule
Purpose
Numeric and typed citation tags only
Supporting facts use only [N] (chart and recovered entries), [P] (unsaved patient overlays), or [K] (public reference snippets). Prohibiting square brackets around lab names or section headers prevents unmapped pseudo-citations.
Manifest-checked abstention
The model checks [2] first: if nothing was omitted and an item is absent, it reports that no record is documented; if history was condensed or scoped, it states what is visible and notes that omitted history may hold earlier entries.
Quantitative and temporal fidelity
Values, units, comparators, reference ranges, vaccine dose counts, and ISO YYYY-MM-DD dates are copied verbatim. Single measurements (n=1) are not extrapolated into trends, and relative time is anchored to the latest clinical event date rather than administrative or device dates.
Non-prescriptive clinical framing
Responses distinguish active from stopped or historical items, never instruct a patient to start, stop, or adjust medications on their own, and suggest follow-up questions for the care team.
Condensation
Three-tier deterministic condensation
wahs_core operates on typed clinical items extracted from FHIR R4 rather than raw text chunks. It applies no static item caps or fixed note truncation lengths, stepping down only when the rendered chart exceeds the active token budget.
Tier
Behavior
Rationale
Tier 0 · Verbatim
Strips FHIR wrapper boilerplate, invalidated entries (entered-in-error, cancelled), and duplicate Base64 notes; emits all remaining items and full clinical notes verbatim.
Once transport overhead is stripped, typical outpatient multi-clinic charts fit inside a 16k budget with zero information loss.
Tier 1 · Uniform RLE folding
Keeps the HL7 IPS safety core, acute encounters, active care plans, imaging, and full notes verbatim. Run-length folds repeated historical observations, panels, immunizations, historical meds, resolved conditions, procedures, and routine visits into the latest entry plus count, date span, numeric min..max range, and merged memberUuids.
Serial vitals, recurring lab panels, and routine visits account for most token growth in longitudinal records. Folding preserves span, bounds, and source UUIDs without domain-specific heuristics.
Tier 2 · IPS core & note horizon
Reserves the HL7 IPS safety core (patient header, active allergies, active conditions, active medications, active devices, and folded immunizations), binary-searches a monotonic recency prefix across remaining sections, and binary-searches a dynamic character horizon across included notes.
Guarantees safety-critical active problems, allergies, and medications are retained under tight budgets while allocating remaining capacity smoothly across clinical narratives and logging exact omitted counts in [2].
Structural vs. abstractive compression. Pre-summarizing a chart with a language model risks silent omissions, altered values, and loss of per-resource citation links. Deterministic structural condensation is reproducible, strictly monotonic as token budgets increase, and preserves exact FHIR resource IDs (including memberUuids across folded series) on every line.
Context Enrichment
Question-aware context enrichment
Enrichers supply structured facts or retrieved spans that are tedious or error-prone for a model to derive from a condensed chart alone. Each module runs deterministically under its own token cap, writes only to Region 2, and emits an explicit disclosure in x_wahs.enrichers.
Module
Failure mode addressed
Mechanism
temporal
Date arithmetic slips and confusion between historical and recent measurements.
Missed therapeutic duplication across brand/generic names and unstated reference ranges.
Queries an embedded SQLite knowledge base (CIEL, RxNorm/ATC, CDC CVX/ACIP, LOINC) for active ingredients, ATC drug classes, vaccine series rules, and standard lab intervals.
note_rag
Relevant narrative details truncated when Tier 2 excerpts long hospital or consult notes.
Runs single-patient Okapi BM25 with terminology synonym expansion over unseen note spans, registering sequential [N] citations. Inactive when all notes fit verbatim.
overflow_lookup
Question-specific older structured entries omitted under tight Tier 2 budgets.
Runs IDF-weighted BM25 and code matching over omitted ClinicalItem records and restores matching entries with sequential [N] citations. Inactive when nothing was omitted.
guideline_kb
Limited parametric clinical reference knowledge in smaller open-weight models.
Matches chart codes against an embedded SQLite FTS5 index of public guideline snippets, cited as [K1]..[KM]. Kept opt-in (full-enriched) so baseline clinical grounding stays separate from external reference text.
Hosted deployments default to core-enriched (the first four modules). Because note_rag and overflow_lookup self-gate on Tier 2 omissions, Tier 0 charts run only lightweight temporal and terminology lookups.
Model Orchestration
Single-pass orchestration vs. multi-step alternatives
Pattern
Trade-offs
Role in WAHS
Raw FHIR in an unbounded window
Requires no parser, but wastes context capacity on JSON syntax and degrades attention over multi-thousand-resource exports.
Evaluation control arm only.
Multi-step agentic tool loops
Allows iterative search over tiny summaries, but adds round-trip latency and fails silently when a model skips a needed lookup or queries the wrong term.
Not used; deterministic retrieval runs pre-turn instead.
Multi-model summarize- or verify-chains
Can filter outputs, but multiplies GPU cost and time-to-first-token while complicating direct citation mapping.
Not used on interactive requests; multi-judge verification runs offline in evaluation.
Deterministic pre-assembly + single LLM call
Bounded preparation latency, single generation pass, inspectable prompt state via /v1/wahs/context/preview, and orthogonal module flags.
Production and sandbox path.
Model Selection
Open-weight model tiers
Standardizing on three open-weight tiers within the Gemma 4 family keeps the chat template, offline SentencePiece tokenizer, and citation/abstention behavior aligned from shared datacenter GPUs down to laptops.
Alias
Architecture
Target hardware
Operating role
wahs-26b (default)
Gemma 4 26B-A4B sparse MoE (~4B active parameters per token)
Shared university GPU server
Hosted default for multi-source synthesis and Tier-2 retrieval integration, combining 26B capacity with 4B active-parameter throughput.
wahs-12b
Gemma 4 12B dense
Single 24 GB GPU or 32-64 GB unified-memory workstation
Self-hosted clinic or workstation tier when server-grade VRAM is unavailable.
wahs-e4b
Gemma 4 E4B
Laptops and CPU/edge devices
Low-footprint tier for constrained hardware; pairs well with full-enriched when extra clinical reference context is helpful.
Because clients address models through logical aliases (WAHS_MODEL_MAP_JSON) and standard OpenAI /v1 payloads, substituting a new open-weight model family requires only updating server configuration and selecting the matching offline tokenizer family.
Context Sizing
Chart budgets and KV-cache sizing
Target chart budget
16k default with retrieval recovery
Even when a model supports very long windows, packing tens of thousands of tokens of repetitive history dilutes attention across clinical details and slows prefill. Defaulting the condensed chart to 16,384 tokens keeps Tier 0 records intact while letting note_rag and overflow_lookup pull in question-specific details from larger Tier 2 records. Callers can override the budget from 2k to 64k.
Upstream KV allocation
Fixed 64k num_ctx pin
Changing Ollama's num_ctx per request forces a full model reload whenever a user switches budget presets, while oversized allocations strain shared GPU memory. Pinning WAHS_OLLAMA_NUM_CTX=65536 accommodates every chart budget up to 64k inside a single warm KV slot without reloads. Mechanics are covered under Architecture: Token accounting.
Privacy & Provenance
Authorization, selective disclosure, and provenance
Access control and selective sharing are enforced in deterministic infrastructure rather than prompt instructions. Per-user data access is gated by Keycloak bearer tokens at fhir-auth and verified again by single-patient scope checks in wahs-engine before extraction, with zero server-side chat persistence. Selective sharing with clinicians or family members is handled by client-side JWE encryption in SMART Health Links (with standards-based HL7 DS4P segmentation as a separate platform track) rather than heuristic prompt redaction. Every engine response attaches an HL7 AI-Provenance resource recording the resolved model, profile, prompt SHA-256, active enrichers, and human_review_required: true.
Evaluation
Factorial evaluation design
Because condensation budgets, profiles, individual enrichers, and model aliases are orthogonal request parameters, wahs-engine can be evaluated across controlled ablations without code changes. Using the clinical AI validation harness, candidate configurations are tested on synthetic multi-clinic charts and de-identified hospital records (MIMIC-IV-FHIR), comparing raw FHIR inputs, un-enriched condensation across token budgets, and individual or combined enricher modules across model tiers under blinded multi-judge rubric grading for clinical accuracy, completeness, citation validity, abstention, and safety.
Published study protocols, score tables, and full question-level transcripts are maintained at WAHS Evaluation Reports ↗.
Limitations
Current limitations and open questions
Dataset and judge scope: Evaluations to date run on synthetic multi-clinic personas and de-identified hospital records with blinded automated judges; clinician-adjudicated calibration and prospective usability studies with patients remain ahead.
Upstream EHR coding quality: Deterministic folding, unit-checked trend math, and terminology lookups depend on source coding consistency; uncoded free-text labs, missing units, or undated entries limit what rule-free extraction can normalize.
Complex cross-document timelines: Single-pass generation with BM25 note retrieval handles targeted lookup and medication/problem reconciliation well, whereas questions requiring multi-hop reasoning across dozens of long inpatient notes remain constrained by single-pass attention.
Upstream web chat parity: The synced upstream /api/health-chat tab in shl-ips routes through wahs-engine, but does not yet surface interactive [N] provenance drawers or pass per-resource UI selection filters (unlike the primary Ask WAHS view).
Non-diagnostic scope: Outputs are designed to help patients review records and prepare questions for a clinician, not to provide autonomous clinical decision support.
WA Health Summary is an exploratory research and demonstration project using synthetic and de-identified records. AI outputs can contain errors and do not constitute medical advice or replace clinical review.