Air-gapped offline AI workstation setup with secure NVMe storage and zero external network connectivity
AI Hardware
Intermediate
24 min read Updated

How to Build an Offline AI System: Air-Gapped Setup Guide (2026)

Build an offline AI system, local MCP agent, and air-gapped Ollama server in 2026. Covers VRAM sizing, LAN binding, local RAG, and zero-egress security.

build offline ai offline ai ai agent offline offline ai server air gapped ai local mcp local rag offline zero egress ai

Building an offline AI system eliminates cloud data exposure, vendor outages, and per-token API fees by executing quantized 12B to 32B models, local RAG pipelines, and MCP tool-calling agents strictly on local hardware at 45 to 120 tokens per second. Cloud-hosted APIs force proprietary source code, clinical records, and internal telemetry across shared networks where retention policies and billing tiers shift without warning.

Engineers deploying disconnected AI workstations must align GPU VRAM bandwidth, sneakernet dependency staging, LAN server access controls, and kernel-level zero-egress verification. This engineering blueprint covers everything required to build an offline AI stack in late 2026, from hardware sizing and local Model Context Protocol (MCP) agents to embedded ChromaDB search and continuous packet auditing.

Key Takeaways

  • An offline AI system runs quantized open-weights models such as Microsoft Phi-4 14B and Google Gemma 4 12B strictly on local hardware without internet connectivity, eliminating cloud API token costs and third-party data exposure.
  • A workstation with 12GB to 16GB of GPU VRAM runs 12B to 14B parameter models at 45 to 75 tokens per second, while spilling residual layers to DDR5 system RAM drops generation throughput by up to 90%.
  • Running an AI agent offline pairs an Ollama or llama.cpp inference backend with local Model Context Protocol (MCP) tool servers over stdio transport, enabling automated tool execution with zero open network sockets.
  • Deploying an offline AI server across an isolated LAN requires setting OLLAMA_HOST=0.0.0.0:11434 and OLLAMA_NO_CLOUD=1 alongside subnet-restricted iptables rules and continuous tcpdump packet auditing.

Why Build an Offline AI System? The Case for True Air-Gap Isolation

Organizations build an offline AI system to guarantee physical data sovereignty, maintain uninterrupted availability during cloud outages, and eliminate recurring per-token API expenses by keeping all weights, embeddings, and prompts inside a verified local security perimeter.

Regulatory Compliance and Physical Data Sovereignty

Modern engineering teams rely on automated document synthesis, code refactoring, and semantic search across massive internal archives. Sending prompts to public cloud endpoints routes confidential payloads across external backbones, exposing proprietary logic to remote logging and third-party subpoenas.

Teams operating under HIPAA, GDPR, ITAR, or FedRAMP High mandates cannot transmit unencrypted clinical records, financial risk models, or defense documentation to multitenant cloud APIs. Running inference on an air-gapped workstation satisfies strict compliance audits because zero network packets exit the physical facility perimeter.

Eliminating Hidden Telemetry and Cloud Outage Risk

Many developers familiar with running AI models locally with Ollama assume that local execution automatically implies complete network isolation. In practice, default desktop installations attempt outbound telemetry pings, background update checks, and remote registry lookups on daemon startup.

High-assurance deployments eliminate hidden network listeners by enforcing explicit offline flags or executing compiled C++ binaries directly from the llama.cpp Official GitHub Repository. Disconnected execution also removes exposure to regional cloud outages and sudden API rate limits in industrial control rooms, offshore research vessels, and classified testing labs.

Hardware Requirements and VRAM Sizing for Disconnected AI Systems

Selecting the right memory architecture determines whether an offline AI workstation responds interactively or stalls under severe PCIe bandwidth bottlenecks. Static model weights and active context caches must reside entirely within high-speed GPU VRAM or unified memory to sustain readable generation speeds.

The matrix below maps real-world late 2026 throughput across workstation hardware tiers running standard Q4_K_M quantized open-weights models:

Hardware Architecture Memory Configuration Target Model Class (Nov 2026) Generation Speed (TPS) Primary Practical Use Case
Modern Multi-Core CPU 32 GB DDR5 System RAM 2B - 4B (Gemma 4 E2B, Phi-4-mini) 10 - 25 TPS Background Batch Document Parsing
NVIDIA RTX 4060 / 5060 8 GB - 12 GB GDDR6 12B - 14B (Gemma 4 12B, Phi-4 14B) 45 - 75 TPS Low-Latency Interactive Chat & RAG
Apple Silicon M4 Pro / Max 36 GB - 64 GB Unified Memory 24B - 32B (Mistral Small 4 24B, Qwen 2.5 Coder 32B) 30 - 55 TPS Local Code Synthesis & MCP Agents
NVIDIA RTX 4090 / 5090 24 GB - 32 GB GDDR6X / GDDR7 26B - 32B (Gemma 4 31B, DeepSeek-R1-Distill-Qwen-32B) 55 - 120 TPS Real-Time Multi-Step Agent Reasoning
Dual GPU / High-Memory Node 64 GB - 128 GB VRAM / Unified 100B+ MoE (Llama 4 Scout 17B Active MoE) 30 - 55 TPS Multi-Document Enterprise Synthesis

Consumer GPU and Unified Memory Hardware Tiers

Dedicated GPUs with 12GB to 16GB of VRAM form the practical baseline for offline AI chatbot hardware requirements. Memory buses delivering 500 GB/s or higher allow Q4_K_M quantized Microsoft Phi-4 14B (~8.5GB footprint) and Google Gemma 4 12B (~7.5GB footprint) to sustain 45 to 75 tokens per second with room left for context cache.

Workstations targeting 24B to 32B coding and reasoning models require 24GB+ of VRAM or unified memory. Apple Silicon nodes share a single pool of high-bandwidth LPDDR5X memory across CPU and GPU cores; engineers sizing compact desktop clusters can follow our Mac Mini home AI server build guide for dedicated Apple Silicon hardware configurations.

Model Quantization and KV Cache Memory Allocation

Memory planning for offline language models must account for both static GGUF weight storage and dynamic Key-Value (KV) cache growth. Enabling Flash Attention (-fa in llama.cpp or OLLAMA_FLASH_ATTENTION=1) substantially compresses KV cache memory overhead when processing 32K to 128K token contexts.

According to 2026 llama.cpp memory bandwidth benchmarks, offloading residual layers from 500+ GB/s GPU VRAM to 60-90 GB/s DDR5 system RAM reduces token generation throughput by up to 90%, dropping interactive speed from 50+ tokens per second down to 4 tokens per second.

Memory Hierarchy Tier Capacity & Protocol Measured Bandwidth Assigned Model Components Inference Throughput
Dedicated GPU VRAM 12 GB - 32 GB GDDR6X / GDDR7 500 - 1,790 GB/s Static Weights + Active KV Cache 45 - 120 Tokens/sec
System DDR5 RAM (Fallback) 32 GB - 64 GB DDR5 60 - 90 GB/s Residual Offloaded Layers 3 - 8 Tokens/sec
High-Speed NVMe Storage PCIe 4.0 / 5.0 SSD 5,000 - 10,000 MB/s Cold GGUF Weight Checkpoints Cold Loading Only

[!TIP] Stick to Q4_K_M or Q5_K_M quantization tiers and cap num_ctx to your actual prompt budget. Keeping 100% of transformer layers inside physical VRAM always outperforms running a larger precision model that spills even 1GB into system RAM.

Running an Offline AI Agent and Local AI Server (Ollama and Local MCP)

Basic offline chat only answers questions from static model weights. Production engineering workflows require an offline AI server shared safely across an isolated local network and an offline AI agent capable of invoking local scripts, querying internal SQLite databases, and inspecting system logs without internet access.

Configuring a LAN Offline AI Server with Ollama and Firewall Controls

By default, Ollama binds strictly to the host loopback interface (127.0.0.1:11434), blocking requests from sibling developer machines on the same air-gapped network. To operate a shared offline AI server across an isolated LAN, configure a systemd drop-in override that binds to all internal interfaces while disabling cloud registry fallbacks.

Run sudo systemctl edit ollama.service on the air-gapped Linux server and insert the following environment block:

[Service]
Environment="OLLAMA_HOST=0.0.0.0:11434"
Environment="OLLAMA_NO_CLOUD=1"
Environment="OLLAMA_FLASH_ATTENTION=1"
Environment="OLLAMA_MODELS=/opt/offline_ai/models"
Environment="OLLAMA_KEEP_ALIVE=24h"

Reload the service with sudo systemctl daemon-reload && sudo systemctl restart ollama. Setting OLLAMA_NO_CLOUD=1 prevents the daemon from hanging on external manifest lookups when a client requests a local model tag, while OLLAMA_KEEP_ALIVE=24h keeps weights pinned in VRAM between team requests.

Ollama does not include built-in API authentication. Exposing 0.0.0.0:11434 without network controls allows any host on the wire to pull, delete, or query models, so enforce subnet-scoped iptables rules that permit port 11434 strictly from your internal RFC 1918 LAN subnet while dropping all WAN egress:

#!/usr/bin/env bash
# Restrict LAN offline AI server to internal 192.168.50.0/24 subnet with zero WAN egress
set -euo pipefail

iptables -F
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP

# Allow loopback IPC and established local LAN replies
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
iptables -A INPUT -s 192.168.50.0/24 -p tcp --dport 11434 -j ACCEPT
iptables -A OUTPUT -d 192.168.50.0/24 -p tcp --sport 11434 -m state --state ESTABLISHED -j ACCEPT

This rule set allows authorized workstations on 192.168.50.0/24 to send inference requests to the GPU server over port 11434 while mathematically blocking the server from initiating any outbound connection to external IP addresses.

Building an Offline AI Agent with Local MCP Stdio Transport

To build an offline AI agent that executes deterministic local actions, pair Ollama’s OpenAI-compatible /v1/chat/completions endpoint with the Model Context Protocol. Engineers new to the protocol’s capability primitives can review our Model Context Protocol architecture guide for a breakdown of tools, resources, and prompts.

As defined in the Model Context Protocol Transports Specification, the stdio transport spawns local tool servers as child processes exchanging newline-delimited JSON-RPC 2.0 messages over stdin and stdout. Because stdio uses operating system pipes rather than TCP sockets, an offline AI agent can discover and execute local tools with zero listening network ports.

First, create a local MCP tool server (local_ops_mcp.py) using FastMCP from the official Python mcp package staged offline:

#!/usr/bin/env python3
"""Air-gapped local MCP stdio server exposing read-only SQLite audit log search."""
import sqlite3
import sys
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("OfflineOpsTools")

@mcp.tool()
def search_local_audit_logs(keyword: str, limit: int = 5) -> str:
    """Query local air-gapped SQLite audit logs by keyword."""
    conn = sqlite3.connect("file:/opt/offline_ai/audit.db?mode=ro", uri=True)
    cursor = conn.cursor()
    cursor.execute(
        "SELECT timestamp, severity, event FROM system_logs WHERE event LIKE ? LIMIT ?",
        (f"%{keyword}%", limit),
    )
    rows = cursor.fetchall()
    conn.close()
    return str(rows) if rows else "No matching local audit records found."

if __name__ == "__main__":
    # Never print to stdout; stderr is reserved for diagnostics under MCP stdio
    sys.stderr.write("Starting OfflineOpsTools MCP server over stdio...\n")
    mcp.run(transport="stdio")

Opening SQLite with mode=ro enforces read-only database access at the storage driver level, while writing startup diagnostics strictly to sys.stderr preserves the stdout JSON-RPC stream.

Next, create the offline agent orchestrator (offline_agent.py) that discovers tool schemas from the local MCP server and routes tool calls through a local tool-capable model such as qwen2.5-coder:32b or mistral-small4:

#!/usr/bin/env python3
"""Offline AI agent orchestrator connecting Ollama to a local MCP stdio server."""
import asyncio
import json
import requests
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

OLLAMA_CHAT_URL = "http://127.0.0.1:11434/v1/chat/completions"
MODEL_NAME = "qwen2.5-coder:32b"

async def run_offline_agent(user_prompt: str) -> str:
    server_params = StdioServerParameters(
        command="python3",
        args=["/opt/offline_ai/local_ops_mcp.py"],
    )

    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            tool_list = await session.list_tools()

            openai_tools = [
                {
                    "type": "function",
                    "function": {
                        "name": t.name,
                        "description": t.description,
                        "parameters": t.inputSchema,
                    },
                }
                for t in tool_list.tools
            ]

            messages = [{"role": "user", "content": user_prompt}]
            first_resp = requests.post(
                OLLAMA_CHAT_URL,
                json={"model": MODEL_NAME, "messages": messages, "tools": openai_tools},
                timeout=60,
            )
            first_resp.raise_for_status()
            assistant_msg = first_resp.json()["choices"][0]["message"]

            if assistant_msg.get("tool_calls"):
                messages.append(assistant_msg)
                for call in assistant_msg["tool_calls"]:
                    fn_name = call["function"]["name"]
                    fn_args = json.loads(call["function"]["arguments"])
                    mcp_result = await session.call_tool(fn_name, fn_args)
                    messages.append(
                        {
                            "role": "tool",
                            "tool_call_id": call["id"],
                            "content": str(mcp_result.content),
                        }
                    )

                final_resp = requests.post(
                    OLLAMA_CHAT_URL,
                    json={"model": MODEL_NAME, "messages": messages},
                    timeout=60,
                )
                final_resp.raise_for_status()
                return final_resp.json()["choices"][0]["message"]["content"]

            return assistant_msg.get("content", "")

if __name__ == "__main__":
    answer = asyncio.run(run_offline_agent("Check local audit logs for failed SSH logins."))
    print(answer)

The orchestrator inspects the local MCP tool registry dynamically, converts each tool schema into the standard function-calling payload accepted by Ollama, executes the requested tool over local stdio, and feeds the structured output back for final synthesis.

Comparing Ollama, llama.cpp, and vLLM for Offline Servers

Selecting an inference runtime for an offline AI server depends on concurrent user load and GPU hardware class. While Ollama excels for single-developer workstations and small LAN teams, high-concurrency internal deployments often migrate to the PagedAttention and continuous batching architecture documented in the vLLM Official Serving Documentation.

Evaluation Dimension Ollama llama.cpp (llama-server) vLLM
Primary Role Workstation CLI & small LAN server Minimal C++ edge & custom GGUF serving High-concurrency enterprise GPU server
Weight Format GGUF via Modelfiles Native GGUF checkpoints SafeTensors, FP8, AWQ, GPTQ
Concurrency Scaling Sequential / low concurrent queues Low to moderate parallel slots High throughput via PagedAttention
Hardware Target Consumer GPUs, Apple Silicon, CPUs CPUs, edge devices, mixed GPUs Multi-GPU NVIDIA / AMD server nodes
Air-Gap Footprint Single static binary + model blob dir Zero-dependency compiled C++ binary Python + CUDA wheel bundle

Choose Ollama when a single engineer or small team needs turnkey GGUF management and OpenAI-compatible tool calling in five minutes. Choose llama-server for minimal attack surface on air-gapped edge boxes, and choose vLLM when 10 or more concurrent users or autonomous agents share a multi-GPU LAN server.

Software Bootstrapping: Sneakernet Dependency Provisioning

Provisioning software onto an air-gapped machine requires a deterministic sneakernet transfer workflow. In regulated environments, security architects compare sneakernet transfers against hardware data diodes; while optical data diodes enforce unidirectional electronic packet flows for continuous ingestion, physical sneakernet media remains the standard for batch-bootstrapping isolated AI workstations.

Teams deciding between automated model daemons and raw C++ binaries during staging should consult our Ollama vs llama.cpp runtime comparison to select the right offline binary footprint. For automated headless pipelines, configure local endpoints according to the Ollama Official API Documentation so scripts target loopback sockets without external DNS lookups.

Staging Python Wheels and Checksum Verification

To install Python packages such as mcp, chromadb, pypdf, and requests without internet access, download pre-compiled binary wheels on an internet-connected staging host matching the target operating system, CPU architecture, and Python minor version.

Execute the following script on the connected staging host to bundle every transitive dependency and generate a cryptographic manifest:

#!/usr/bin/env bash
# Step 1: Execute on internet-connected staging machine
set -euo pipefail

mkdir -p ./offline_ai_bundle/wheels
mkdir -p ./offline_ai_bundle/models

# Download binary wheels for target Linux x86_64 Python 3.12 workstation
python3 -m pip download \
  --dest ./offline_ai_bundle/wheels \
  --only-binary=:all: \
  --platform manylinux_2_28_x86_64 \
  --python-version 312 \
  --implementation cp \
  mcp \
  chromadb \
  pypdf \
  requests

cd ./offline_ai_bundle
sha256sum wheels/*.whl > checksums.sha256
echo "Software staging complete. Transfer offline_ai_bundle via encrypted drive."

Specifying --only-binary=:all: guarantees that pip never attempts to compile C extensions from source tarballs on the air-gapped target host.

After moving the encrypted transfer drive to the isolated machine, validate every wheel against the SHA-256 manifest and install strictly from local disk:

#!/usr/bin/env bash
# Step 2: Execute on isolated air-gapped target workstation
set -euo pipefail

cd /media/secure_drive/offline_ai_bundle

# Verify cryptographic integrity prior to installation
sha256sum -c checksums.sha256

# Install packages with external PyPI index disabled
python3 -m pip install \
  --no-index \
  --find-links=./wheels \
  mcp chromadb pypdf requests

Passing --no-index disables all network index resolution, ensuring the installation either succeeds deterministically from local wheels or fails loudly if a transitive dependency was omitted during staging.

Air-Gapped Model Weight Transfer Protocols

Transferring multi-gigabyte GGUF model checkpoints requires preserving directory manifests and verifying file integrity after physical transport. On Linux, copy the complete ~/.ollama/models blob and manifest tree onto your staging drive and bind OLLAMA_MODELS=/opt/offline_ai/models on the target host.

Always compute and compare SHA-256 hashes of large GGUF files on the air-gapped machine before loading them into VRAM. Silent USB controller write errors can corrupt individual tensor blocks, causing garbage token loops or immediate segmentation faults during model initialization.

Building an Offline RAG System to Chat with Documents Privately

Retrieval-Augmented Generation (RAG) enables offline language models to answer technical queries grounded in internal schematics, compliance manuals, and proprietary repositories. Every stage of an offline RAG pipeline must run locally: document parsing, dense vector embedding, persistent indexing, similarity retrieval, and answer synthesis.

Pipeline Stage Processing Engine Data Transformation Network Egress Status
1. Text Ingestion Local pypdf parser Unstructured PDF to overlapping chunks Zero Sockets (Local File I/O)
2. Dense Embeddings Local nomic-embed-text Text chunks to 768-dim vector embeddings Loopback Only (127.0.0.1)
3. Vector Indexing In-process ChromaDB PersistentClient Embeddings persisted to local SQLite Embedded Process (Zero IPC)
4. Semantic Search Cosine similarity indexing Query vector matched to top-K chunks Local Disk Retrieval
5. Context Synthesis Local phi4:14b or gemma4:12b Context prompt to grounded response Loopback Only (127.0.0.1)

Local Embeddings and Embedded Vector Storage with ChromaDB

Evaluating chromadb vs pgvector for offline architectures highlights a clear operational trade-off. PostgreSQL with pgvector supports multi-node relational workloads, but it requires administering a background database daemon, local authentication roles, and shared memory tuning.

As detailed in the ChromaDB Local Architecture Documentation, ChromaDB’s PersistentClient operates as an embedded SQLite-backed library directly inside the Python process. Pairing ChromaDB with nomic-embed-text produces 768-dimensional dense vectors entirely in local memory without running extra database services.

Context Assembly and Zero-Telemetry Query Synthesis

The Python script below ingests a local PDF manual, indexes overlapping chunks into an embedded ChromaDB store, and synthesizes grounded responses via the loopback Ollama endpoint:

#!/usr/bin/env python3
"""Zero-Network Offline RAG Pipeline for Air-Gapped Workstations."""
import os
import requests
import chromadb
from pypdf import PdfReader

OLLAMA_API_URL = "http://127.0.0.1:11434/api/generate"
EMBED_API_URL = "http://127.0.0.1:11434/api/embeddings"
MODEL_NAME = "phi4:14b"  # High-accuracy 14B reasoning (or "gemma4:12b")
EMBED_MODEL = "nomic-embed-text"
DB_STORAGE_DIR = "/opt/offline_ai/chroma_db"

def extract_text_from_pdf(pdf_path: str, chunk_size: int = 500, overlap: int = 50) -> list[str]:
    """Extract text from local PDF and partition into overlapping segments."""
    if not os.path.exists(pdf_path):
        raise FileNotFoundError(f"Document not found at {pdf_path}")

    reader = PdfReader(pdf_path)
    full_text = "\n".join(page.extract_text() or "" for page in reader.pages)
    words = full_text.split()
    return [
        " ".join(words[i : i + chunk_size])
        for i in range(0, len(words), chunk_size - overlap)
        if words[i : i + chunk_size]
    ]

def get_local_embedding(text: str) -> list[float]:
    """Generate 768-dim dense vector embedding via loopback daemon."""
    response = requests.post(
        EMBED_API_URL,
        json={"model": EMBED_MODEL, "prompt": text},
        timeout=30,
    )
    response.raise_for_status()
    return response.json()["embedding"]

def index_document(pdf_path: str, collection_name: str = "secure_docs") -> None:
    """Index document chunks into embedded persistent SQLite vector store."""
    client = chromadb.PersistentClient(path=DB_STORAGE_DIR)
    collection = client.get_or_create_collection(name=collection_name)

    chunks = extract_text_from_pdf(pdf_path)
    for idx, chunk in enumerate(chunks):
        collection.upsert(
            ids=[f"chunk_{idx}"],
            embeddings=[get_local_embedding(chunk)],
            documents=[chunk],
        )

def query_offline_rag(query_text: str, collection_name: str = "secure_docs") -> str:
    """Retrieve matching chunks and synthesize a grounded answer locally."""
    client = chromadb.PersistentClient(path=DB_STORAGE_DIR)
    collection = client.get_collection(name=collection_name)

    query_vector = get_local_embedding(query_text)
    results = collection.query(query_embeddings=[query_vector], n_results=3)
    retrieved_contexts = "\n---\n".join(results["documents"][0])

    prompt = (
        "Answer strictly using the retrieved context below. "
        "If the context lacks the answer, state that information is unavailable.\n\n"
        f"Context:\n{retrieved_contexts}\n\nUser Question: {query_text}"
    )

    response = requests.post(
        OLLAMA_API_URL,
        json={
            "model": MODEL_NAME,
            "prompt": prompt,
            "stream": False,
            "options": {"temperature": 0.2, "num_ctx": 8192},
        },
        timeout=60,
    )
    response.raise_for_status()
    return response.json()["response"]

Using collection.upsert makes document re-indexing idempotent across sneakernet content updates, while setting temperature: 0.2 minimizes hallucination when synthesizing technical procedures from retrieved chunks.

Portable AI on USB: High-Speed NVMe Storage Architecture

A self-contained portable AI volume lets field engineers and security auditors carry a verified runtime, local vector index, and quantized weights across air-gapped workstations without modifying the host operating system. Teams deploying ultra-compact low-power field appliances can also evaluate our guide to running AI models on Raspberry Pi for single-board edge hardware trade-offs.

Storage Bottlenecks: Portable NVMe SSD vs. Flash Drives

Standard USB thumb drives and microSD cards rely on low-end flash controllers that throttle sustained sequential reads to 30 to 80 MB/s. Loading an 8.5GB Q4_K_M 14B model checkpoint over a standard flash drive takes over two minutes before the first token renders.

Portable NVMe SSDs connected over USB 3.2 Gen 2 (10 Gbps) or USB4 (40 Gbps) sustain sequential read speeds between 1,000 MB/s and 2,800 MB/s. That throughput loads multi-gigabyte model weights into VRAM in under five seconds and keeps SQLite vector index lookups responsive during large document scans.

Portable Environment Configuration and Folder Structure

Organizing the external NVMe drive into isolated subdirectories prevents accidental contamination from host environment variables or pre-installed Python packages. Structure the portable volume using the directory layout below:

Volume Path Purpose Key Contents
/media/portable_ai/bin/ Static runtime binaries ollama binary, portable python3 runtime
/media/portable_ai/models/ Pre-staged GGUF weights phi4-14b-q4_k_m.gguf, gemma4-12b-q4_k_m.gguf, nomic-embed-text
/media/portable_ai/data/ Private knowledge & scripts documents/, chroma_db/, offline_agent.py, local_ops_mcp.py
/media/portable_ai/wheels/ Offline dependency cache Verified .whl files and checksums.sha256 manifest
/media/portable_ai/start_portable_ai.sh Zero-host launch script Sets loopback OLLAMA_HOST, OLLAMA_NO_CLOUD=1, and traps exit

Use the following self-contained launch script to bind the portable daemon strictly to loopback and clean up background processes on exit:

#!/usr/bin/env bash
# start_portable_ai.sh - Self-contained portable execution launcher
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export OLLAMA_MODELS="${SCRIPT_DIR}/models"
export OLLAMA_HOST="127.0.0.1:11434"
export OLLAMA_NO_CLOUD="1"
export PATH="${SCRIPT_DIR}/bin:${PATH}"

"${SCRIPT_DIR}/bin/ollama" serve > /dev/null 2>&1 &
DAEMON_PID=$!
trap 'kill ${DAEMON_PID} 2>/dev/null || true' EXIT

sleep 2
echo "Portable offline AI active on 127.0.0.1:11434."
python3 "${SCRIPT_DIR}/data/offline_agent.py"

Registering an EXIT trap guarantees that closing the terminal immediately terminates the background ollama process so the portable NVMe volume can be unmounted cleanly without open file handles.

Security Hardening, Zero-Egress Verification, and Production Troubleshooting

Physical disconnection provides baseline isolation, but enterprise air-gap deployments require defense-in-depth at the storage, firewall, and packet inspection layers. Encrypt persisted model partitions and vector stores with LUKS2 encryption (using localized TPM keys on headless servers) to protect data at rest against physical drive theft.

Kernel Firewall Lockdown with iptables Default Drop

Single-host air-gapped workstations should invert conventional firewall defaults by dropping all inbound, forwarded, and outbound traffic across physical and wireless interfaces while permitting only loopback (lo) traffic.

Execute the lockdown script below on dedicated standalone air-gapped hosts:

#!/usr/bin/env bash
# Standalone Air-Gap Kernel Firewall Lockdown Script
set -euo pipefail

iptables -F
iptables -X
iptables -t nat -F
iptables -t mangle -F

# Enforce default DROP across every standard netfilter chain
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP

# Permit local IPC strictly across loopback interface
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT

# Log and drop any non-loopback egress attempt
iptables -A OUTPUT -j LOG --log-prefix "EGRESS_VIOLATION_BLOCKED: " --log-level 4
iptables -A OUTPUT -j DROP

# Disable physical NICs and wireless radios at the driver layer
ip link set eth0 down 2>/dev/null || true
ip link set wlan0 down 2>/dev/null || true
rfkill block all 2>/dev/null || true

Combining kernel netfilter rules with ip link set down and rfkill block all prevents misconfigured services from transmitting packets even if a physical Ethernet cable is plugged in accidentally during maintenance.

Continuous Packet Auditing and Automated Intrusion Alarms

Empirical zero-egress verification requires inspecting live kernel packet rings rather than trusting application documentation. As explained in the Linux Kernel Packet MMAP Documentation, kernel ring-buffer packet capture exposes raw network frames directly from kernel memory with minimal overhead.

Deploy the tcpdump monitor below as a background watchdog that logs any non-loopback packet and immediately terminates running inference processes:

#!/usr/bin/env bash
# Zero-Egress Continuous Packet Audit Watchdog
set -euo pipefail

LOG_FILE="/var/log/zero_egress_audit.log"
echo "Starting continuous packet audit at $(date)..." >> "${LOG_FILE}"

tcpdump -i any -n -q -l "not (ip and (src 127.0.0.1 or dst 127.0.0.1))" 2>/dev/null | while read -r line; do
  echo "CRITICAL SECURITY ALERT: Non-loopback packet detected: ${line}" | tee -a "${LOG_FILE}"
  pkill -9 -f "ollama" || true
  pkill -9 -f "python3" || true
  exit 1
done

Because -l forces line-buffered output, tcpdump flushes any anomalous frame immediately to the while loop, triggering the kill switch within milliseconds of a rogue socket attempt.

Production Troubleshooting and Air-Gapped Trade-offs

Offline AI deployments fail in predictable ways when environment flags, protocol streams, or memory ceilings are misconfigured. Use the diagnostic matrix below to resolve the four most common production failures:

Symptom / Error Log Root Cause Verified Resolution
ollama connection refused localhost offline Daemon stopped or bound to wrong interface Run OLLAMA_HOST=127.0.0.1:11434 ollama serve and verify via curl http://127.0.0.1:11434/api/version
Timeouts or fetch failed on model load Client or daemon attempting cloud registry check Export OLLAMA_NO_CLOUD=1 in both server and client environments and confirm tag via ollama list
MCP client drops session with JSON parse error Local MCP stdio server printed logs to stdout Redirect all debug prints to sys.stderr; reserve stdout strictly for JSON-RPC 2.0 frames
Speed drops from 60 TPS to 4 TPS mid-chat KV cache plus weights spilled into DDR5 RAM Enable OLLAMA_FLASH_ATTENTION=1, reduce num_ctx, or step down to Q4_K_M quantization

Even a tuned air-gapped workstation carries clear operational boundaries compared to frontier cloud APIs such as Claude Opus 5.5, GPT-6.2 Astra, and Gemini 4 Carbon. Local systems have no live web search index and rely on internal IT teams to execute sneakernet updates for new weights and security patches.

Architectural Metric Disconnected Air-Gapped AI Cloud Frontier APIs (Nov 2026)
Data Sovereignty 100% On-Premise (Zero Network Egress) External Multi-Tenant Cloud Infrastructure
Marginal Token Cost $0.00 Per Generated Token Variable Per-Million-Token Usage Billing
External Connectivity None Required (Air-Gapped / Isolated LAN) Continuous High-Bandwidth Internet Required
Real-Time Knowledge Bounded to Local Vector Indices & MCP Tools Live Web Search & External SaaS Connectors
Model Capacity Range 2B to 100B+ MoE (Bounded by Local VRAM) Frontier Models (Claude Opus 5.5, GPT-6.2 Astra, Gemini 4 Carbon)
Cost Structure Upfront GPU / Workstation CapEx Zero Upfront Hardware Cost (OpEx)

For ultra-constrained embedded microcontrollers, robotics controllers, and industrial sensors where multi-billion-parameter LLMs exceed thermal and memory envelopes, consult the Google LiteRT On-Device AI Documentation to deploy compact quantized edge models on dedicated NPUs and edge TPUs.

Frequently Asked Questions

Can AI models run completely offline without internet?

Yes, open-weights language models such as Microsoft Phi-4 14B and Google Gemma 4 12B run completely offline once GGUF weights and runtimes are staged on local storage. Local inference engines load quantized weights into GPU VRAM or unified memory and generate tokens with zero external network sockets.

How do you run an AI agent offline with local tools?

An offline AI agent pairs a local tool-calling model served by Ollama or llama.cpp with Model Context Protocol (MCP) servers communicating over stdio transport. The orchestrator spawns local tool scripts as child processes and exchanges JSON-RPC 2.0 messages over stdin and stdout without opening any network ports.

How do you set up an offline AI server on a local network?

Set OLLAMA_HOST=0.0.0.0:11434 and OLLAMA_NO_CLOUD=1 in the systemd service unit so the inference engine serves requests to internal LAN workstations without cloud fallback. Because Ollama lacks built-in authentication, restrict port 11434 to your internal RFC 1918 subnet using iptables and drop all WAN egress.

What hardware is required for an offline AI chatbot?

An offline AI workstation requires a modern multi-core CPU paired with at least a 12GB to 16GB VRAM GPU or an Apple Silicon Mac with 32GB of unified memory. That hardware tier runs Q4_K_M quantized 12B to 14B models at 45 to 75 tokens per second without spilling layers into slower system RAM.

How does an offline AI USB stick work without internet?

An offline AI USB stick stores static inference binaries, cached Python wheels, vector indices, and GGUF model weights on a portable NVMe SSD. Running a local launcher script sets OLLAMA_MODELS and OLLAMA_HOST to loopback so the entire stack boots directly from the drive without modifying the host OS.

How do you verify an offline AI system has zero network leakage?

Enforce an iptables default-DROP policy across INPUT, FORWARD, and OUTPUT chains while permitting only loopback traffic on 127.0.0.1. Run a continuous tcpdump monitor on all interfaces to log non-loopback frames and automatically terminate inference processes if any egress attempt occurs.

Can you build a private document search system offline?

Yes, an offline RAG pipeline combines pypdf text extraction, local nomic-embed-text embeddings, and an embedded ChromaDB PersistentClient backed by SQLite. All vector indexing, cosine similarity retrieval, and answer synthesis execute on local disk and loopback memory with zero external API calls.

build offline ai offline ai ai agent offline offline ai server air gapped ai local mcp local rag offline zero egress ai

Found this helpful? Share it with others.

Raj, Founder, AI Agents Kit at AI Agents Kit

Raj

Founder, AI Agents Kit

Raj is the founder of AI Agents Kit, where he writes hands-on guides on AI agents, agent frameworks, Model Context Protocol (MCP), prompt engineering and developer tooling. He builds and tests the tools he covers and focuses on practical, working examples for developers and teams adopting agentic AI.

AI Agents LLMs Prompt Engineering Python TypeScript