
Update deployment version
An AI-assisted HL7 referral triage workflow for InterSystems IRIS AI Hub. ReferralPilot accepts a referral as an HL7 v2 message, checks it against a searchable local policy library, evaluates synthetic clinic capacity, and asks an IRIS AI Hub agent to record a reasoned specialty, urgency, and any missing information. Every AI recommendation remains pending until a human approves it. The workflow and its audit trail are stored in IRIS.
Deployment target: InterSystems IRIS Community AI Hub build
2027.1.0AI.109.0. The original contest baseline was build2026.3.0AI.154.0; the image tag remains configurable for a judging environment that uses another approved build. AI Hub is an Early Access build. Use it only under the contest permission described in the contest announcement.
Three synthetic ORM referrals exercise distinct outcomes:
The policy knowledge base uses AI Hub’s IRIS vector-backed RAG classes and local FastEmbed embeddings. If those components are unavailable in the image, the workflow degrades gracefully: /health reports knowledgeBase: fallback and the agent falls back to the deterministic SearchPolicies tool. The LLM is used for judgment and explanation; deterministic checks validate the recommendation and enforce the human-approval gate. The project contains no real patient data.
REFERRALPILOT_DEMO_MODE=true, the demo uses its deterministic replay mode so the workflow remains runnable.In the EAP portal, select AI Hub and download the current approved Community image for your platform. This project defaults to 2027.1.0AI.109.0; choose the x64 or ARM64 archive as appropriate.
Load the downloaded archive and identify its full image name:
docker image load -i iris-community-2027.1.0AI.109.0-docker.tar.gz
docker images
Retag the loaded image to the local name used by this project (replace <loaded-image-name> with the name printed above):
docker tag iris-community:2027.1.0AI.109.0
If the EAP portal supplies a different approved build, keep its exact local tag and set REFERRALPILOT_IMAGE in .env; the Compose build argument is configurable.
The portal has rotated early-access builds during the contest. Use the build explicitly approved for the target judging environment, record that tag in the submission, and run all validation gates against that exact image.
Optional: copy .env.example to .env and set OPENAI_API_KEY for live agent decisions. The defaults in docker-compose.yml already start the app in replay mode, so no .env file is required. Never commit .env or a real API key. For a shared environment, also set REFERRALPILOT_API_TOKEN and protect the dashboard URL from untrusted users.
Start the application:
docker compose up --build -d
Check that IRIS is ready and open the dashboard. Both web applications are created with AutheEnabled=32 (password authentication), so IRIS credentials must be supplied with HTTP Basic auth:
curl -u _SYSTEM:SYS http://localhost:52773/api/referralpilot/health
Open http://localhost:52773/csp/irisapp/ReferralPilot.UI.cls and sign in with _SYSTEM / SYS. The dashboard asks once for the same credentials so its API calls can be authorised, then remembers them for the browser session.
The first build installs the ZPM client, creates the IRISAPP database and namespace, compiles this project’s ObjectScript classes, creates the REST and CSP web applications, indexes the policy knowledge base, seeds three synthetic demo referrals, and starts the ensemble production. The %AI.* AI Hub classes ship inside the AI Hub image, so no external iris-llm ZPM package is installed. No AI Hub image, or image derived from it, is published by this repository.
The REST API is mounted at /api/referralpilot:
| Method | Path | Purpose |
|---|---|---|
GET |
/health |
Readiness check with agent-key, demo-mode, and knowledge-base status |
GET |
/referrals |
List referrals and workflow state |
GET |
/referral?id={id} |
Get one referral by id with full audit trail |
GET |
/outbound?id={id} |
Inspect the HL7 message produced after approval |
POST |
/hl7 |
Submit one HL7 v2 referral message (raw body, Content-Type: text/plain) |
POST |
/triageById?id={id} |
Queue the AI triage decision for referral {id} |
POST |
/triage |
Same as above with the id in the body: {"id":"..."} |
POST |
/approve |
Approve a pending recommendation and queue the downstream HL7 routing operation. Body: {"id":"...","reviewer":"...","comment":"..."} (id may also be passed as ?id=) |
POST |
/reject |
Reject a pending recommendation. Body: {"id":"...","reviewer":"...","comment":"..."} (id may also be passed as ?id=) |
POST |
/retry?id={id} |
Clear the failed-attempt counter and re-queue automated triage |
POST |
/manual-triage?id={id} |
Human completes a referral parked by the pipeline fallback. Body: {"specialty":"Cardiology","urgency":"URGENT","missingInformation":[],"rationale":"...","reviewer":"..."} |
GET |
/pipeline |
Pipeline health: status counts, manual queue, dead letters, alerts, recorded attempts |
GET |
/deadletters |
Dead-letter records written by the fallback operation |
GET |
/alerts |
Operational alerts raised by the fallback operation |
POST |
/demo/reset |
Reload the three de-identified demo referrals |
Routes use plain paths with the referral id passed as a query parameter (?id=...). The %CSP.REST route-pattern compiler in this AI Hub build rejects {id} URL templates, so the original /referrals/{id}/... style routes were replaced with static paths. POST /approve, POST /reject, and POST /triage accept the id inside the JSON body, and POST /review accepts {"id":"...","decision":"approved|rejected","reviewer":"...","comment":"..."}.
The UI’s Load demo action loads the three synthetic examples defined in ReferralPilot.Store. Individual examples are also provided in data/; submit an HL7 file as the request body to /hl7 with Content-Type: text/plain.
/hl7 REST endpoint or from the inbound HL7 service watching /tmp/referralpilot-inbound, and stores the original payload with a stable message identifier.ReferralPilot.Production. Its business process invokes the AI Hub agent and the bounded tools. Tools can record a recommendation, but cannot approve it or emit a downstream referral.RoutingOperation emits a downstream HL7 ORM^O01 acceptance to the receiving clinic and writes an operator-visible copy to /tmp/referralpilot-outbound.Agent errors never auto-approve a referral. When no LLM key is configured, or REFERRALPILOT_DEMO_MODE=true, deterministic replay rules return visibly marked replay recommendations. The dashboard labels these decisions accordingly.
Automation that cannot finish must never silently drop a referral. ReferralPilot therefore implements an explicit exception pipeline inside the interoperability production rather than returning a bare HTTP error:
POST /triage {"id":"R3"}
|
v
TriageProcess (Business Process)
| bounded retries (MAXATTEMPTS = 3)
| each failure -> pipeline.attempt_failed audit + status triage_retrying
|
+-- success -> recommendation saved, status pending_review / needs_information
|
+-- exhausted
|
v
FallbackOperation (Business Operation)
|-- Store.RequestManualTriage -> status manual_triage_required
|-- Store.AddDeadLetter -> ^ReferralPilot("deadletter", id, n)
|-- Store.AddAlert -> ^ReferralPilot("alert")
+-- dead-letter JSON written to the DeadLetterDir setting
|
v
Human fallback: POST /manual-triage?id={id}
| (same specialty whitelist and urgency safety rules apply)
v
status pending_review -> normal Approve / Reject gate
Design points:
TriageProcess stops after MAXATTEMPTS and always returns a success status, so the Ensemble message is not re-queued forever.DeadLetterDir production setting, so it can be pointed at a shared volume without a code change.POST /retry?id={id} clears the attempt counter and re-queues triage, so an operator can recover after fixing the provider.Store.ManualTriage reuses RecordRecommendation, so the specialty whitelist, urgency enumeration, and acute-symptom escalation (ROUTINE to URGENT) still apply to decisions entered by a person.manual queue / dead letters / alerts, parked referrals render a “Pipeline fallback” panel with Retry automated triage and Complete triage manually.New pipeline states: triage_retrying (an automated attempt failed and will be retried) and manual_triage_required (automation is exhausted and a clinician must complete triage).
The production closes the loop around the AI decision: messages enter through a service, and only human-approved referrals leave through an operation.
EHR export / HL7 drop REST client
| |
v v
/tmp/referralpilot-inbound POST /hl7
| |
+----------------+-------------------+
v
HL7Service (Business Service, Ens.InboundAdapter)
| Store.CreateFromHL7 -> idempotent by MSH-10
| consumed files move to /tmp/referralpilot-inbound/consumed
v
TriageProcess -> FallbackOperation (see the previous section)
v
Human Approve / Reject gate
v approved only
RoutingOperation (Business Operation)
| every other status is audited as routing.skipped
+-> ^ReferralPilot("outbound", id)
+-> /tmp/referralpilot-outbound/<id>.hl7 (HL7 ORM^O01)
HL7Service only reads files, validates them with the same deterministic parser used by the REST endpoint, archives the source file, and queues triage. It never calls the agent directly.hl7.duplicate_ignored and does not re-queue triage.RoutingOperation refuses to emit anything unless the referral status is approved; a rejected or pending referral can never reach the downstream clinic.MSH-10 is OUT-<referral id>, OBR-4 carries the normalized specialty code (CARD, NEURO, ONC, ORTHO, GENERAL), and free text is delimiter-escaped so it cannot break the pipe/caret hierarchy.routing.queue_failed; the clinician’s approval is never rolled back, and the outbound payload stays in ^ReferralPilot("outbound", id) for inspection.Drop an HL7 file into the inbox to exercise the service without the REST API:
docker compose exec iris sh -c "mkdir -p /tmp/referralpilot-inbound && sed 's/MSG-CARDIO-001/CLINIC-20261102-A/g' /home/irisowner/dev/data/referral-cardio.hl7 > /tmp/referralpilot-inbound/clinic-1.hl7"
The service picks the file up within one adapter interval (5 seconds), archives it, and queues AI triage with the same business process the REST endpoint uses. In replay mode the new referral moves automatically to pending_review (or needs_information when a required result is missing), so it appears in the dashboard already awaiting the human approval gate.
| Variable | Default | Description |
|---|---|---|
OPENAI_API_KEY |
empty | OpenAI key for live AI Hub decisions. Omit for replay mode |
REFERRALPILOT_MODEL |
gpt-5-nano |
Model name passed to the AI Hub provider |
REFERRALPILOT_DEMO_MODE |
true |
Forces deterministic replay mode regardless of whether a provider key is set |
REFERRALPILOT_IMAGE |
iris-community:2027.1.0AI.109.0 |
Local EAP image tag used by the Compose build |
REFERRALPILOT_ALLOW_DEMO_RESET |
demo-mode only | Allows /demo/reset to replace all workflow data in live mode |
REFERRALPILOT_API_TOKEN |
empty | Optional shared secret. When set, every endpoint except /health requires X-ReferralPilot-Token |
REFERRALPILOT_REQUIRE_REVIEWER |
auto | In live mode, requires a non-placeholder reviewer identity; set true/false to override |
Set REFERRALPILOT_DEMO_MODE=false and provide OPENAI_API_KEY to exercise live agent decisions.
Compose binds both exposed ports to 127.0.0.1 so the demo is not exposed to the LAN by default. Change the port bindings deliberately when deploying behind a TLS reverse proxy. For any shared deployment, change the default IRIS SYS password and set REFERRALPILOT_API_TOKEN.
The AI Hub build supports OpenAI, Anthropic, Gemini, Amazon Bedrock, and experimental providers. Adapting provider selection is isolated in ReferralPilot.Agent. Judges can use their own key in .env.
Referral state and a chronological audit trail are persisted in IRIS globals. Each event records the referral ID, stage, actor (system, agent, or reviewer), timestamp, outcome, and relevant evidence. Agent sessions expose token and tool-call statistics in AI Hub; the UI displays the saved decision mode and the workflow trace. The Health endpoint reports knowledgeBase, demoMode, agentKeyConfigured, apiTokenRequired, and reviewerIdentityRequired so the runtime can be diagnosed at a glance.
The repository ships four unit-test classes under src/ReferralPilot/Tests/:
ReferralPilot.Tests.Store — HL7 parsing, specialty normalization, replay triage urgency rules, safety escalation, review workflow, audit trail, edge cases.ReferralPilot.Tests.Agent — Demo-mode detection, missing-key replay fallback, unknown-referral error path.ReferralPilot.Tests.Pipeline — Attempt counting, fallback operation routing, dead-letter and alert recording, manual triage recovery, safety escalation on the human path, pipeline statistics.ReferralPilot.Tests.Routing — Approved referrals produce an outbound ORM^O01, unapproved referrals are skipped and audited, unknown referrals raise an alert, free-text escaping.These classes extend %UnitTest.TestCase and use the standard %occStatus / %occInclude includes. The AI Hub EAP image ships a stub %UnitTest.TestCase without the assert methods, so .dockerignore keeps src/ReferralPilot/Tests out of the container image and the build stays clean. On an IRIS build that includes a complete %UnitTest implementation (for example a standard Community distribution), run all tests inside the container:
docker compose exec iris iris session IRIS -U IRISAPP "##class(%UnitTest.Manager).RunTest(\"ReferralPilot.Tests\")"
Run a single test class:
docker compose exec iris iris session IRIS -U IRISAPP "##class(%UnitTest.Manager).RunTest(\"ReferralPilot.Tests.Store\")"
Windows PowerShell note. The examples above use POSIX shell quoting. PowerShell strips the inner quotes before
iris sessionreceives them, so the command fails with<NOROUTINE>. Pipe the ObjectScript through stdin instead (-Tdisables the TTY so stdin is passed through):'write ##class(%UnitTest.Manager).RunTest("ReferralPilot.Tests"),! halt' | docker compose exec -T iris iris session IRIS -U IRISAPPAlternatively run the
bashexamples from WSL, Git Bash, or macOS/Linux.
The API and replay mode do not require an external model key. Live Agent calls require outbound network access from the container and the configured provider key.
Run the static acceptance gate before every build:
.\tests\validate.ps1
It verifies required files, ZPM metadata and dependencies, Compose configuration, HL7 fixtures, known-bad Dynamic Object expressions, workflow guards, and whether the selected EAP image is loaded locally.
After the container starts, run the complete end-to-end workflow:
.\tests\smoke.ps1
The smoke test waits for readiness, resets the synthetic cases, runs triage, verifies human approval, waits for downstream HL7 routing, confirms that an approved referral cannot be triaged again, and checks duplicate HL7 idempotency. If REFERRALPILOT_API_TOKEN is set, pass the same value with -Token.
The complete gate, including build, IRIS unit tests, and HTTP smoke test, is:
.\scripts\load-aihub-image.ps1 -ImageArchive .\iris-community-2027.1.0AI.109.0-docker.tar.gz
.\tests\run-all.ps1
With REFERRALPILOT_DEMO_MODE=false and OPENAI_API_KEY configured, validate the actual model rather than replay logic:
$env:REFERRALPILOT_ALLOW_DEMO_RESET = 'true'
.\tests\live-eval.ps1
This uses three fixed cases and fails unless every recommendation is genuinely live, the specialty and urgency match the policy expectations, and the imaging gap is explicitly reported.
Create a versioned ZPM/Open Exchange archive after validation:
.\tests\package.ps1
The archive, manifest, and SHA-256 are written to dist/.
The defensible acceptance sequence is:
ReferralPilot.Tests reports no unit-test failures (on a build that includes %UnitTest).These gates make the distinction between “code exists”, “code compiles”, and “the clinical workflow behaves correctly”. Passing only the first is not considered a working submission.
received; failed or parked referrals use explicit retry/manual paths.needs_information referral requires a documented reviewer comment.ORM^O01, PID-3, OBR-4, NTE, and MSH-10.AutheEnabled=32 (IRIS password authentication). For any non-demo deployment, replace the default _SYSTEM/SYS credentials, enable TLS, and issue a dedicated least-privilege user for the dashboard and API.MIT. See https://github.com/Brett-git-app/ReferralPilot/blob/main/LICENSE.