WA Health Summary · Architecture & Builder Reference
WA Health Summary system architecture
WA Health Summary stores patient records in HAPI FHIR R4, authorizes every read through a per-user proxy (fhir-auth), and routes question answering through wahs-engine, a stateless OpenAI-compatible Python service. Client applications (the web app, mobile companion, and public Research Sandbox) handle presentation and session state while delegating FHIR extraction, condensation, enrichment, prompt assembly, and citation mapping to the engine. Design rationale for condensation, context engineering, and model selection is covered under LLM Strategy.
Per-user FHIR authorization.wahs-engine holds no HAPI database or administrative credentials. It forwards the caller's Keycloak bearer token to fhir-auth (uwcirg/jwt-proxy) on every request, aborts startup if configured against fhir-internal, and strips any resource whose subject does not match the authorized patient.
Stateless request handling. Conversation history stays in the client and is passed as an OpenAI messages[] array on each turn. The engine writes no chat transcripts to disk or database; in-memory dataset and prefix caches are partitioned by verified user subject, dataset timestamps, and request scope.
Deterministic context preparation. FHIR extraction, three-tier structural condensation, and optional enrichment modules execute in deterministic Python before a single southbound /v1/chat/completions call.
Structured citation provenance. Inline [N], [P], and [K] tags map through x_wahs.citation_map to source FHIR resources, unsaved client overlays, and public reference snippets. The final response carries an HL7 AI-Provenance record with human_review_required: true.
Platform ownership, shared backend, and client lifecycle
WA Health Summary operates as one unified clinical platform rather than separate web and mobile systems. A permanent core foundation owns patient identity, per-user FHIR R4 authorization, linked clinical and patient-authored datasets, encrypted SMART Health Links sharing, and the canonical SvelteKit web application (uwcirg/shl-ips). A permanent stateless AI middleware service (wahs-engine) powers question answering across routes without holding database or administrative credentials. Beside the canonical web app, a thin mobile UX and evaluation surface (wahs-mobile-frontend) runs against the exact same identity provider, FHIR repository, sharing server, and AI engine so mobile interaction flows and clinical evaluations can advance in parallel before converging into shl-ips.
Permanent clinical platform & canonical web app (uwcirg/shl-ips)Permanent stateless AI middleware (wahs-engine)Temporary mobile UX & evaluation surface (wahs-mobile-frontend, converges into shl-ips)
Single backend, converging frontends: Any record imported in shl-ips or personal note saved in wahs-mobile-frontend writes to the same authorized MasterPatient dataset graph in HAPI FHIR R4 and is immediately reflected in both interfaces and in wahs-engine.
Single source of truth for OIDC identity, per-user FHIR access control, linked clinical and patient-story datasets, and JWE-encrypted SMART Health Links.
Canonical web application
SvelteKit web app (uwcirg/shl-ips, including /api/health-chat and /api/chat)
Permanent frontend
Primary patient-facing application for SMART record imports, IPS summary curation, QR sharing, and grounded question answering; long-term destination for mobile-responsive UX.
Shared stateless AI engine
wahs-engine (wahs_core + wahs_extensions)
Permanent middleware
Stateless Python service behind /api/health-chat and /api/chat. Holds zero HAPI admin credentials, forwards the caller's Keycloak JWT, runs deterministic condensation and enrichers, and emits [N]/[P]/[K] citations with HL7 AI-Provenance.
Parallel mobile UX & evaluation layer
wahs-mobile-frontend (React UI + pass-through BFF implementing the MHCID mobile design flow)
Temporary / retireable
Zero-backend companion layered on the same Keycloak realm, HAPI FHIR datasets, SHL server, and wahs-engine contract so usability studies and clinical evaluations run ahead of schedule; retires as validated mobile workflows merge into shl-ips.
Public Research Sandbox note: For unauthenticated public inspection (Research Sandbox), a separate wahs-sandbox-engine container runs the same wahs-engine image over read-only synthetic bundles on openclinai-edge with no network route to Keycloak, fhir-auth, or HAPI FHIR.
Services & Network Boundaries
Services and network boundaries
The hosted stack runs under Docker Compose behind a Caddy reverse proxy with two Docker networks: wahs-net (internal, carrying all patient FHIR and database traffic) and openclinai-edge (connecting services reachable from Caddy). wahs-sandbox-engine attaches only to openclinai-edge and has no route to HAPI FHIR, Keycloak, or PostgreSQL.
Service
Component
Role
Networks
wahs-shl-ips
SvelteKit app (shl-ips)
WAHS web app and server routes for Ask WAHS (/api/chat) and health record chat (/api/health-chat).
wahs-net, edge
wahs-mobile-frontend
React UI + Node BFF
Mobile companion; BFF proxies /api/chat and preview requests to wahs-engine.
wahs-net, edge
wahs-engine
FastAPI (wahs-engine)
Record assembly, condensation, enrichment, prompt framing, model routing, and provenance.
wahs-net only
wahs-sandbox-engine
Same image, sandbox env
Serves mounted example bundles and user uploads for the Research Sandbox.
edge only
wahs-fhir-auth / wahs-fhir-auth-proxy
nginx + uwcirg/jwt-proxy
Validates Keycloak bearer tokens, stamps security labels on writes, and enforces per-user read access.
Stores JWE-encrypted health summaries and serves shlink:/ manifests.
wahs-net, edge
wahs-db
PostgreSQL 14
Relational storage for HAPI FHIR and Keycloak.
wahs-net only
wahs-auth-gate
Python gate service
Google OAuth allowlist check and HMAC-SHA256 session cookie for hosted demo subdomains.
wahs-net, edge
Southbound LLM host
OpenAI /v1 endpoint
Ollama behind LiteLLM on UW CIRG GPUs, or any OpenAI-compatible server.
outbound HTTPS
Request Pipeline
Five-stage pipeline in wahs-engine
Both POST /v1/chat/completions and POST /v1/wahs/context/preview run Stages 1 through 4; chat completions then execute Stage 5.
Two-region prompt split: Stage 3 builds a system message (Region 1) containing instructions, the condensed chart ([1]..[N]), and any unsaved draft overlays ([P1]..[PM]). Because Region 1 does not depend on the question text, the model host can reuse its KV cache across follow-up turns. Stage 4 appends question-aware enricher blocks to the user turn suffix (Region 2).
Patient-data runtime
wahs-engine
Attached only to wahs-net; reads FHIR via http://fhir-auth:8080/fhir using the caller's bearer token.
WAHS_ALLOW_LOCAL_BUNDLE_MODE=false and WAHS_DEMO_BUNDLES_DIR unset; inline bundles are rejected and demo routes return 404.
Reachable only from the web and mobile BFFs over internal Docker DNS.
Sandbox runtime
wahs-sandbox-engine
Same container image on openclinai-edge only, with WAHS_FHIR_AUTH_BASE_URL set to an unroutable placeholder.
Mounts ten synthetic and de-identified FHIR R4 bundles read-only at /bundles and accepts JSON bundle uploads (Caddy caps request bodies at 25 MB).
Bundle listing and /v1/wahs/context/preview are public; /v1/chat/completions requires the project allowlist cookie (unless the user connects a local model from the browser).
Request Trace
End-to-end request trace
Trace for synthetic patient Margaret Chen (records from Pacific Northwest Geriatrics, Overlake Sleep & Behavioral Clinic, Community Pharmacy, and the WA State immunization registry) asking in the mobile companion: "What active medications am I taking, and are there any fall or sedation risks I should ask my doctor about?"
Step
Execution
Output / header
1. Client & BFF
The mobile app posts to its BFF (POST /api/chat). The BFF strips any browser-supplied fhir_bundle and forwards Authorization: Bearer <keycloak_jwt>, messages[], and wahs options to POST /v1/chat/completions on wahs-engine.
OpenAI chat request with wahs options.
2. Assembly
assembler.py resolves MasterPatient by JWT sub, reads linked datasets via paged Patient/{id}/$everything, skips re-fetching datasets whose meta.lastUpdated matches cache, applies chart_scope, and runs enforce_single_patient_scope.
x_wahs.scope_applied, dataset cache counters.
3. Condensation
wahs_core parses FHIR resources, drops entered-in-error and cancelled entries, SHA-256 deduplicates identical notes, and checks token count against the 16,384-token chart budget. Margaret's chart fits at Tier 0.
Under core-enriched, temporal adds date anchors and lab deltas and terminology_kb resolves RxNorm/ATC drug classes (including overlapping sedatives and statins). note_rag and overflow_lookup return empty because Tier 0 excerpted and omitted nothing.
x_wahs.enrichers disclosures and token counts.
5. Generation
upstream.py yields an initial context_ready SSE chunk carrying citation_map, posts to the southbound model with num_ctx=65536, emits : keepalive comments every 15s while waiting on prefill, and strips <think> blocks from streamed deltas.
The final SSE chunk attaches x_wahs and ai_provenance. The client renders inline [N], [P], and [K] tags as buttons that open the cited entry's resource type, date, and source organization.
x_wahs.citation_map and x_wahs.ai_provenance.
Client Integrations
Client integration paths
Four client paths call the engine over the same HTTP contract.
Caller
Route
Scope and provenance support
Web app: Ask WAHS
shl-ips/api/chat → wahs-engine
Full wahs option block (model, budget, enrichers, source/category scope, overlays), streamed x_wahs envelope, and interactive citation drawer.
Upstream health-record chat tab routed to wahs-engine with the caller's bearer token and markdown answer rendering. The engine assembles the chart from FHIR directly, so browser-side per-resource toggles and tool definitions are ignored and [N] tags render as plain text.
Mobile companion
Node BFF /api/chat → wahs-engine
Full x_wahs provenance, non-blocking ?mode=preview cache warm-up after sign-in, clinic source filtering, saved patient-story resources in [1]..[N], and flagged discrepancies passed in overlay_resources ([P1]..[PM]).
Research Sandbox
Caddy /api/engine/* → wahs-sandbox-engine
Public bundle catalog, wahs.bundle_id or inline JSON preview (condensed chart, enricher suffix, system prompt), and gated chat streaming or direct browser forwarding to a local OpenAI-compatible server.
Data Model
FHIR dataset layout
Each account has one MasterPatient resource keyed by Keycloak subject (identifier.system = http://keycloak.cirg.uw.edu). Imported clinical sources and patient-authored records are stored as separate linked datasets: each dataset has its own Patient resource referenced from MasterPatient.link[], tagged with category, method, and display name metadata.
Category tag
Resources stored
Write path
provider-health-record
Imported clinic, hospital, pharmacy, and immunization registry bundles.
Web import flows (such as SMART on FHIR) and the synthetic persona seeder.
patient-story
Journal notes (Observation, LOINC 51855-5), goals (Goal), care needs (Condition), and discrepancy flags (Flag) with ISO-8601 dates.
Web app and mobile companion; each save posts a replacement transaction bundle and updates MasterPatient.link[].
about-me / patient-medical-history
Demographics, occupation (LOINC 11341-5), self-reported conditions, medications, and advance directives.
Onboarding and Add Info forms in both apps.
Replacing or updating a dataset advances its Patient.meta.lastUpdated timestamp, which invalidates only that dataset's entry in wahs-engine on the next request.
State & Caching
Identity, session state, and caching
Layer
Owner
Scope and eviction
Identity & authorization
Keycloak, fhir-auth
Bearer JWT passed from client BFF to wahs-engine to fhir-auth. enforce_single_patient_scope strips any resource referencing a patient outside the authorized MasterPatient and its linked dataset IDs.
Conversation turns
Browser memory
Passed in messages[] on every request. When prior turns would push the prompt past WAHS_CONTEXT_WINDOW minus reserved output tokens, the oldest turns are dropped and counted in history_trimmed_turns.
Fixed num_ctx keeps one KV-cache allocation warm across budget presets so unchanged system prefixes avoid full prefill recomputation on follow-up turns.
Engine Internals
Packages, condensation tiers, and citation namespaces
FastAPI application (app.py), star-graph fetcher and scope guard (assembler.py), enricher runner (pipeline.py), southbound SSE client and provenance builder (upstream.py), profile/prompt loaders, JWT helpers, and bundled offline tokenizers (tokenizers_registry.py).
wahs_extensions
Optional enricher modules, imported lazily only when enabled by a profile or request.
wahs_devtools
wahs-seed-hapi CLI for loading synthetic demo personas into HAPI FHIR and Keycloak.
Condensation tiers
condense_bundle_to_budget measures candidate outputs with the target model's offline tokenizer and selects the lowest tier that fits budget_effective. Design trade-offs are discussed under LLM Strategy: Condensation.
Tier
Activation
Mechanics
Tier 0 · Verbatim
Full extracted chart fits budget.
Drops entered-in-error, cancelled, and unperformed entries, SHA-256 deduplicates identical decoded notes, and emits every clinical item and full note text verbatim.
Tier 1 · Uniform RLE folding
Tier 0 exceeds budget.
Preserves the HL7 IPS safety core, acute encounters, active care plans, imaging, and full clinical notes verbatim. Run-length folds repeated historical observations, panels, immunizations, historical medications, resolved conditions, procedures, and routine visits sharing a (section, code, unit/status) key into the latest entry plus count, date span, numeric min..max range, and merged memberUuids.
Tier 2 · IPS core & note horizon
Tier 1 exceeds budget.
Reserves the HL7 IPS safety core (patient header, active allergies, active conditions, active medications, active devices, and folded immunizations), binary-searches a monotonic section-interleaved recency prefix, and binary-searches a character horizon across included notes to fill remaining tokens.
Chart numbering and citation namespaces
Marker
Target
Prompt location & registration
[1], [2], [3]..[N]
[1] is the patient demographics line; [2] is the Completeness Manifest (tier, included counts, folded/excerpted/omitted counts); [3]..[N] are chart entries, continued sequentially by note_rag and overflow_lookup.
Chart in Region 1; recovered passages and items in Region 2. Mapped in x_wahs.citation_map with memberIds when folded.
[P1]..[PM]
Unsaved client draft notes and discrepancy flags passed in wahs.overlay_resources (capped at 5,120 bytes).
Appended after the chart inside Region 1 (sys_prompt) and added to citation_map.
[K1]..[KM]
Public clinical reference snippets matched to chart codes.
Appended to Region 2 when guideline_kb is active and added to citation_map.
The default prompt (prompts/wahs-default.txt) enforces numeric/tag-only bracket citations, requires checking [2] before reporting an item absent, requires copying values, units, and ISO dates verbatim without single-point trend extrapolation, and prohibits medication-change directives.
Enrichers implement ContextEnricher (wahs_core/ports.py). EnricherPipeline imports wahs_extensions lazily only when active IDs are non-empty, enforces per-module token caps within WAHS_MAX_ENRICHMENT_TOKENS (2,048), appends blocks strictly to Region 2, and records an EnrichmentDisclosure (including fired, tokens_used, and latency_ms) for every module.
wahs-engine separates three token parameters: target chart budget (wahs.target_budget_tokens), physical prompt ceiling (WAHS_CONTEXT_WINDOW), and Ollama KV-cache allocation (WAHS_OLLAMA_NUM_CTX).
Offline exact tokenizers:tokenizers_registry.py bundles the Gemma 4 SentencePiece tokenizer.json and pre-cached OpenAI tiktoken encodings inside the container image, counting tokens offline with zero network calls.
Budget resolution: An explicit wahs.target_budget_tokens is clamped to fit inside WAHS_CONTEXT_WINDOW alongside system framing, conversation turns, and output reserve. In Auto mode, the engine uses WAHS_PREFERRED_CHART_TOKENS, falling back to the profile's preferred_chart_tokens or remaining window capacity. If multi-turn history still pushes total prompt tokens past the ceiling, assembler.py tightens the chart target and re-condenses before sending.
Truncation detection:upstream.py compares offline exact_prompt_tokens against upstream-reported prompt_tokens and sets suspected_upstream_truncation: true if the upstream count drops below 85% on prompts of 1,024+ tokens.
Fixed Ollama num_ctx: For litellm and ollama provider flavors, resolve_ollama_num_ctx pins requests at or below WAHS_OLLAMA_NUM_CTX (65536 in cloud) to a single warm bucket so changing UI budgets between 2k and 64k never triggers an Ollama model reload.
Sharing
SMART Health Links sharing
Summary sharing runs between the client browser and wahs-shl-server without touching wahs-engine. The client builds a FHIR R4 bundle from the user's selected items, encrypts it in the browser using WebCrypto compact JWE (alg: dir, enc: A256GCM, 32-byte random key), uploads the ciphertext to POST /shl/{id}/file, and encodes the manifest URL and decryption key into a shlink:/ link and QR code with an expiration date and optional passcode. Because the decryption key stays in the URL fragment, wahs-shl-server stores only ciphertext.
Edge & Access Control
Hosted edge routing and access control
On the hosted demonstration VM, Caddy enforces a project-level Google allowlist (wahs-auth-gate) in front of the app subdomains while keeping patient-level data isolation in Keycloak and fhir-auth.
Hostname
Caddy routing and authentication
wahealth.openclinai.org
Verifies Google sign-in against WAHS_AUTH_WHITELIST_EMAILS and issues an HMAC-SHA256 signed, HttpOnly cookie scoped to .openclinai.org.
wahs-web.openclinai.org
forward_auth to wahs-auth-gate; routes /realms/* and /resources/* to Keycloak, /fhir* to fhir-auth, /shl-server/* to wahs-shl-server, and app/SSE routes (flush_interval -1 on /api/chat*) to wahs-shl-ips.
wahs-mobile.openclinai.org
forward_auth to wahs-auth-gate; routes /fhir* to fhir-auth, /shl-server/* to wahs-shl-server, and app/SSE routes to wahs-mobile-frontend.
wahs-demo.openclinai.org
Serves the static Research Sandbox UI and proxies /api/engine/* to wahs-sandbox-engine. Bundle and preview routes are open; /api/engine/v1/chat/completions requires forward_auth.
Configuration
Runtime configuration and local stack
wahs-engine ships minimal package defaults (baseline profile with zero enrichers imported and a 32768 window). Hosted cloud deployments set the overrides below in compose/wahs-cloud/docker-compose.yml.
Variable
Package default
Hosted value
Behavior
WAHS_FHIR_AUTH_BASE_URL
http://fhir-auth:8080/fhir
same
Per-user FHIR proxy URL; startup fails if pointed at fhir-internal.
LLM_BASE_URL
http://host.docker.internal:8079/v1
UW CIRG gateway
Southbound OpenAI-compatible base URL.
WAHS_MODEL_MAP_JSON
built-in alias map
wahs-26b/12b/e4b → ollama/gemma4:*
Maps public model IDs to upstream provider model names.
WAHS_DEFAULT_MODEL
wahs-26b
wahs-26b
Fallback model when omitted by caller.
WAHS_DEFAULT_PROFILE
baseline
core-enriched
Fallback profile from profiles.yaml.
WAHS_PREFERRED_CHART_TOKENS
unset
16384
Auto-mode target chart token budget.
WAHS_CONTEXT_WINDOW
32768
65536
Physical prompt ceiling enforced offline.
WAHS_OLLAMA_NUM_CTX
unset (min(65536, window))
65536
Warm Ollama KV-cache pin; 0 or omit defers to server default.
WAHS_MAX_ENRICHMENT_TOKENS
2048
2048
Shared ceiling across enabled enrichers.
WAHS_CACHE_TTL_SECONDS
1800
3600
TTL for in-memory dataset and prefix caches.
WAHS_ALLOW_LOCAL_BUNDLE_MODE
false
false (sandbox: true)
Permits wahs.fhir_bundle and wahs.bundle_id without a bearer JWT.
WAHS_DEMO_BUNDLES_DIR
unset
unset (sandbox: /bundles)
Read-only bundle directory for /v1/wahs/demo-bundles.
HEALTH_CHAT_BACKEND (shl-ips)
gateway
wahs-engine
Routes shl-ips/api/health-chat through wahs-engine.
Running locally. Developers with access to the WAHS repositories can run HAPI FHIR, Keycloak, fhir-auth, SMART Health Links, wahs-engine, and both client apps via Docker Compose: