WA Health Summary

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.

Source: pmanko/wahs-engine ↗ · pmanko/shl-ips ↗ · pmanko/wahs-mobile-frontend ↗ · Deployment: pmanko/openclinai.org ↗

Architectural invariants

  1. 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.
  2. 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.
  3. 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.
  4. 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.
On this page
  1. Services & networks
  2. Request pipeline
  3. Request lifecycle
  4. Client integrations
  5. FHIR data model
  6. Identity, state & caching
  7. Engine internals
  8. HTTP & SSE contract
  9. Enricher runtime
  10. Budgets & context allocation
  11. Sharing
  12. Edge & access control
  13. Configuration & local stack

Part 1 · System

Services and networks

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-ipsSvelteKit web app (shl-ips)WAHS web app and server-side BFF for Ask WAHS and the health record chat.private, edge
wahs-mobile-frontendMobile companion + Node BFFPhone-sized client; BFF proxies chat and preview calls to the engine.private, edge
wahs-engineFastAPI (wahs-engine)Record assembly, condensation, enrichment, prompt framing, model routing, provenance.private
wahs-sandbox-engineSame image, sandbox configServes read-only example bundles and uploads for the Research Sandbox.edge only
wahs-fhir-auth / wahs-fhir-auth-proxynginx + uwcirg/jwt-proxyPer-user FHIR authorization: validates the bearer token and applies ownership policy on every request.private (nginx also edge)
wahs-fhirHAPI FHIR R4System of record for all patient datasets.private
wahs-keycloakKeycloak (wahs realm)OIDC identity for patients; issues the tokens forwarded to fhir-auth.private, edge
wahs-shl-serverSMART Health Links serverStores encrypted shared summaries and serves shlink:/ manifests.private, edge
wahs-dbPostgreSQLStorage for HAPI FHIR and Keycloak.private
wahs-auth-gatePython gate serviceProject-level Google allowlist and signed session cookie for the hosted demo.private, edge
LLM gatewayOpenAI-compatible endpointExternal 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.

wahs-engine five-stage request pipeline Stage 1 FHIR sources: HAPI FHIR datasets linked from a MasterPatient, patient-authored data, or sandbox bundles. Stage 2 authorization and scope: bearer token forwarded through fhir-auth, freshness check, chart scope and draft overlays applied. Stage 3 condensation: extraction and three-tier verbatim-first condensation into a stable chart prefix with a completeness manifest. Stage 4 prompt and enrichment: profile and prompt resolution plus optional enrichers appended to the turn suffix. Stage 5 model and provenance: single OpenAI-compatible streaming call, citation map, and HL7 AI-Provenance. 1. FHIR SOURCES HAPI FHIR R4 MasterPatient + datasets Clinic & pharmacy imports Notes, goals, care needs Sandbox mode: /bundles:ro or upload Paged $everything per linked dataset 2. AUTH & SCOPE fhir-auth proxy Caller's bearer token No HAPI admin access Single-patient guard Freshness check: meta.lastUpdated Applies chart_scope & draft overlays 3. CONDENSE wahs_core Tier 0: verbatim Tier 1: series folding Tier 2: safety core + notes Region 1: stable prefix [1]..[N] + [2] manifest Model-specific tokenizer Prefix cache key 4. PROMPT & ENRICH Profile + enrichers temporal · terminology_kb note_rag · overflow_lookup guideline_kb (opt-in) Region 2: turn suffix Append-only, capped Lazy-loaded modules Disclosed in x_wahs 5. MODEL & PROVENANCE OpenAI /v1 stream wahs-26b | 12b | e4b Fixed context allocation SSE keepalives x_wahs envelope [N] [P] [K] citation_map HL7 AI-Provenance human review required Client applications (presentation only) WAHS web app (shl-ips) · WAHS mobile companion · Research Sandbox (wahs-demo.openclinai.org)
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.
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. tier: 0, omitted_clinical_items: 0, X-WAHS-Prefix-Hash header.
4. Enrichment 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-recordClinic, hospital, pharmacy, and registry imports.Import flows in the web app (for example SMART on FHIR) and the demo seeder.
patient-storyJournal 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 historyDemographics, 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_coreStandard-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_engineFastAPI 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_extensionsOptional enrichers, imported only when a profile or request enables them.
wahs_devtoolsSeeder 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 · VerbatimExtracted chart fits the budget.Removes FHIR transport overhead, invalidated entries, and duplicate notes. Every remaining item is rendered verbatim.
Tier 1 · Series foldingVerbatim 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 packingFolded 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 /healthzInternalVersion, default model, profile, budget, context window, and whether demo bundles are enabled.
GET /v1/modelsPublicConfigured model aliases.
GET /v1/wahs/profilesPublicProfile catalog, available_enrichers, budget options, and active defaults.
POST /v1/wahs/context/previewBearer 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/completionsBearer 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 onlyEnabled 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
temporal450Chart anchor date, lookback cutoffs, vaccine elapsed time, and unit-safe longitudinal lab deltas.Always runs when enabled; skips single measurements and incompatible units.
terminology_kb550In-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_rag1,100Okapi BM25 over note spans not already shown in the chart, with terminology-based query expansion.Only when Tier 2 excerpted or omitted notes.
overflow_lookup550IDF-weighted BM25 and code matching over omitted clinical items.Only when the manifest reports omitted items.
guideline_kb500SQLite FTS5 over public reference snippets, intersected with the chart's codes.Opt-in (full-enriched or explicit request).
experimental.clinical_reconciliationn/aPrototype rule graph over sample packs.Rejected with 422 unless WAHS_ALLOW_EXPERIMENTAL_ENRICHERS=true.
Profile (profiles.yaml) Preferred chart tokens Enrichers
baseline (package default)Full windowNone. wahs_extensions is never imported.
temporal32,768temporal
terminology32,768terminology_kb
temporal-terminology32,768temporal, terminology_kb
rag-overflow16,384note_rag, overflow_lookup
core-enriched (hosted default)16,384temporal, terminology_kb, note_rag, overflow_lookup
full-enriched32,768All five, including guideline_kb

Budgets & Context Allocation

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.orgGate portal. Verifies a Google sign-in against an allowlist and sets an HMAC-signed, HttpOnly session cookie scoped to .openclinai.org.
wahs-web.openclinai.orgCaddy 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.orgSame 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.orgStatic 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_URLhttp://fhir-auth:8080/fhirsamePer-user FHIR proxy. Startup fails if it points at the internal FHIR server.
LLM_BASE_URLhttp://host.docker.internal:8079/v1UW CIRG gatewayAny OpenAI-compatible endpoint (LiteLLM, Ollama, vLLM, llama.cpp).
WAHS_MODEL_MAP_JSONbuilt-in aliaseswahs-26b/12b/e4b → ollama/gemma4:*Maps public model aliases to upstream model IDs.
WAHS_DEFAULT_MODELwahs-26bwahs-26bModel used when a request omits one.
WAHS_DEFAULT_PROFILEbaselinecore-enrichedProfile used when a request omits one.
WAHS_PREFERRED_CHART_TOKENSunset16384Auto-mode chart budget.
WAHS_CONTEXT_WINDOW3276865536Full prompt ceiling.
WAHS_OLLAMA_NUM_CTXunset (smaller of 65,536 and the window)65536Fixed upstream context allocation; 0 defers to the server.
WAHS_MAX_ENRICHMENT_TOKENS20482048Shared ceiling for all enricher output.
WAHS_CACHE_TTL_SECONDS18003600Dataset and prefix cache lifetime.
WAHS_ALLOW_LOCAL_BUNDLE_MODEfalsefalse (sandbox: true)Allows inline or registered bundles without a token. Never enabled on the patient-data engine.
WAHS_DEMO_BUNDLES_DIRunsetunset (sandbox: /bundles)Read-only bundle directory for the demo endpoints.
HEALTH_CHAT_BACKEND (shl-ips)gatewaywahs-engineRoutes 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.

Back to top