WA Health Summary · Architecture & Builder Reference
System architecture: from patient-controlled FHIR records to cited answers
WA Health Summary stores each patient's records in HAPI FHIR R4, gates every read through a per-user authorization proxy, and answers questions through wahs-engine, a stateless OpenAI-compatible service that assembles, condenses, and cites the record before calling an open-weight model. This page describes the services, data model, request pipeline, security boundaries, and interfaces. The reasoning behind the condensation, context, and model choices is on the LLM Strategy page.
No database credentials in the AI layer.wahs-engine never reads HAPI FHIR directly. It forwards the caller's Keycloak bearer token through fhir-auth (uwcirg/jwt-proxy) on every turn, refuses to start if pointed at the internal FHIR server, and strips any resource that references a different patient.
Stateless service, explicit scope. Conversation history lives in the client and is sent as an OpenAI messages[] array each turn. The engine keeps only bounded, per-user in-memory caches keyed by identity, dataset fingerprints, and scope.
Deterministic preparation, single model call. Record assembly, condensation, and optional enrichment are deterministic code paths. The model is called once per turn with a stable chart prefix and a question-specific suffix.
Every claim is addressable. Answers cite numbered tags that resolve through x_wahs.citation_map to a FHIR resource, a patient-authored draft, or a public reference snippet. The final frame carries an HL7 AI-Provenance record with human_review_required: true.
The hosted stack runs as one Docker Compose project behind a shared Caddy edge proxy. Two networks separate concerns: wahs-net is private and carries all patient data traffic, while openclinai-edge connects services that Caddy exposes publicly. The Research Sandbox engine sits only on the edge network and has no route to patient data.
Service
Component
Role
Networks
wahs-shl-ips
SvelteKit web app (shl-ips)
WAHS web app and server-side BFF for Ask WAHS and the health record chat.
private, edge
wahs-mobile-frontend
Mobile companion + Node BFF
Phone-sized client; BFF proxies chat and preview calls to the engine.
private, edge
wahs-engine
FastAPI (wahs-engine)
Record assembly, condensation, enrichment, prompt framing, model routing, provenance.
private
wahs-sandbox-engine
Same image, sandbox config
Serves read-only example bundles and uploads for the Research Sandbox.
edge only
wahs-fhir-auth / wahs-fhir-auth-proxy
nginx + uwcirg/jwt-proxy
Per-user FHIR authorization: validates the bearer token and applies ownership policy on every request.
private (nginx also edge)
wahs-fhir
HAPI FHIR R4
System of record for all patient datasets.
private
wahs-keycloak
Keycloak (wahs realm)
OIDC identity for patients; issues the tokens forwarded to fhir-auth.
private, edge
wahs-shl-server
SMART Health Links server
Stores encrypted shared summaries and serves shlink:/ manifests.
private, edge
wahs-db
PostgreSQL
Storage for HAPI FHIR and Keycloak.
private
wahs-auth-gate
Python gate service
Project-level Google allowlist and signed session cookie for the hosted demo.
private, edge
LLM gateway
OpenAI-compatible endpoint
External southbound model host (Ollama behind LiteLLM on UW CIRG GPUs, or any compatible server).
outbound
Request Pipeline
Five stages inside wahs-engine
Every chat turn and every context preview runs the same five stages. Clients only render the result; they hold no condensation, prompt, or citation logic.
Two-region prompt: Stage 3 produces a chart prefix that does not depend on the question, so the model host can reuse its cached attention state across follow-up turns. Stage 4 appends question-specific context to the turn suffix, which never invalidates that prefix.
Patient-data runtime
wahs-engine
Private network only; reads FHIR through http://fhir-auth:8080/fhir with the caller's token.
WAHS_ALLOW_LOCAL_BUNDLE_MODE=false and no demo bundle directory, so inline bundles are rejected and demo endpoints return 404.
Called only by the web and mobile BFFs over internal Docker DNS.
Sandbox runtime
wahs-sandbox-engine
Same container image, attached only to the edge network, with its FHIR URL pointed at an unroutable host.
Mounts ten synthetic and de-identified bundles read-only at /bundles and accepts uploaded bundles (request bodies capped at 25 MB at the edge).
Bundle browsing and context preview are public; chat completion requires the project session cookie, or the browser can forward the prepared prompt to a local model.
Request Lifecycle
One question, end to end
Example: Margaret, a synthetic patient with records from a geriatrics clinic, a sleep clinic, a pharmacy, and the state immunization registry, asks 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
What happens
Observable artifact
1. Client & BFF
The mobile BFF forwards Authorization: Bearer <keycloak_jwt>, the turn history, and wahs options (model, budget, enrichers, source scope, unsaved draft overlays) to POST /v1/chat/completions. It strips any browser-supplied FHIR bundle.
OpenAI request with a wahs block.
2. Assembly
The engine resolves the MasterPatient by the token's subject, reads each linked dataset with paged $everything, reuses cached datasets whose meta.lastUpdated has not changed, applies chart_scope, and drops foreign-patient references.
x_wahs.scope_applied, dataset cache hits and fetches.
3. Condensation
wahs_core extracts clinical items and notes, drops invalidated entries, deduplicates identical notes, and selects the lowest tier that fits the chart budget. Margaret's record fits verbatim.
With core-enriched, temporal adds date anchors and lab trends and terminology_kb adds drug-class groupings. note_rag and overflow_lookup stay inactive because nothing was excerpted or omitted.
x_wahs.enrichers with per-module token counts and disclosures.
5. Generation
The engine emits a context_ready SSE frame with the citation map, calls the model once, sends keepalive comments while the host queues or prefills, and strips any reasoning blocks from the streamed text.
Streamed deltas; structured error frame on upstream failure.
6. Rendering
The client renders the answer and turns each [N] or [P] tag into a link. Selecting one opens the cited resource, its date, and its source.
Final frame with x_wahs and ai_provenance.
Client Integrations
Four callers, one engine contract
All clients use the same OpenAI-compatible endpoints. They differ in how much of the wahs option block and the x_wahs response they use.
Caller
Path to the engine
What it uses
Web app: Ask WAHS
shl-ips server route → wahs-engine
Full option block (model, budget, enrichers, source and category scope, overlays), streamed x_wahs provenance, and the citation inspector.
Web app: health record chat
/api/health-chat with HEALTH_CHAT_BACKEND=wahs-engine
The upstream "Ask About My Data" tab. Sends the user's question with their own bearer token and the default model. The engine builds the chart from FHIR, so browser-side record toggles and tool definitions are not applied, and citations render as plain text.
Mobile companion
Node BFF (/api/chat) → wahs-engine
Chat with full provenance, a context preview call right after sign-in to warm the caches, source scoping, and patient-authored overlays cited as [P].
Research Sandbox
Static page → Caddy → wahs-sandbox-engine
Demo bundle listing, wahs.bundle_id lookups, context preview (chart, enricher appendix, system prompt), and gated chat or local-model forwarding.
FHIR Data Model
A star graph of datasets per patient
Each person has one MasterPatient resource identified by their Keycloak subject (identifier.system = http://keycloak.cirg.uw.edu). Every imported source becomes its own dataset: a Patient resource plus its clinical resources, linked from MasterPatient.link[]. Dataset tags record provenance, so the engine can label and scope each source.
Dataset category
Contents
Written by
provider-health-record
Clinic, hospital, pharmacy, and registry imports.
Import flows in the web app (for example SMART on FHIR) and the demo seeder.
patient-story
Journal entries (Observation, LOINC 51855-5), goals (Goal), care needs (Condition), and flags (Flag).
Web app and mobile companion. Each save writes a new dataset in one transaction and replaces the previous story link.
about-me and patient-reported history
Demographics, occupation, self-reported conditions and medications.
Setup and Add Info flows in both apps.
Because every write updates meta.lastUpdated on the affected dataset, the engine's freshness check picks up new or edited data on the next turn without any notification channel between the apps and the engine.
Identity, State & Caching
Four independent state layers
Identity, conversation history, extracted chart data, and model-host attention state are owned by different components. None of them requires a conversation database on the server.
State layer
Owner
Contract
Identity & ownership
Keycloak, fhir-auth
The bearer token travels from the client BFF to the engine to fhir-auth. The engine derives the verified subject from it and enforces a single-patient scope before extraction.
Conversation history
Client session
Sent as messages[] on each turn. If history no longer fits the context window, the oldest turns are trimmed and the count is reported as history_trimmed_turns.
Dataset & prefix caches
wahs-engine memory
Keyed by verified subject, dataset fingerprints, scope, tokenizer family, prompt hash, and budget. Bounded by entry and byte caps (package defaults: 256 datasets / 256 MB and 128 prefixes / 128 MB) with TTL eviction.
Model-host attention cache
Ollama on UW CIRG GPUs
One fixed context allocation per model, so a repeated chart prefix can be reused across turns and budget changes without reloading the model.
Engine Internals
Packages, condensation tiers, and citation namespaces
Package
Responsibility
wahs_core
Standard-library-only FHIR R4 extraction (extractors.py), three-tier condenser (condenser.py), [1]..[N] chart rendering with citation mapping (chart_serializer.py), and the ContextEnricher protocol (ports.py).
wahs_engine
FastAPI runtime: record assembly and scope enforcement (assembler.py), enricher orchestration (pipeline.py), upstream streaming and provenance (upstream.py), profile and prompt registries, configuration, schemas, and model tokenizers.
wahs_extensions
Optional enrichers, imported only when a profile or request enables them.
wahs_devtools
Seeder that loads synthetic demo personas into HAPI FHIR and Keycloak.
Condensation tiers
The condenser selects the lowest tier whose output fits the chart budget, measured with the target model's tokenizer. Why the tiers are designed this way is covered under Condensation on the LLM Strategy page.
Tier
Selected when
Transformation
Tier 0 · Verbatim
Extracted chart fits the budget.
Removes FHIR transport overhead, invalidated entries, and duplicate notes. Every remaining item is rendered verbatim.
Tier 1 · Series folding
Verbatim chart exceeds the budget.
Folds repeated lab and vital series by code and unit into earliest, extremes, and latest values.
Tier 2 · Safety core & note packing
Folded chart still exceeds the budget.
Reserves allergies, active medications, active problems, and implanted devices; packs remaining items by recency; distributes the rest of the budget across clinical notes. Omitted counts go to the [2] Completeness Manifest.
Citation namespaces
Tag
Refers to
Registered by
[1]..[N]
Chart entries, including note passages and omitted records recovered for the current question.
Chart serializer, then note_rag and overflow_lookup continue the same numeric sequence.
[P1]..[PM]
Unsaved patient-authored drafts and flags sent as wahs.overlay_resources.
Assembler, from the client's overlay payload.
[K1]..[KM]
Public clinical reference snippets.
guideline_kb, when enabled.
The default system prompt (prompts/wahs-default.txt) instructs the model to cite only with these tags, to check the Completeness Manifest before stating that something is absent, to copy values and dates exactly, and to avoid medication-change instructions. Prompts load from WAHS_PROMPTS_DIR and their hash is recorded in every response.
Part 2 · Builder Reference
HTTP endpoints, request schema, and SSE contract
Endpoint
Auth
Purpose
GET /healthz
Internal
Version, default model, profile, budget, context window, and whether demo bundles are enabled.
GET /v1/models
Public
Configured model aliases.
GET /v1/wahs/profiles
Public
Profile catalog, available_enrichers, budget options, and active defaults.
POST /v1/wahs/context/preview
Bearer token (or sandbox bundle)
Runs assembly, condensation, and enrichment without calling the model. Returns chart_text, system_prompt, enrichment text, and x_wahs.
POST /v1/chat/completions
Bearer token (or gated sandbox)
Standard OpenAI chat completion, streamed or not, with the optional wahs block.
GET /v1/wahs/demo-bundles GET /v1/wahs/demo-bundles/{id}/resources
Sandbox only
Enabled only when WAHS_ALLOW_LOCAL_BUNDLE_MODE=true and WAHS_DEMO_BUNDLES_DIR is set; otherwise 404.
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": {
"profile": "core-enriched",
"target_budget_tokens": 16384,
"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": []
}
}
--> First SSE frame, sent before the model starts generating:
data: {"object":"chat.completion.chunk","x_wahs_stream":{"event":"context_ready","prefix_cache_key_hash":"...","citation_map":{...}}}
--> Comment frames while the model host queues or prefills:
: keepalive
--> Content deltas (reasoning blocks removed), or a structured error frame:
data: {"error":{"type":"upstream_error","message":"..."}}
--> Final frame (values illustrative):
{
"x_wahs": {
"citation_map": {
"12": { "resourceType": "MedicationRequest", "id": "...", "date": "...", "source": "...", "display": "Zolpidem tartrate 10 MG Oral Tablet" }
},
"condensation": {
"tier": 0, "tier_name": "verbatim", "profile_id": "core-enriched", "prompt_id": "wahs-default",
"budget_effective": 16384, "context_window": 65536, "upstream_num_ctx": 65536,
"omitted_clinical_items": 0, "cache_hit": true, "history_trimmed_turns": 0
},
"completeness_manifest": { ... },
"enrichers": [ { "id": "temporal", ... }, { "id": "terminology_kb", ... } ],
"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
}
}
}
Enricher Runtime
Profiles and the ContextEnricher contract
Enrichers implement the ContextEnricher protocol in wahs_core/ports.py. The pipeline imports a module only when the active profile or request enables it, gives each module its own token cap inside a shared ceiling (WAHS_MAX_ENRICHMENT_TOKENS, default 2048), and writes output only to the turn suffix. Each module returns an EnrichmentDisclosure that is surfaced in x_wahs.enrichers and the provenance record.
Module
Token cap
Mechanism
Activation
temporal
450
Chart anchor date, lookback cutoffs, vaccine elapsed time, and unit-safe longitudinal lab deltas.
Always runs when enabled; skips single measurements and incompatible units.
terminology_kb
550
In-memory SQLite over CIEL, RxNorm/ATC, CDC CVX/ACIP, and LOINC: drug ingredients and classes, vaccine schedules, missing reference ranges.
Always runs when enabled; never overrides a reference range already in the record.
note_rag
1,100
Okapi BM25 over note spans not already shown in the chart, with terminology-based query expansion.
Only when Tier 2 excerpted or omitted notes.
overflow_lookup
550
IDF-weighted BM25 and code matching over omitted clinical items.
Only when the manifest reports omitted items.
guideline_kb
500
SQLite FTS5 over public reference snippets, intersected with the chart's codes.
Opt-in (full-enriched or explicit request).
experimental.clinical_reconciliation
n/a
Prototype rule graph over sample packs.
Rejected with 422 unless WAHS_ALLOW_EXPERIMENTAL_ENRICHERS=true.
Chart budget, context window, and model-host allocation
Three separate numbers govern prompt size. The chart budget is how many tokens the condensed record may occupy. The context window (WAHS_CONTEXT_WINDOW) is the ceiling for the full prompt plus reserved output. The upstream allocation (WAHS_OLLAMA_NUM_CTX) is the context size requested from Ollama.
Budget resolution: an explicit wahs.target_budget_tokens is honored and clamped to the context window. Otherwise the engine uses WAHS_PREFERRED_CHART_TOKENS, then the profile's preferred tokens, then the window minus system framing, history, enrichment cap, and output reserve. The chosen value and reason are reported as budget_effective and resolution_reason.
Exact accounting: token counts use the target model's tokenizer offline, so prompts are sized before the upstream call instead of being truncated by the model host. A suspected upstream truncation is flagged in x_wahs.
Upstream allocation: when WAHS_OLLAMA_NUM_CTX is set, every request uses that one allocation (stepping up only if a prompt exceeds it), so budget changes do not cause model reloads. Setting it to 0 defers to the server's own default. The rationale is under Context sizing.
Streaming resilience: the context_ready frame and keepalive comments keep proxies and browsers from timing out while a shared GPU queues the request.
Sharing
SMART Health Links, outside the AI path
Sharing a summary does not involve the engine. The client assembles the selected resources into a FHIR bundle, encrypts it in the browser as a compact JWE (alg: dir, enc: A256GCM), uploads the ciphertext to shl-server, and renders a shlink:/ QR code and link with an expiry and optional passcode. The decryption key travels only in the link, so the server stores ciphertext it cannot read. Links can be listed and revoked from either app.
Edge & Access Control
Two layers of access control on the hosted demo
The hosted demo adds a project-level gate in front of the patient-level controls described above. Neither layer replaces the other.
Host
Routing and access
wahealth.openclinai.org
Gate portal. Verifies a Google sign-in against an allowlist and sets an HMAC-signed, HttpOnly session cookie scoped to .openclinai.org.
wahs-web.openclinai.org
Caddy forward_auth to the gate, then routes /realms/* to Keycloak, /fhir* to fhir-auth, the SHL API to shl-server, and everything else to shl-ips. Patient sign-in still happens in Keycloak.
wahs-mobile.openclinai.org
Same gate, with /fhir* to fhir-auth, the SHL API to shl-server, and the app and /api/chat to the mobile BFF.
wahs-demo.openclinai.org
Static sandbox page plus /api/engine/* to wahs-sandbox-engine. Bundle and preview routes are public; chat completion routes require the gate cookie.
Configuration
Runtime configuration
The wahs-engine package ships conservative defaults. The hosted deployment overrides several of them in compose/wahs-cloud/docker-compose.yml.
Variable
Package default
Hosted value
Effect
WAHS_FHIR_AUTH_BASE_URL
http://fhir-auth:8080/fhir
same
Per-user FHIR proxy. Startup fails if it points at the internal FHIR server.
LLM_BASE_URL
http://host.docker.internal:8079/v1
UW CIRG gateway
Any OpenAI-compatible endpoint (LiteLLM, Ollama, vLLM, llama.cpp).
WAHS_MODEL_MAP_JSON
built-in aliases
wahs-26b/12b/e4b → ollama/gemma4:*
Maps public model aliases to upstream model IDs.
WAHS_DEFAULT_MODEL
wahs-26b
wahs-26b
Model used when a request omits one.
WAHS_DEFAULT_PROFILE
baseline
core-enriched
Profile used when a request omits one.
WAHS_PREFERRED_CHART_TOKENS
unset
16384
Auto-mode chart budget.
WAHS_CONTEXT_WINDOW
32768
65536
Full prompt ceiling.
WAHS_OLLAMA_NUM_CTX
unset (smaller of 65,536 and the window)
65536
Fixed upstream context allocation; 0 defers to the server.
WAHS_MAX_ENRICHMENT_TOKENS
2048
2048
Shared ceiling for all enricher output.
WAHS_CACHE_TTL_SECONDS
1800
3600
Dataset and prefix cache lifetime.
WAHS_ALLOW_LOCAL_BUNDLE_MODE
false
false (sandbox: true)
Allows inline or registered bundles without a token. Never enabled on the patient-data engine.
WAHS_DEMO_BUNDLES_DIR
unset
unset (sandbox: /bundles)
Read-only bundle directory for the demo endpoints.
HEALTH_CHAT_BACKEND (shl-ips)
gateway
wahs-engine
Routes the web app's upstream health record chat through the engine.
Running WAHS locally. Developers with access to the WAHS repositories can run HAPI FHIR, Keycloak, fhir-auth, SMART Health Links, the engine, and both apps with Docker Compose.