Skip to contents

Overview

Clinical, behavioral, educational, and medical researchers routinely analyze rich unstructured text—therapy progress notes, EMA journals, student writing, and patient narratives—that cannot be transmitted to external cloud LLM APIs under IRB, HIPAA, or FERPA data-use agreements.

airgapllm provides a complete, privacy-first R workbench for verifiably offline local LLM workflows:

  1. Air-Gapped Container Lifecycle Manager: Generate pinned, hardened Docker (--network none, --read-only, --cap-drop ALL) and HPC Apptainer .def configurations for Ollama, llama.cpp, and vLLM, verify local model weight SHA-256 digests, and run automated pre-flight isolation checks.
  2. Pre-Inference Privacy & PII Engine: Detect, redact, or reversibly pseudonymize (HMAC-SHA256 + AES-256-CBC encrypted vault) direct identifiers in pure R before any text reaches the model.
  3. Crash-Resumable Schema-Enforced Batch Extractor: Extract strictly typed tibbles from R data frames with automated repair retries for malformed outputs and atomic per-row JSONL checkpointing.
  4. Immutable Audit Trail & IRB Protocol Generator: Maintain tamper-evident SHA-256 hash-chained JSONL logs (strictly barring raw text/PII) and generate ready-to-paste IRB/HIPAA Methods boilerplate.

Everything in this vignette runs 100% offline using the built-in deterministic runtime_mock(), while producing the exact container configurations, schemas, checkpoints, audit logs, and IRB narratives used in production on local GPU workstations and HPC nodes.

Step 1: Define a Hardened Air-Gapped Container Specification

Pin your local inference container by exact SHA-256 image digest and local model weight digest:

# Create a synthetic local GGUF model weight file for this demonstration
tmp_dir <- tempfile("airgap_models_")
dir.create(tmp_dir)
model_file <- file.path(tmp_dir, "llama-3.1-8b-instruct-q4_K_M.gguf")
writeBin(charToRaw("demo-local-open-weights-binary-v1"), model_file)

# Compute and verify streaming SHA-256 digest of the local weights
model_ver <- verify_model_digest(model_file)
model_ver
#> <airgap_digest_verification> [COMPUTED]
#>   Path:       /tmp/Rtmp6L91Fo/airgap_models_1d134376899b/llama-3.1-8b-instruct-q4_K_M.gguf
#>   Size bytes: 33
#>   Actual:     sha256:76dd95b3a60524dc3ae8890d0c6a330fc958c3a2efbfe2f363e3dfc77b131e92

# Define a hardened, digest-pinned container spec
spec <- airgap_container_spec(
  backend = "llama.cpp",
  image = "ghcr.io/ggerganov/llama.cpp",
  image_digest = paste0("sha256:", strrep("a", 64)),
  model_dir = tmp_dir,
  model_file = basename(model_file),
  model_digest = model_ver$actual_digest,
  gpu = "nvidia",
  memory_limit = "24g",
  user = "1000:1000"
)
spec
#> <airgap_container_spec>
#>   Backend:       llama.cpp
#>   Image:         ghcr.io/ggerganov/llama.cpp@sha256:aaaaaaaaaaaa...
#>   Network mode:  none
#>   Read-only:     TRUE | Cap-drop: ALL
#>   Model mount:   /tmp/Rtmp6L91Fo/airgap_models_1d134376899b -> /models:ro
#>   Model file:    llama-3.1-8b-instruct-q4_K_M.gguf
#>   GPU:           nvidia (all)
#>   Spec digest:   sha256:d21034244c3ef4dbe6d50a3181795a9ecc3ee0c91b6177d94d2952069e08baaa

Generate reproducible deployment artifacts for either a lab workstation (emit_docker_run(), emit_docker_compose()) or a university HPC GPU cluster (emit_apptainer_def()):

cat(emit_docker_run(spec), "\n")
#> docker run --rm --network none --read-only --cap-drop ALL --security-opt no-new-privileges:true --tmpfs /tmp:rw,noexec,nosuid,size=512m --tmpfs /run:rw,noexec,nosuid,size=64m --user 1000:1000 --memory 24g --gpus all -v /tmp/Rtmp6L91Fo/airgap_models_1d134376899b:/models:ro -e DO_NOT_TRACK=1 -e HF_DATASETS_OFFLINE=1 -e HF_HUB_OFFLINE=1 -e TRANSFORMERS_OFFLINE=1 ghcr.io/ggerganov/llama.cpp@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa --model /models/llama-3.1-8b-instruct-q4_K_M.gguf --host 127.0.0.1 --port 8080
cat(emit_apptainer_def(spec), "\n")
#> # Generated by airgapllm 0.6.0
#> # Air-gapped HPC execution command:
#> #   apptainer build airgapllm-llama-cpp.sif airgapllm.def
#> #   apptainer run --containall --no-home --net --network none --nv --bind '/tmp/Rtmp6L91Fo/airgap_models_1d134376899b:/models:ro' airgapllm-llama-cpp.sif
#> 
#> Bootstrap: docker
#> From: ghcr.io/ggerganov/llama.cpp@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
#> 
#> %labels
#>     org.airgapllm.generator airgapllm-0.6.0
#>     org.airgapllm.backend llama.cpp
#>     org.airgapllm.spec_digest sha256:d21034244c3ef4dbe6d50a3181795a9ecc3ee0c91b6177d94d2952069e08baaa
#>     org.airgapllm.network_mode none
#>     org.airgapllm.model_digest sha256:76dd95b3a60524dc3ae8890d0c6a330fc958c3a2efbfe2f363e3dfc77b131e92
#> 
#> %environment
#>     export DO_NOT_TRACK='1'
#>     export HF_DATASETS_OFFLINE='1'
#>     export HF_HUB_OFFLINE='1'
#>     export TRANSFORMERS_OFFLINE='1'
#> 
#> %post
#>     mkdir -p /models
#>     chmod 755 /models || true
#> 
#> %runscript
#>     exec llama-server '--model' '/models/llama-3.1-8b-instruct-q4_K_M.gguf' '--host' '127.0.0.1' '--port' '8080' "$@"

Run an automated pre-flight isolation and weight-integrity check before touching any participant data:

pf <- preflight_isolation_check(
  spec = spec,
  endpoint = "http://127.0.0.1:8080/v1",
  model_path = model_file
)
pf
#> <airgap_preflight> [PASS]
#>   Checked at:   2026-11-28T20:38:16Z
#>   Endpoint:     loopback
#>   Record hash:  sha256:77bbce3eaae039fdc5d11840c049a53acc6cafeaaf82b5f2d9685837f1a03369
#>   [PASS] network_isolation: Container network_mode is 'none'.
#>   [PASS] read_only_rootfs: Container root filesystem is read-only.
#>   [PASS] capabilities_dropped: All Linux capabilities dropped (--cap-drop ALL).
#>   [PASS] no_new_privileges: no-new-privileges security option enabled.
#>   [PASS] image_digest_pinned: Image pinned to sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.
#>   [PASS] host_bind_loopback: Host bind interface restricted to loopback (127.0.0.1).
#>   [PASS] container_env_isolation: Container environment preserves mandatory offline/loopback flags with no proxy overrides.
#>   [PASS] endpoint_loopback_only: Verified canonical loopback host (127.0.0.1).
#>   [PASS] model_digest_verified: Model weights verified against pinned SHA-256 (sha256:76dd95b3a60524dc3ae8890d0c6a330fc958c3a2efbfe2f363e3dfc77b131e92).
#>   [PASS] env_proxy_isolation: No outbound proxy environment variables detected.

Notice that any attempt to connect to a remote cloud API or non-loopback host is rejected immediately:

is_loopback_endpoint("http://127.0.0.1:8080/v1")
#> [1] TRUE
is_loopback_endpoint("https://api.openai.com/v1")
#> [1] FALSE

Step 2: Inspect Pre-Run PII Coverage

Consider a small synthetic batch of clinical session notes containing direct identifiers:

notes <- tibble(
  note_id = sprintf("NOTE_%02d", 1:6),
  note_text = c(
    "Patient: Jane Doe (MRN: 884210) reported mild sleep disruption on 2026-03-14.",
    "Dr. Robert Vance emailed follow-up plan to jane.doe@clinic.org; anxiety reduced.",
    "Emergency contact phone (555) 234-5678 verified; no acute crisis indicators.",
    "DOB: 1989-11-02; lives at 742 Evergreen Terrace, Hartford, CT 06103. Mood stable.",
    "Student ID: STU-44102 completed coping exercises after Cognitive Behavioral Therapy.",
    "Progress note with zero personal identifiers; affect calm and engaged."
  )
)

# Aggregate privacy coverage report (strictly zero raw PII stored or printed)
pii_privacy_report(notes, text_col = "note_text")
#> <airgap_privacy_report> (aggregate counts only; zero raw PII)
#>   Documents scanned:  6
#>   Documents with PII: 5 (83.33%)
#>   Total detections:   9
#>   By entity type:
#>     - date: 2 (2 docs, 33.33%)
#>     - email: 1 (1 docs, 16.67%)
#>     - mrn_id: 2 (2 docs, 33.33%)
#>     - person_name: 2 (2 docs, 33.33%)
#>     - phone: 1 (1 docs, 16.67%)
#>     - street_address: 1 (1 docs, 16.67%)

Step 3: Declare a Strict Typed Extraction Schema

Define the exact R column types, enum levels, numeric bounds, and nullability rules for downstream statistical analysis:

clinical_schema <- extraction_schema(
  sentiment = schema_field(
    "enum",
    values = c("positive", "neutral", "negative"),
    description = "Overall emotional tone of the session note"
  ),
  severity = schema_field(
    "integer",
    min = 0L,
    max = 10L,
    description = "Clinical symptom severity rating from 0 to 10"
  ),
  confidence = schema_field(
    "numeric",
    min = 0,
    max = 1,
    nullable = TRUE,
    description = "Model extraction confidence score"
  ),
  crisis_flag = schema_field(
    "logical",
    description = "TRUE if acute safety or crisis risk is indicated"
  ),
  name = "clinical_session_coding"
)
clinical_schema
#> <airgap_schema> 'clinical_session_coding' (4 fields, strict_keys=TRUE)
#>   - sentiment: enum (values=[positive,neutral,negative])
#>   - severity: integer (min=0, max=10)
#>   - confidence: numeric (min=0, max=1, nullable)
#>   - crisis_flag: logical
#>   Schema digest: sha256:cd6b3c558997cb404d9a53eb9aefb7c2b3c577ca3e5a9747398a4140cbe8144c

Step 4: Execute Crash-Resumable, Schema-Enforced Batch Extraction

Now run airgap_extract() with:

  • Mandatory pre-inference PII redaction (pii_policy = "redact"),
  • Simulated malformed JSON on NOTE_02 to demonstrate automatic structured repair retries,
  • Atomic row-level checkpointing (checkpoint_path), and
  • Automatic hash-chained IRB/HIPAA audit logging (audit_log_path).

In production on a local GPU workstation, swap runtime_mock() for runtime_ollama("llama3.1:8b-instruct-q4_K_M") or runtime_openai_local("llama-3.1-8b", base_url = "http://127.0.0.1:8080/v1").

ck_path <- tempfile(fileext = ".checkpoint.jsonl")
audit_path <- tempfile(fileext = ".audit.jsonl")

rt <- runtime_mock(
  model = "llama-3.1-8b-instruct-q4_K_M",
  seed = 2026L,
  malform_schedule = list(
    NOTE_02 = c(
      "{truncated_json",
      '{"sentiment":"very_bad","severity":99,"confidence":0.8,"crisis_flag":false}'
    )
  )
)

extracted <- airgap_extract(
  data = notes,
  text_col = "note_text",
  schema = clinical_schema,
  runtime = rt,
  id_col = "note_id",
  pii_policy = "redact",
  checkpoint_path = ck_path,
  audit_log_path = audit_path,
  container_spec = spec,
  model_path = model_file,
  max_retries = 2L
)

extracted
#> # A tibble: 6 × 9
#>   note_id sentiment severity confidence crisis_flag .status .attempts .error
#>   <chr>   <chr>        <int>      <dbl> <lgl>       <chr>       <int> <chr> 
#> 1 NOTE_01 positive         3      0.656 TRUE        ok              1 NA    
#> 2 NOTE_02 neutral          5      0.958 TRUE        ok              3 NA    
#> 3 NOTE_03 neutral          1      0.574 TRUE        ok              1 NA    
#> 4 NOTE_04 positive         8      0.871 TRUE        ok              1 NA    
#> 5 NOTE_05 positive         8      0.527 TRUE        ok              1 NA    
#> 6 NOTE_06 positive         6      0.759 TRUE        ok              1 NA    
#> # ℹ 1 more variable: .elapsed_ms <dbl>

Notice that NOTE_02 succeeded on attempt 3 after two automatic structured repair retries, and every column has strict R types (character, integer, numeric, logical).

extraction_throughput(extracted)
#> $rows_total
#> [1] 6
#> 
#> $rows_resumed
#> [1] 0
#> 
#> $rows_processed
#> [1] 6
#> 
#> $rows_succeeded
#> [1] 6
#> 
#> $rows_failed
#> [1] 0
#> 
#> $total_retries
#> [1] 2
#> 
#> $output_pii_leaks
#> [1] 0
#> 
#> $elapsed_sec
#> [1] 0.015
#> 
#> $rows_per_sec
#> [1] 400

Step 5: Verify the Immutable Audit Log & Generate IRB Boilerplate

Verify cryptographic chain integrity from GENESIS to the latest entry, then render a ready-to-paste Methods / IRB Data-Security protocol section directly from the verified ledger:

audit_log_verify(audit_path)
#> <airgap_audit_verification> [VALID]
#>   Entries verified: 1
#>   Chain head hash:  sha256:e3c83e543498e35c0cb77894c2950224d20df9b6e033304034fd465cd3dbaa3b

irb_text <- generate_irb_narrative(
  source = audit_path,
  study_title = "Offline Clinical Progress Note Phenotyping",
  protocol_id = "IRB-2026-0412",
  institution = "University Research Medical Center",
  regulatory_framework = c("HIPAA", "IRB"),
  format = "markdown"
)

cat(irb_text)
#> ## Data Security & Air-Gapped Local AI Processing Protocol
#> 
#> - **Study Title:** Offline Clinical Progress Note Phenotyping
#> - **Protocol ID:** IRB-2026-0412
#> - **Institution:** University Research Medical Center
#> - **Regulatory Scope:** HIPAA / IRB
#> - **Run ID:** `run_20261128T203816Z_9640d6a6` (2026-11-28T20:38:16Z)
#> 
#> ### 1. Offline Local AI Execution & Network Isolation
#> 
#> All automated natural language processing was executed strictly offline using `airgapllm` (v0.6.0, R 4.6.2) with **zero transmission of research data to external cloud APIs or third-party servers**. Inference was configured for local execution (`backend = "llama.cpp"`, endpoint class: `offline_mock`) under hardened container controls (`network_mode = "none"`, read-only root filesystem, all Linux capabilities dropped, `no-new-privileges`, read-only model volume mounts, and offline telemetry suppression). Automated pre-flight isolation checks (`preflight_isolation_check()`) returned **`PASS`** (attestation hash: `sha256:404102d3e381c2dbe98700393dbb833db0dc8897f48481698702e5344633d3cb`), confirming strict local/loopback confinement and proxy bypass prior to reading participant text.
#> 
#> ### 2. Pre-Inference De-Identification & Privacy Safeguards
#> 
#> Prior to prompt construction, all unstructured text was processed in-memory by the deterministic pure-R `airgapllm` PII detection and redaction engine (`pii_policy = "redact"`, config digest `sha256:f76846ac5dfd228489ebd8dcb73058007a0acb02b83c072fc0baeda2f2c59119`). A total of **9** direct identifier span(s) across **6** entity class(es) were replaced with non-reversible typed placeholders (e.g., `[REDACTED_PERSON_NAME]`, `[REDACTED_EMAIL]`) before any text reached the local inference runtime.
#> 
#> Input text is canonicalized against Unicode homoglyphs and zero-width obfuscators prior to scanning, including HIPAA Safe Harbor controls for ages > 89 and geographic ZIP codes (including the 17 restricted 3-digit prefixes). Untrusted research text is wrapped in explicit data-boundary delimiters to mitigate embedded prompt-injection attacks, and generated character outputs undergo post-inference PII leakage scanning (0 post-inference leak(s) detected/mitigated). Neither raw participant text nor raw PII strings are persisted in crash-recovery checkpoints or compliance logs. Audit log writes enforce a strict schema allowlist and automated PII scanning that aborts execution if any raw text key or sensitive identifier is encountered.
#> 
#> ### 3. Model Provenance, Schema Enforcement & Reproducibility
#> 
#> Structured extraction used local open-weights model `llama-3.1-8b-instruct-q4_K_M` (weight SHA-256: `sha256:76dd95b3a60524dc3ae8890d0c6a330fc958c3a2efbfe2f363e3dfc77b131e92`) with deterministic decoding parameters (`temperature = 0`, `seed = 2026`, `top_p = 1`). Every model generation was validated against a strictly typed output schema (schema SHA-256: `sha256:cd6b3c558997cb404d9a53eb9aefb7c2b3c577ca3e5a9747398a4140cbe8144c`; prompt template SHA-256: `sha256:6a44be68e580b91843102b7759acb2b137a5b2000fb7f33726aebabd80d3cebd`) with bounded structured repair retries for malformed outputs and atomic row-level JSONL checkpointing. Across **6** input record(s), **6** succeeded and **0** failed (0 resumed from checkpoint; 2 structured repair retries).
#> 
#> ### 4. Immutable Compliance Audit Trail
#> 
#> Run provenance is recorded in a tamper-evident, SHA-256 hash-chained JSONL audit log linking each entry to its predecessor from `GENESIS`. Audit verification status: **VERIFIED (1 chained entries; zero tampering detected)** (chain head digest: `sha256:e3c83e543498e35c0cb77894c2950224d20df9b6e033304034fd465cd3dbaa3b`).
#> 
#> ### Technical Provenance Summary
#> 
#> | Control / Artifact | Verified Value |
#> | :--- | :--- |
#> | Isolation Pre-Flight Status | `PASS` (`sha256:404102d3e381c2dbe98700393dbb833db0dc8897f48481698702e5344633d3cb`) |
#> | Endpoint Class | `offline_mock` |
#> | Container Backend / Network | `llama.cpp` / `none` |
#> | Container Image Digest | `sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa` |
#> | Container Spec Digest | `sha256:d21034244c3ef4dbe6d50a3181795a9ecc3ee0c91b6177d94d2952069e08baaa` |
#> | Model Name | `llama-3.1-8b-instruct-q4_K_M` |
#> | Model Weight SHA-256 | `sha256:76dd95b3a60524dc3ae8890d0c6a330fc958c3a2efbfe2f363e3dfc77b131e92` |
#> | Prompt Template SHA-256 | `sha256:6a44be68e580b91843102b7759acb2b137a5b2000fb7f33726aebabd80d3cebd` |
#> | Output Schema SHA-256 | `sha256:cd6b3c558997cb404d9a53eb9aefb7c2b3c577ca3e5a9747398a4140cbe8144c` |
#> | Decoding Seed / Temperature | `2026` / `0` |
#> | Pre-Inference PII Policy | `redact` (`9` detections) |
#> | Rows Processed (OK / Failed) | `6` (`6` / `0`) |
#> | Audit Chain Head Hash | `sha256:e3c83e543498e35c0cb77894c2950224d20df9b6e033304034fd465cd3dbaa3b` |
#> | Software Environment | `airgapllm 0.6.0` / `R 4.6.2` |
#> 
#> #### Aggregate Pre-Inference PII Redaction Counts (Zero Raw Values Stored)
#> 
#> | Entity Type | Count |
#> | :--- | ---: |
#> | `date` | 2 |
#> | `email` | 1 |
#> | `mrn_id` | 2 |
#> | `person_name` | 2 |
#> | `phone` | 1 |
#> | `street_address` | 1 |