WA Health Summary

WA Health Summary · LLM Strategy

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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
On this page
  1. Design constraints
  2. Prompt structure
  3. Condensation
  4. Context enrichment
  5. Model orchestration
  6. Model selection
  7. Context sizing
  8. Privacy & provenance
  9. Evaluation design
  10. Current limitations

Constraints

Design constraints

Record size and FHIR noise

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.

Two-Region Prompt Layout and Multi-Turn KV-Cache Reuse Left: Assembled prompt payload divided into Region 1 (System prefix: wahs-default.txt rules, [1] Patient header, [2] Completeness Manifest, [3]..[N] Condensed clinical ledger, and [P1]..[PM] Unsaved draft overlays) and Region 2 (Turn suffix: prior messages[] turns plus active user question and capped enricher blocks up to 2,048 tokens). Right: Turn 1 prefills both regions and caches Region 1 in GPU VRAM under X-WAHS-Prefix-Hash; Turn 2+ hits the cached Region 1 KV state and prefills only Region 2. REGION 1 · SYSTEM PREFIX (messages[0] · Question-Invariant) X-WAHS-Prefix-Hash Grounding & Citation Rules (wahs-default.txt) cite only [N] [P] [K]; check [2] [1] Patient Header + [2] Completeness Manifest tier, included & omitted counts [3]..[N] Condensed Clinical Ledger (dated, source-labeled FHIR items) 16k default (2k..64k) [P1]..[PM] Unsaved Client Draft Overlays (optional wahs.overlay_resources) ≤ 5,120 bytes REGION 2 · TURN SUFFIX (messages[1..k] · Question-Specific) Prior Conversation Turns (oldest trimmed if window full) User Question + Enricher Appendix (temporal, terminology_kb, RAG, [K]) ≤ 2,048 tok cap Turn 1: Initial Question 1. Encodes Region 1 + Region 2 in one pass 2. Caches Region 1 attention KV states in the warm 64k GPU slot Prefix stored under X-WAHS-Prefix-Hash Turn 2+: Follow-Up or Enricher Toggle 1. Region 1 bytes stay identical 2. GPU KV Cache HIT on Region 1 (zero chart re-prefill even if enrichers change) 3. Prefills only the short Region 2 suffix Fast follow-ups + clean module ablations
Two-region prompt split: Isolating all question-dependent enrichers in Region 2 guarantees that Region 1 remains byte-identical across follow-up turns and across enricher ablations.
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 onlySupporting 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 abstentionThe 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 fidelityValues, 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 framingResponses 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.

Three-Tier Monotonic Condensation and Self-Gated Tier-2 Recovery Flowchart from FHIR R4 extraction through token budget checks using the offline Gemma 4 tokenizer: if the chart fits budget, Tier 0 renders all items and notes verbatim and note_rag/overflow_lookup stay inactive; if Tier 0 exceeds budget, Tier 1 applies uniform RLE series folding while keeping the IPS safety core and full notes intact; if Tier 1 still exceeds budget, Tier 2 reserves the IPS safety core, binary-searches a monotonic recency prefix and dynamic note horizon, logs omissions in [2] Completeness Manifest, and activates self-gated note_rag and overflow_lookup to recover question-relevant passages and omitted records into Region 2. FHIR R4 Extraction wahs_core/extractors.py Drops entered-in-error & cancelled resources SHA-256 note dedupe Offline Gemma 4 count Tier 0 · Verbatim Ledger (tokens ≤ budget) Emits 100% of extracted items and full clinical notes verbatim. folded = 0 · excerpted = 0 · omitted = 0 note_rag & overflow_lookup self-gate OFF (nothing omitted) Tier 1 · Uniform RLE Folding (Tier 0 > budget) IPS safety core, acute visits, care plans, imaging & full notes intact. Folds repeated labs, vitals, panels, meds, conditions & visits into: latest + count + date span + min..max + merged memberUuids If tokens ≤ budget: omitted = 0 (retrieval enrichers stay OFF) Tier 2 · IPS Core + Note Horizon (Tier 1 > budget) 1. Reserves HL7 IPS safety core (allergies, active meds/conds/devices, imms) 2. Binary-searches monotonic recency prefix + dynamic note char horizon 3. Logs exact excerpted & omitted counts in [2] Completeness Manifest if > budget if > budget Region 1 · System Prefix [1] Patient + [2] Manifest [3]..[N] Condensed Chart Question-invariant KV prefix Fits strictly inside budget_effective Self-Gated Tier-2 Recovery • note_rag (cap 1,100t): BM25 over unseen note tails → [N] • overflow_lookup (cap 550t): BM25 + code match on omitted → [N] Appended to Region 2 (turn suffix)
Condensation and recovery loop: Retrieval modules stay dormant on Tier 0 and Tier 1 charts, activating automatically under Tier 2 to recover question-relevant note passages and omitted structured items without mutating Region 1.
Tier Behavior Rationale
Tier 0 · VerbatimStrips 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 foldingKeeps 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 horizonReserves 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
temporalDate arithmetic slips and confusion between historical and recent measurements.Computes chart anchor date, lookback cutoffs, elapsed vaccine intervals, and unit-checked numeric lab deltas.
terminology_kbMissed 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_ragRelevant 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_lookupQuestion-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_kbLimited 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

Clinical Record Orchestration Patterns Compared Four horizontal swimlanes comparing orchestration patterns: A. Raw FHIR in unbounded context (JSON token bloat and diluted attention); B. Multi-step agentic tool loops (multiple LLM round-trips and silent lookup misses); C. Multi-model summarize chains (unverified intermediate summary loses 1-to-1 resource UUID links); D. WAHS deterministic pre-assembly plus single LLM call (wahs_core condensation, bounded enrichers, inspectable context preview, one streamed LLM call, and direct [N]/[P]/[K] UUID provenance). A. Raw FHIR Window Control baseline only Raw FHIR JSON (up to 22 MB) 1 Oversized LLM Call JSON syntax wastes budget; long-context attention dilution & VRAM stalls B. Agentic Tool Loop Not used in WAHS Tiny Summary LLM ↔ Search Tools (1..k turns) Model decides whether & what to query Multi-round latency; silent clinical misses when model skips a needed lookup C. LLM Summarize Chain Not used online LLM #1 Pre-Summarizes LLM #2 Answers Summary 2x GPU cost & latency; paraphrasing breaks 1-to-1 FHIR resource UUID links D. WAHS Pre-Assembly Shipped architecture Deterministic Python Prep wahs_core + capped enrichers 1 Streamed LLM Call Warm prefix KV reuse Predictable latency + inspectable preview + direct [N] / [P] / [K] resource provenance
Why pre-assembly + single pass: Moving extraction, condensation, and BM25 recovery into deterministic Python ahead of generation eliminates tool-skipping failure modes and preserves 1-to-1 resource citations.
Pattern Trade-offs Role in WAHS
Raw FHIR in an unbounded windowRequires 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 loopsAllows 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-chainsCan 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 callBounded 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 serverHosted default for multi-source synthesis and Tier-2 retrieval integration, combining 26B capacity with 4B active-parameter throughput.
wahs-12bGemma 4 12B denseSingle 24 GB GPU or 32-64 GB unified-memory workstationSelf-hosted clinic or workstation tier when server-grade VRAM is unavailable.
wahs-e4bGemma 4 E4BLaptops and CPU/edge devicesLow-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

Warm 64k KV-Cache Slot Partitioning and Gemma 4 Model Tiers Top: A 65,536-token (64k) fixed Ollama num_ctx allocation containing system framing, the 16k default condensed chart (adjustable from 2k to 64k without reloading the model), the capped 2k enricher suffix, conversation turns, output reserve, and warm KV headroom. Bottom: Three Gemma 4 model tiers sharing the same tokenizer and prompt contract across university GPU servers (wahs-26b MoE), 24 GB GPU or unified-memory workstations (wahs-12b), and laptops/CPU edge hardware (wahs-e4b). Pinned Upstream KV Allocation (WAHS_OLLAMA_NUM_CTX = 65,536 tokens) Zero model reloads across 2k..64k Rules ~0.6k Condensed Chart + [P] (16k default) Region 1 KV-cached prefix Enrichers ≤ 2,048 tok Turns + Output History + reply Warm KV Headroom (up to 64k) Accommodates 32k / 64k chart presets Caller target_budget_tokens selectable from 2k to 64k Three Open-Weight Gemma 4 Tiers (Shared Tokenizer & Prompt Contract) wahs-26b (Hosted Default) Gemma 4 26B-A4B Sparse MoE ~4B active params/token · Shared GPU server Multi-source synthesis + Tier-2 recovery wahs-12b (Workstation) Gemma 4 12B Dense Single 24 GB GPU or 32-64 GB unified RAM Self-hosted clinic or desktop deployment wahs-e4b (Laptop / Edge) Gemma 4 E4B Laptops, Apple Silicon, or CPU hosts Low-memory footprint; pairs with full-enriched
Decoupled budget vs. KV slot: Keeping one fixed 64k KV allocation on the GPU host avoids reload stalls when toggling budgets, while offline Gemma 4 tokenizers size each tier across all three model weights.
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.

Back to top