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

Part 1 · System Logic Model

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.

WA Health Summary system logic model: permanent shared platform, stateless AI engine, and converging client surfaces Three-layer architectural boundary diagram. At the bottom, the permanent shared clinical and identity platform holds Keycloak 26 OIDC, fhir-auth (uwcirg/jwt-proxy), HAPI FHIR R4 with MasterPatient and linked clinic and patient-story datasets, and smart.health.links-server. In the middle, wahs-engine serves as permanent stateless AI middleware behind /api/health-chat and /api/chat, forwarding the caller's Keycloak bearer token through fhir-auth, running deterministic three-tier condensation and enrichers, and returning [N], [P], and [K] citations with HL7 AI-Provenance. At the top left, the canonical SvelteKit web app (uwcirg/shl-ips) is marked as the permanent frontend target. At the top right, inside a dashed amber boundary marked temporary and retireable, wahs-mobile-frontend implements the MHCID mobile interaction flow on top of the exact same Keycloak, FHIR, SHL, and wahs-engine services, with a convergence arrow showing validated mobile UX patterns merging into shl-ips. CANONICAL WEB APP (uwcirg/shl-ips) PERMANENT FRONTEND SvelteKit Health Summary & Record Workspace SMART clinic & pharmacy imports, IPS curation, QR sharing Patient-authored notes, care goals, care needs & flags Server routes: /api/health-chat & /api/chat → wahs-engine Long-term production UI (desktop & responsive mobile) UX patterns converge MOBILE UX LAYER (wahs-mobile-frontend) TEMPORARY / RETIREABLE MHCID Mobile Flow Prototype (React UI + Thin BFF) Zero separate database, user directory, or clinical rules Reads & writes the exact same MasterPatient FHIR datasets Enables parallel usability & clinical evaluation Retires as validated mobile UX converges into shl-ips Direct OIDC, FHIR R4 & SHL JWE reads/writes Same OIDC, FHIR R4 & SHL JWE endpoints /api/health-chat & /api/chat (JWT) /api/chat & preview (same JWT) SHARED STATELESS AI ENGINE (wahs-engine) PERMANENT AI MIDDLEWARE Per-User Auth Only Zero HAPI DB/admin creds Forwards caller Bearer JWT Single-patient scope guard Deterministic Context 3-tier FHIR condensation Warm Region 1 prefix cache Bounded suffix enrichers Grounded Generation OpenAI /v1 → Gemma 4 GPU [N] [P] [K] citation_map HL7 AI-Provenance envelope Paged $everything via fhir-auth (caller Bearer JWT) SHARED CLINICAL & IDENTITY PLATFORM (SINGLE SOURCE OF TRUTH) PERMANENT FOUNDATION Keycloak 26 OIDC (wahs) Single patient identity (sub) One login across web & mobile fhir-auth (uwcirg/jwt-proxy) Validates Keycloak Bearer JWT Per-user FHIR security policy HAPI FHIR R4 + PostgreSQL MasterPatient + clinic imports Shared patient-story & flags smart.health.links-server Encrypted JWE summary blobs shlink:/ manifests & QR sharing
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.
Architectural boundary Components Lifecycle status Ownership & convergence role
Core clinical & identity infrastructure Keycloak 26, fhir-auth (uwcirg/jwt-proxy), HAPI FHIR R4, PostgreSQL, smart.health.links-server Permanent foundation 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-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?"

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.

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