Washington Health Summary (WAHS) · Architecture & Builder Reference
From multi-source FHIR R4 records to cited open-weight answers.
wahs-engine is the standalone, zero-privilege middleware connecting WA Health Summary frontends (the SvelteKit Web App, Mobile Companion, and isolated Explorer Sandbox) to patient FHIR R4 records and pluggable open-weight LLMs. This page opens with the 5-stage visual flow and a real patient trace, followed by the full builder wire contract, enricher catalog, and runtime configuration.
Zero database credentials in the AI layer. Production wahs-engine never talks directly to internal HAPI FHIR; it forwards the signed-in caller's Keycloak Bearer JWT through fhir-auth (uwcirg/jwt-proxy) on every turn.
Prefix-stable verbatim-first condensation + append-only enrichers. The query-invariant condensed chart ledger ([1]..[N]) stays byte-identical in the system prefix for GPU KV-cache reuse, while opt-in modular enrichers (core-enriched: 4 of 5 generalizable modules) attach strictly to the turn suffix.
Warm 64k num_ctx pin with full OpenAI /v1 portability. Every request across 2k to 64k target budgets runs inside one warm 65,536-token Ollama KV slot (default wahs-26b + 16k chart + core-enriched), eliminating 128k VRAM stalls and cold model reloads while returning inline [N] FHIR citations and HL7 AI-Provenance.
Five stages from FHIR sources to verifiable provenance
Every user turn moves linearly through five clear stages with explicit security and caching boundaries. Client apps stay thin presentation shells with zero clinical condensation or prompt business logic.
Two-region prompt split: Stage 3 produces a query-invariant chart prefix (Region 1) that stays cached in GPU VRAM across follow-up questions. Stage 4 appends bounded, question-aware enrichers strictly to the turn suffix (Region 2) so prefix KV caching is never invalidated.
Production Runtime
wahs-engine (Live HAPI + Keycloak)
Attached to private wahs-net; calls http://fhir-auth:8080/fhir with the caller's Keycloak JWT.
WAHS_ALLOW_LOCAL_BUNDLE_MODE=false and WAHS_DEMO_BUNDLES_DIR unset (demo bundle endpoints disabled and return HTTP 404).
Serves both wahs-shl-ips and wahs-mobile-frontend BFFs over internal Docker networking.
Isolated Sandbox Runtime
wahs-sandbox-engine (wahs-demo.openclinai.org)
Runs the exact same container image (wahs-26b, 16k, core-enriched, 64knum_ctx) attached strictly to openclinai-edge with zerowahs-net access to HAPI, Keycloak, or Postgres.
Mounts 10 de-identified/synthetic FHIR R4 bundles read-only at /bundles:ro and supports user-uploaded bundles up to 25 MB.
Caddy exposes browsing and /v1/wahs/context/preview publicly while gating /v1/chat/completions behind the unified OpenClinAI Google whitelist cookie (or zero-sign-in Local BYO-Model mode).
Worked Trace
Tracing a real Margaret Chen question end to end
Question: "What active medications am I taking, and are there any fall or sedation risks I should ask my doctor about?" (Margaret Chen: 82-year-old multi-clinic geriatrics & Overlake sleep record, 448 FHIR R4 resources across 3 sources).
Stage
What wahs-engine Executes
Observable Artifact / Timing
1. Auth & Freshness
Forwards Margaret's Keycloak JWT to fhir-auth, traverses linked patient datasets, and compares meta.lastUpdated stamps against the per-user dataset cache.
~10 ms on warm turns; re-fetches only newly synced or edited datasets.
2. Extraction & Tier 0
Strips FHIR JSON boilerplate, drops entered-in-error entries, SHA-256 deduplicates identical Base64 notes, and packs all 448 resources verbatim because they fit inside the 16,384-token chart budget.
temporal attaches date anchors and lab trajectories; terminology_kb maps RxNorm/CIEL classes (Beers Criteria CNS depressants, anticoagulants, missing reference ranges) without bracket pseudo-citations; note_rag and overflow_lookup no-op cleanly because Tier 0 dropped zero items.
Appended to turn suffix (~280 tokens), preserving Region 1 KV cache.
4. Southbound Stream
Immediately emits SSE context_ready (carrying the full citation_map), sends the prompt to ollama/gemma4:26b pinned at num_ctx=65536, emits : keepalive every 15s if queued, and strips any model <think> blocks.
Live cloud verification: TTFT ~4.7s (0.58s warm GPU prefill), total ~7.8s.
5. Clickable Provenance
Every medication and clinical risk cites numeric [N] tags only (rule enforced in wahs-default.txt). Clicking [12] in Web, Mobile, or Sandbox opens the exact FHIR R4 resource JSON, clinic source, and date.
0 malformed pseudo-citations; HL7 AI-Provenance attached on final frame.
State, Isolation & Caching
Four decoupled state layers with zero server chat database
Keeping authentication, chat history, chart freshness, and GPU KV-cache reuse independent removes stateful session databases from the AI server and eliminates cross-patient cache leakage.
State Layer
Owner
Contract & Security Guarantee
1. Identity & Ownership
Keycloak · fhir-auth
Authorization: Bearer <jwt> travels from app BFF to wahs-engine to fhir-auth. Single-patient scope enforcement strips any foreign Patient/ reference before extraction.
2. Chat Turn History
Browser session memory
Stateless OpenAI messages[] array sent each turn. No conversation database lives in wahs-engine or on the GPU host.
3. Extracted & Prefix LRU
wahs-engine RAM
Partitioned strictly by (verified_sub, datasets_fingerprint, scope_hash, tokenizer_family, prompt_sha256, budget) with bounded entry/byte caps and TTL eviction.
4. GPU KV-Cache Slot
UW CIRG H200 / Ollama
Pinned num_ctx=65536 keeps one warm KV slot across all 2k to 64k budget choices, reusing Region 1 attention states on follow-up turns in under 0.6s.
wahs_core is a pure-Python standard-library FHIR R4 preparation engine. It strips transport JSON noise and duplicate notes without clinical mutation, keeping records 100% verbatim whenever they fit and compressing smoothly only when a chart exceeds the active budget.
0 omitted items; 100% intact narratives and intraday timestamps.
Tier 1 · Uniform Series Folding
Verbatim chart exceeds budget
Folds repeated identical historical lab/vital series uniformly by LOINC code and unit, keeping earliest, min/max peak, and latest values.
Zero lost safety-core entries; preserves longitudinal trends without arbitrary cutoffs.
Tier 2 · IPS Safety Core & Water-Filling
Folded chart still exceeds budget
Reserves the HL7 IPS safety core ↗ (allergies, active meds, active problems, implants), packs remaining items by recency, and water-fills clinical notes across remaining tokens.
Writes exact omitted counts to [2] Completeness Manifest; note_rag and overflow_lookup recover question-relevant dropped items.
Part 2 · Builder Reference
HTTP endpoints, OpenAI /v1 request schema, and SSE contract
Any client frontend, evaluation harness, or local developer tool talks to wahs-engine through standard OpenAI endpoints plus three discovery/preview endpoints.
Endpoint
Auth
Purpose
GET /healthz
Public (internal)
Returns version, default_model, default_profile, default_target_budget_tokens, context_window, and demo_bundles_enabled.
GET /v1/models
Public
Lists configured model aliases (wahs-26b, wahs-12b, wahs-e4b) and upstream availability.
GET /v1/wahs/profiles
Public
Returns declarative profiles.yaml catalog, available_enrichers (5 modules), target_context_options, and active defaults.
POST /v1/wahs/context/preview
Bearer JWT (or sandbox bundle)
Runs assembly, condensation, and enrichers without calling the LLM; returns chart_text, exact system_prompt, X-WAHS-Prefix-Hash, and x_wahs.
POST /v1/chat/completions
Bearer JWT (or gated sandbox)
Standard OpenAI chat completion (stream: true or false) with wahs options, immediate context_ready SSE frame, 15s keepalives, and x_wahs provenance.
GET /v1/wahs/demo-bundles GET /v1/wahs/demo-bundles/{id}/resources
Opt-in sandbox only (404 in prod)
Active only when both WAHS_ALLOW_LOCAL_BUNDLE_MODE=true and WAHS_DEMO_BUNDLES_DIR are set; powers Step 1 FHIR browsing and cached wahs.bundle_id lookups.
Declarative profiles.yaml and the 5 generalizable enrichers
Enrichers are lazy-loaded from wahs_extensions only when enabled (zero import overhead on raw baseline). Each module enforces a strict per-enricher token cap inside a shared WAHS_MAX_ENRICHMENT_TOKENS=2048 ceiling and emits strictly into the turn suffix.
Enricher ID
Token Cap
In Core (4/5)?
What It Adds to the Turn Suffix
temporal
450
Core
Explicit date anchors, relative elapsed times, and chronological numeric lab deltas so models do not confuse old and recent labs.
terminology_kb
550
Core
Deterministic CIEL, RxNorm, LOINC, and CDC ACIP lookup normalizing drug classes, brand/generic overlaps, and lab reference ranges (plain text, zero bracket pseudo-citations).
note_rag
1,100
Core
Okapi BM25 passage retrieval over unseen spans of long clinical notes whenever Tier 2 excerpted or omitted clinical narratives ([P1]..[Pk] citations).
overflow_lookup
550
Core
Recovers question-relevant structured FHIR records dropped under tight Tier 2 budgets and registers them back into the sequential [N] citation map.
guideline_kb
500
Opt-in (5/5 All)
Attaches public clinical guideline snippets (KDIGO, ADA, ACC/AHA, Beers Criteria) cited as [K1]..[Km] for care-gap and medication safety questions.
Quarantined experimental module (graph.py): The earlier heuristic entity graph (experimental.clinical_reconciliation) is quarantined behind WAHS_ALLOW_EXPERIMENTAL_ENRICHERS=true (disabled in production and sandbox deployments) because its regex-based cross-clinic rules did not generalize cleanly beyond synthetic fixtures. All production apps and benchmarks use the 5 generalizable modules above, defaulting to core-enriched (4/5).
Dynamic chart budgets and why num_ctx is pinned at 64k
wahs-engine separates chart condensation budget (how many tokens the condensed record may occupy, default 16k in Auto mode or explicit caller selection from 2k to 64k) from upstream Ollama KV-cache allocation (WAHS_OLLAMA_NUM_CTX=65536).
Warm 64k KV Pin
Zero model reloads across 2k to 64k presets
Why not 128k? Requesting num_ctx=131072 caused Ollama KV-cache overallocation and >120s stalls on shared GPUs.
Why 64k instead of 32k? Apples-to-apples UW CIRG H200 benchmarks showed gemma4:26b cold load at 64k (29.33s) is effectively identical to 32k (30.19s), and warm TTFT is identical (0.28s vs 0.27s), while keeping one single warm KV cache across every UI budget toggle from 2k through 64k with zero model reload thrashing.
Budget Resolution Rules
Exact offline token accounting on every turn
Auto mode: Uses WAHS_PREFERRED_CHART_TOKENS (16,384) when set, falling back to profile preferred tokens or available context window minus exact system framing, conversation history, active enricher cap, and output tokens.
Explicit override: Caller wahs.target_budget_tokens (e.g. 2k, 8k, 32k, 64k) is honored directly and clamped strictly to physical WAHS_CONTEXT_WINDOW (65,536), never silently truncated upstream.
Operations Reference
Key runtime environment variables
Variable
Cloud Default
Behavior
WAHS_FHIR_AUTH_BASE_URL
http://fhir-auth:8080/fhir
Per-user FHIR proxy URL. Startup aborts if pointed at fhir-internal.
LLM_BASE_URL
https://llm.co.dev.cirg.uw.edu/v1
Any OpenAI-compatible southbound gateway (LiteLLM, Ollama, vLLM, llama-router).
WAHS_DEFAULT_MODEL
wahs-26b
Default model alias mapped via WAHS_MODEL_MAP_JSON to ollama/gemma4:26b.
WAHS_DEFAULT_PROFILE
core-enriched
Declarative profile from profiles.yaml (4/5 generalizable enrichers).
WAHS_PREFERRED_CHART_TOKENS
16384
Auto-mode chart budget target; explicit caller budgets override up to window ceiling.
WAHS_CONTEXT_WINDOW
65536
Physical prompt ceiling enforced by exact offline tokenizers before upstream calls.
WAHS_OLLAMA_NUM_CTX
65536
Warm Ollama KV-cache pin (set 0 / omit to defer to server default).
WAHS_ALLOW_LOCAL_BUNDLE_MODE
false (prod) true (sandbox)
Permits inline wahs.fhir_bundle and wahs.bundle_id without Keycloak JWT; strictly false in production.
WAHS_DEMO_BUNDLES_DIR
unset (prod) /bundles (sandbox)
Read-only FHIR R4 bundle directory for /v1/wahs/demo-bundles (returns 404 when unset).
Pinned WAHS_CONTEXT_WINDOW & WAHS_OLLAMA_NUM_CTX at 65536; shipped 3-part selector + Enrichers: 4/5 (Core) menu in shl-ips, wahs-mobile-frontend, and zero-logic wahs-demo backed by isolated wahs-sandbox-engine; added immediate context_ready, 15s SSE keepalives, and numeric-only citation hygiene; validated across Run 3A (n=225) and Run 3B (n=144).
Evaluated condensation, note RAG, KB rules, and tool-calling across 75 scenarios and Gemma 4 26B / 12B / E4B on UW CIRG H200 (99.8% resolved citations; confirmed agentic 2k tool loops underperform condensation).
Nov 11, 2026
Standalone wahs-engine & Zero-Privilege fhir-auth
Shipped pure-standard-library wahs_core, Keycloak JWT pass-through via uwcirg/jwt-proxy, multi-dataset star-graph pooling, and service-to-service BFF integration in both Web and Mobile frontends.