WA Health Summary

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.

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

Core system properties

  1. 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.
  2. 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.
  3. 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.
  4. 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.
On this page
  1. Services & networks
  2. Request pipeline
  3. Request trace
  4. Client integrations
  5. FHIR dataset layout
  6. Identity, state & caching
  7. Engine internals
  8. HTTP & SSE contract
  9. Enrichers & profiles
  10. Token accounting
  11. SMART Health Links
  12. Edge routing & gate
  13. Configuration & local stack

Part 1 · System

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.

WA Health Summary System Landscape and Network Boundaries System landscape across four zones: user browsers at the top (Web App, Mobile Companion, and Public Research Sandbox), the openclinai-edge network containing Caddy, wahs-auth-gate, Web and Mobile BFFs, and the isolated wahs-sandbox-engine (with no route to wahs-net), the private wahs-net network containing wahs-engine, fhir-auth, Keycloak, shl-server, HAPI FHIR R4, and PostgreSQL, and the outbound OpenAI-compatible GPU model host on the right. WAHS Web App Browser wahs-web.openclinai.org OIDC PKCE · WebCrypto A256GCM JWE WAHS Mobile Browser wahs-mobile.openclinai.org Phone UI · WebCrypto A256GCM JWE Research Sandbox Browser wahs-demo.openclinai.org Public preview · Optional Local BYO-Model EDGE NETWORK BOUNDARY (openclinai-edge) Caddy Edge Proxy (TLS, Host Routing, SSE flush_interval -1, 25 MB Sandbox Cap) Enforces forward_auth on app subdomains and /api/engine/v1/chat/completions; keeps /context/preview public wahs-auth-gate (:8096) Google allowlist + HMAC cookie wahs-shl-ips (:4000) SvelteKit Web UI + /api/chat & /api/health-chat BFF routes wahs-mobile-frontend (:4001) Mobile UI + Node /api/chat BFF Strips browser fhir_bundle; warms preview wahs-sandbox-engine (:8080) Read-only /bundles:ro + JSON uploads Isolated: zero route to wahs-net PRIVATE PATIENT-DATA NETWORK (wahs-net) wahs-engine (:8080) Stateless AI Middleware Forwards caller Bearer JWT wahs_core 3-tier condenser 5 modular suffix enrichers Zero DB / HAPI admin creds fhir-auth & Keycloak OIDC JWT validation + per-user FHIR security policy wahs-shl-server Stores encrypted JWE blobs Outside AI path (no keys) wahs-fhir (HAPI R4) MasterPatient + linked clinic & patient-story datasets wahs-db (Postgres 14) Backing database for HAPI FHIR & Keycloak OUTBOUND MODEL HOST (HTTPS /v1) UW CIRG GPU Gateway LiteLLM → Ollama (OpenAI /v1) wahs-26b · wahs-12b · wahs-e4b Warm num_ctx=65536 KV slot Stateless (zero stored chat history) Outbound HTTPS POST /v1/chat/completions
System topology: Patient-facing web and mobile apps access HAPI FHIR strictly through fhir-auth inside wahs-net, while wahs-sandbox-engine runs the same container image on openclinai-edge with zero connectivity to patient data stores.
Service Component Role Networks
wahs-shl-ipsSvelteKit 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-frontendReact UI + Node BFFMobile companion; BFF proxies /api/chat and preview requests to wahs-engine.wahs-net, edge
wahs-engineFastAPI (wahs-engine)Record assembly, condensation, enrichment, prompt framing, model routing, and provenance.wahs-net only
wahs-sandbox-engineSame image, sandbox envServes mounted example bundles and user uploads for the Research Sandbox.edge only
wahs-fhir-auth / wahs-fhir-auth-proxynginx + uwcirg/jwt-proxyValidates Keycloak bearer tokens, stamps security labels on writes, and enforces per-user read access.wahs-net (nginx also edge)
wahs-fhirHAPI FHIR R4 (v8.0.0)FHIR R4 repository for patient datasets.wahs-net only
wahs-keycloakKeycloak 26 (wahs realm)OIDC identity provider issuing patient access tokens.wahs-net, edge
wahs-shl-serversmart.health.links-serverStores JWE-encrypted health summaries and serves shlink:/ manifests.wahs-net, edge
wahs-dbPostgreSQL 14Relational storage for HAPI FHIR and Keycloak.wahs-net only
wahs-auth-gatePython gate serviceGoogle OAuth allowlist check and HMAC-SHA256 session cookie for hosted demo subdomains.wahs-net, edge
Southbound LLM hostOpenAI /v1 endpointOllama 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.

wahs-engine five-stage request pipeline Stage 1 FHIR sources: HAPI FHIR datasets linked from MasterPatient, patient-authored data, or sandbox bundles. Stage 2 authorization and scope: bearer token forwarded through fhir-auth, meta.lastUpdated check, chart_scope and draft overlays applied. Stage 3 condensation: extraction and three-tier condensation into a stable system prefix with Completeness Manifest at [2]. 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 & [P] draft overlays 3. CONDENSE wahs_core Tier 0: verbatim Tier 1: RLE folding Tier 2: IPS core + notes Region 1: system prefix [1]..[N], [2] manifest, [P] Offline exact tokenizer X-WAHS-Prefix-Hash 4. PROMPT & ENRICH Profile + enrichers temporal · terminology_kb note_rag · overflow_lookup guideline_kb (opt-in) Region 2: turn suffix Append-only (≤ 2,048 tok) Lazy-loaded modules Disclosed in x_wahs 5. MODEL & PROVENANCE OpenAI /v1 stream wahs-26b | 12b | e4b Fixed num_ctx=65536 15s SSE keepalives x_wahs envelope [N] [P] [K] citation_map HL7 AI-Provenance human_review_required Client applications (UI and session state) WAHS web app (shl-ips) · WAHS mobile companion · Research Sandbox (wahs-demo.openclinai.org)
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).
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?"

Ask WAHS Request and Streaming Sequence Sequence across five participants (Browser UI, App BFF, wahs-engine, fhir-auth and HAPI FHIR, and GPU Model Host): 1. Browser posts JWT, messages, and wahs options to BFF; 2. BFF strips any fhir_bundle and posts to wahs-engine; 3. wahs-engine checks Patient.meta.lastUpdated via fhir-auth and fetches changed datasets; 4. wahs-engine condenses the chart, runs enrichers, and immediately streams context_ready with citation_map; 5. wahs-engine calls the GPU host with num_ctx=65536; 6. GPU streams deltas while wahs-engine strips think blocks and sends 15s keepalives; 7. Final SSE chunk delivers x_wahs provenance and HL7 AI-Provenance. Browser / App UI App BFF (/api/chat) wahs-engine fhir-auth + HAPI R4 GPU Host (/v1) 1. JWT + messages[] + wahs 2. Strip bundle; POST /v1/chat/completions 3. Check lastUpdated; fetch changed Condense chart + run enrichers 4. SSE Frame 1: context_ready + citation_map (pre-LLM) 5. Region 1 prefix + Region 2 suffix (num_ctx=65536) 6. Delta tokens (<think> stripped) + 15s : keepalive 7. Final SSE chunk: x_wahs + AI-Provenance + [DONE]
Streaming sequence: Emitting context_ready before the GPU prefill completes gives the client the citation map upfront, while 15-second SSE comment keepalives prevent proxy idle timeouts when shared GPUs queue requests.
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. tier: 0, omitted_clinical_items: 0, X-WAHS-Prefix-Hash.
4. Enrichment 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. OpenAI SSE delta chunks (or structured 502 error frame).
6. Provenance 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.
Web app: Ask About My Data shl-ips /api/health-chat (HEALTH_CHAT_BACKEND=wahs-engine) 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.

Per-Patient FHIR R4 Star-Graph and Dataset Cache Freshness Keycloak JWT subject maps to one MasterPatient resource in HAPI FHIR via fhir-auth. MasterPatient.link[] points to independent dataset Patient resources (clinic records, sleep clinic records, patient-story journal/goals/flags, and about-me demographics). Unchanged datasets hit wahs-engine RAM cache via meta.lastUpdated, while newly edited datasets such as patient-story advance meta.lastUpdated and trigger a selective $everything re-fetch. MasterPatient (HAPI R4) identifier: keycloak | <sub> Authorized via fhir-auth JWT link[]: seealso → Dataset Patients Anchor for single-patient scope Patient/ds-1 · Pacific NW Geriatrics tag: provider-health-record · meta.lastUpdated unchanged Cache HIT Patient/ds-2 · Overlake Sleep & Pharmacy tag: provider-health-record · meta.lastUpdated unchanged Cache HIT Patient/ds-story · My Story (Notes & Goals) tag: patient-story · meta.lastUpdated advanced on save Re-fetched Patient/ds-about · About Me & Self-Reported tag: about-me / patient-medical-history · unchanged Cache HIT wahs-engine Assembler Per-Dataset RAM Cache (sub, dataset_id, lastUpdated) Applies wahs.chart_scope Strips any foreign Patient/ ref Pooled ExtractedChart → Condenser
Star-graph pooling and selective refresh: Saving a note in either app replaces only the patient-story dataset and advances its meta.lastUpdated, so the next turn re-fetches just that dataset while reusing cached clinic imports.
Category tag Resources stored Write path
provider-health-recordImported clinic, hospital, pharmacy, and immunization registry bundles.Web import flows (such as SMART on FHIR) and the synthetic persona seeder.
patient-storyJournal 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-historyDemographics, 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.
Dataset & prefix caches wahs-engine RAM Dataset cache keyed by (verified_sub, dataset_id, lastUpdated) (default cap: 256 entries / 256 MB). Prefix cache keyed by (verified_sub, datasets_fingerprint, scope_hash, tokenizer_family, prompt_sha256, budget) (default cap: 128 entries / 128 MB), plus TTL eviction.
Model KV cache Southbound GPU host 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

Package Modules and responsibilities
wahs_coreZero-dependency Python standard-library package: FHIR R4 parser (extractors.py), three-tier monotonic condenser (condenser.py), [1]..[N] serializer and mapping builder (chart_serializer.py), and ContextEnricher protocol (ports.py).
wahs_engineFastAPI 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_extensionsOptional enricher modules, imported lazily only when enabled by a profile or request.
wahs_devtoolswahs-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 · VerbatimFull 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 foldingTier 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 horizonTier 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.

Part 2 · Builder Reference

HTTP endpoints, request schema, and SSE stream

Endpoint Auth Behavior
GET /healthzInternalReturns engine version, default model, default profile, preferred budget, context window, and demo_bundles_enabled.
GET /v1/modelsPublicLists configured model aliases (wahs-26b, wahs-12b, wahs-e4b).
GET /v1/wahs/profilesPublicReturns declarative profiles from profiles.yaml, available_enrichers, budget presets, and active defaults.
POST /v1/wahs/context/previewBearer JWT (or sandbox bundle)Executes Stages 1 through 4 without calling the LLM; returns chart_text, system_prompt, enrichment_text, X-WAHS-Prefix-Hash, and x_wahs.
POST /v1/chat/completionsBearer JWT (or gated sandbox)OpenAI chat completion (stream: true or false) accepting the wahs extension object.
GET /v1/wahs/demo-bundles
GET /v1/wahs/demo-bundles/{id}/resources
Sandbox onlyActive only when both WAHS_ALLOW_LOCAL_BUNDLE_MODE=true and WAHS_DEMO_BUNDLES_DIR are set; returns 404 in production.
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": [] } } --> Initial SSE chunk (emitted before southbound prefill completes): data: {"id":"chatcmpl-wahs-...","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}],"x_wahs_stream":{"event":"context_ready","prefix_cache_key_hash":"...","citation_map":{...}}} --> Comment keepalive every 15s while southbound host queues or prefills: : keepalive --> Streamed content deltas (<think> stripped), or structured 502 error chunk on upstream failure: data: {"id":"chatcmpl-wahs-...","error":{"message":"Southbound LLM stream returned HTTP 503.","status":502}} --> Final SSE chunk before [DONE] (illustrative field values): { "x_wahs": { "citation_map": { "12": { "index": 12, "resourceType": "MedicationRequest", "id": "...", "source": "Overlake Sleep & Behavioral Clinic", "section": "med_active", "date": "2025-11-10", "display": "(2025-11-10) Medication: 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", "fired": true, ... }, { "id": "terminology_kb", "fired": true, ... } ], "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

Enricher modules and profiles

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.

Enricher ID Cap Mechanism Gating
temporal450Computes chart anchor date, 6m/12m lookback cutoffs, vaccine elapsed intervals, and UCUM-compatible numeric lab deltas.Runs when enabled; skips single-point series (n=1) and mismatched units.
terminology_kb550In-memory SQLite lookup (CIEL v2026-04-28, RxNorm/ATC, CDC CVX/ACIP, LOINC) resolving active ingredients, ATC class overlaps, adult vaccine series, and missing lab reference intervals.Runs when enabled; never overrides inline Observation.referenceRange.
note_rag1,100Single-patient Okapi BM25 passage retrieval over unseen note spans using terminology_kb synonym query expansion; cites passages sequentially as [N].Self-gated to Tier 2 when notes were excerpted or omitted.
overflow_lookup550IDF-weighted Okapi BM25 and code lookup over omitted structured ClinicalItem records; registers sequential [N] citations.Self-gated to Tier 2 when omitted_clinical_items > 0.
guideline_kb500In-memory SQLite FTS5 intersected with chart codes over public clinical reference snippets; cites as [K1]..[KM].Opt-in (full-enriched or explicit wahs.enrichers).
experimental.clinical_reconciliation550Prototype chronic-care rule graph over sample packs.Quarantined; returns HTTP 422 unless WAHS_ALLOW_EXPERIMENTAL_ENRICHERS=true.
Profile ID (profiles.yaml) preferred_chart_tokens Active enrichers
baseline (package default)null (full window)None (wahs_extensions not imported)
temporal32768temporal
terminology32768terminology_kb
temporal-terminology32768temporal, terminology_kb
rag-overflow16384note_rag, overflow_lookup
core-enriched (hosted default)16384temporal, terminology_kb, note_rag, overflow_lookup
full-enriched32768temporal, terminology_kb, note_rag, overflow_lookup, guideline_kb

Token Accounting

Token accounting and upstream context allocation

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.orgVerifies Google sign-in against WAHS_AUTH_WHITELIST_EMAILS and issues an HMAC-SHA256 signed, HttpOnly cookie scoped to .openclinai.org.
wahs-web.openclinai.orgforward_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.orgforward_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.orgServes 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_URLhttp://fhir-auth:8080/fhirsamePer-user FHIR proxy URL; startup fails if pointed at fhir-internal.
LLM_BASE_URLhttp://host.docker.internal:8079/v1UW CIRG gatewaySouthbound OpenAI-compatible base URL.
WAHS_MODEL_MAP_JSONbuilt-in alias mapwahs-26b/12b/e4b → ollama/gemma4:*Maps public model IDs to upstream provider model names.
WAHS_DEFAULT_MODELwahs-26bwahs-26bFallback model when omitted by caller.
WAHS_DEFAULT_PROFILEbaselinecore-enrichedFallback profile from profiles.yaml.
WAHS_PREFERRED_CHART_TOKENSunset16384Auto-mode target chart token budget.
WAHS_CONTEXT_WINDOW3276865536Physical prompt ceiling enforced offline.
WAHS_OLLAMA_NUM_CTXunset (min(65536, window))65536Warm Ollama KV-cache pin; 0 or omit defers to server default.
WAHS_MAX_ENRICHMENT_TOKENS20482048Shared ceiling across enabled enrichers.
WAHS_CACHE_TTL_SECONDS18003600TTL for in-memory dataset and prefix caches.
WAHS_ALLOW_LOCAL_BUNDLE_MODEfalsefalse (sandbox: true)Permits wahs.fhir_bundle and wahs.bundle_id without a bearer JWT.
WAHS_DEMO_BUNDLES_DIRunsetunset (sandbox: /bundles)Read-only bundle directory for /v1/wahs/demo-bundles.
HEALTH_CHAT_BACKEND (shl-ips)gatewaywahs-engineRoutes 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:

Back to top