WA Health Summary

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.

Updated November 26, 2026 · Source: pmanko/wahs-engine ↗ · Apps: shl-ips ↗ · wahs-mobile-frontend ↗ · Sandbox: wahs-demo.openclinai.org ↗

Core architectural invariants

  1. 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.
  2. 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.
  3. 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.
On this page
  1. 5-stage pipeline
  2. Worked trace
  3. Isolation & caching
  4. Condensation & enrichers
  5. API & SSE contract
  6. Profiles & 5 enrichers
  7. Budgets & 64k pin
  8. Runtime config
  9. Release milestones

Part 1 · End-to-End Flow

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.

WAHS Engine Five-Stage End-to-End Pipeline Five sequential stages: Stage 1 FHIR Sources (HAPI R4 star-graph datasets, My Story, IPS, or isolated sandbox bundles), Stage 2 Zero-Privilege Auth (Keycloak JWT via fhir-auth proxy and meta.lastUpdated freshness check), Stage 3 Extract and Condense (wahs_core SHA-256 note dedupe and 3-tier verbatim-first condensation into [1]..[N] prefix), Stage 4 Profile, Prompt and Enrichers (wahs-default prompt plus 5 modular generalizable enrichers in turn suffix), Stage 5 LLM and Provenance (OpenAI /v1 streaming at pinned 64k num_ctx returning clickable [N]/[P]/[K] citations and HL7 AI-Provenance). 1. FHIR SOURCES HAPI FHIR R4 MasterPatient star-graph Multi-clinic EHR imports My Story / Goals / IPS Sandbox Mode (isolated): /bundles:ro or JSON upload Up to 7,099+ entries (22 MB raw FHIR JSON) 2. ZERO-PRIV AUTH fhir-auth Proxy Forwards user Bearer JWT Zero HAPI admin creds Single-patient guard Freshness (~10 ms): meta.lastUpdated check Applies wahs.chart_scope & unsaved draft overlays 3. CONDENSE wahs_core Engine Tier 0: Verbatim full chart Tier 1: Uniform series RLE Tier 2: IPS core + notes Region 1: Stable Prefix [1]..[N] + [2] Manifest Exact Gemma 4 tokenizer X-WAHS-Prefix-Hash LRU 4. PROMPT & ENRICH Profiles + 5 Modules temporal · terminology_kb note_rag · overflow_lookup guideline_kb (opt-in) Region 2: Turn Suffix Append-only (≤ 2,048 tok) Zero-import baseline path Default: core-enriched (4/5) 5. LLM & PROVENANCE OpenAI /v1 Stream wahs-26b | 12b | e4b Pinned num_ctx=65536 15s SSE keepalives x_wahs Provenance [N] [P] [K] → FHIR UUID HL7 AI-Provenance Warm TTFT < 0.6s Thin Client Surfaces (Zero Clinical Business Logic) WAHS Web App (shl-ips :4000) · WAHS Mobile Companion (:4001) · Isolated Explorer Sandbox (wahs-demo.openclinai.org)
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.
Isolated Sandbox Runtime

wahs-sandbox-engine (wahs-demo.openclinai.org)

  • Runs the exact same container image (wahs-26b, 16k, core-enriched, 64k num_ctx) attached strictly to openclinai-edge with zero wahs-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. tier: 0 (verbatim), omitted_clinical_items: 0, stable X-WAHS-Prefix-Hash.
3. Core Enrichers (4/5) 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.

Core Mechanism

Continuous 3-tier verbatim-first condensation (wahs_core)

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.

Tier Activation Condition Transformation Applied Completeness Guarantee
Tier 0 · Verbatim Full Chart Extracted chart fits target budget Strips FHIR JSON wrapper overhead, drops entered-in-error/not-done, SHA-256 deduplicates identical Base64 notes; emits every resource verbatim. 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.
POST /v1/chat/completions Authorization: Bearer <keycloak_jwt> Content-Type: application/json { "model": "wahs-26b", "stream": true, "messages": [ { "role": "user", "content": "What active medications am I taking and are there any fall risks?" } ], "wahs": { "target_budget_tokens": 16384, "profile": "core-enriched", "enrichers": ["temporal", "terminology_kb", "note_rag", "overflow_lookup"], "chart_scope": { "include_sources": [], "exclude_sources": [], "include_categories": [], "exclude_categories": [], "include_resource_types": [], "exclude_resource_types": [], "ips_bundle_id": null, "date_from": null, "date_to": null }, "overlay_resources": [] } } --> Immediate SSE Frame 1 (before LLM prefill completes): data: {"object":"chat.completion.chunk","x_wahs_stream":{"event":"context_ready","prefix_cache_key_hash":"9e3a81c4f012","citation_map":{...}}} --> Heartbeat every 15s while upstream GPU queues or prefills (prevents proxy idle timeouts): : keepalive --> Streamed OpenAI content deltas (with <think> stripped), or structured SSE error frame on upstream failure: data: {"error":{"type":"upstream_error","message":"Southbound LLM stream returned HTTP 503."}} --> Final SSE chunk attaches full x_wahs provenance + HL7 AI-Provenance: { "x_wahs": { "citation_map": { "12": { "index": "12", "resourceType": "MedicationRequest", "id": "med-zolpidem-01", "date": "2026-09-14", "source": "Overlake Sleep Medicine", "display": "Zolpidem tartrate 10 MG Oral Tablet" } }, "condensation": { "tier": 0, "tier_name": "verbatim", "profile_id": "core-enriched", "prompt_id": "wahs-default", "actual_tokens": 4812, "budget_effective": 16384, "enrichment_tokens": 284, "context_window": 65536, "upstream_num_ctx": 65536, "omitted_clinical_items": 0, "cache_hit": true }, "enrichers": [ { "id": "temporal", "tokens": 112 }, { "id": "terminology_kb", "tokens": 172 }, { "id": "note_rag", "tokens": 0 }, { "id": "overflow_lookup", "tokens": 0 } ], "ai_provenance": { "resourceType": "Provenance", "profile": "http://hl7.org/fhir/uv/aitransparency/StructureDefinition/AI-Provenance", "recorded_model": "ollama/gemma4:26b", "requested_model": "wahs-26b", "engine": "wahs-engine/0.2.0", "human_review_required": true } } }

Modular Context Enrichers

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).
Profile ID Auto Budget Enrichers Enabled
baselineFull windowNone (zero-import verbatim condensation control)
temporal32,768temporal
terminology32,768terminology_kb
temporal-terminology32,768temporal, terminology_kb
rag-overflow16,384note_rag, overflow_lookup
core-enriched (Default)16,384temporal, terminology_kb, note_rag, overflow_lookup
full-enriched32,768All 5 generalizable enrichers (+ guideline_kb)

Token Sizing & GPU Performance

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).

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_URLhttp://fhir-auth:8080/fhirPer-user FHIR proxy URL. Startup aborts if pointed at fhir-internal.
LLM_BASE_URLhttps://llm.co.dev.cirg.uw.edu/v1Any OpenAI-compatible southbound gateway (LiteLLM, Ollama, vLLM, llama-router).
WAHS_DEFAULT_MODELwahs-26bDefault model alias mapped via WAHS_MODEL_MAP_JSON to ollama/gemma4:26b.
WAHS_DEFAULT_PROFILEcore-enrichedDeclarative profile from profiles.yaml (4/5 generalizable enrichers).
WAHS_PREFERRED_CHART_TOKENS16384Auto-mode chart budget target; explicit caller budgets override up to window ceiling.
WAHS_CONTEXT_WINDOW65536Physical prompt ceiling enforced by exact offline tokenizers before upstream calls.
WAHS_OLLAMA_NUM_CTX65536Warm Ollama KV-cache pin (set 0 / omit to defer to server default).
WAHS_ALLOW_LOCAL_BUNDLE_MODEfalse (prod)
true (sandbox)
Permits inline wahs.fhir_bundle and wahs.bundle_id without Keycloak JWT; strictly false in production.
WAHS_DEMO_BUNDLES_DIRunset (prod)
/bundles (sandbox)
Read-only FHIR R4 bundle directory for /v1/wahs/demo-bundles (returns 404 when unset).

Build Record

Architecture milestones and verification history

Date Milestone Shipped Capability & Verification
Nov 26, 2026 Warm 64k Pin, 5-Enricher UI & Isolated Sandbox Engine 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).
Nov 25, 2026 Slim Baseline & Declarative profiles.yaml Decommissioned legacy med-agent-hub wahs-* profiles; introduced declarative profiles.yaml, CIEL/standards terminology_kb, and lazy-loaded 5-module enricher pipeline; quarantined heuristic graph.py.
Nov 16, 2026 900-Cell 4-Pathway H200 Study 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.

Back to top