Creating a completely offline, local, state-of-the-art RAG system for an M1 MacBook with 32GB RAM involves building from the ground up using modern tools and frameworks optimized for Apple Silicon (ARM64), while ensuring no external dependencies or cloud services are used.
We'll break this into parts:
🧠 System Overview
| Component | Tool/Model |
|---|
| Document Parsing | pypdf, unstructured, markdownify |
| Embedding Model | BAAI/bge-m3 (or nomic-embed-text) |
| Vector Store | faiss-cpu (M1 optimized) |
| LLM (RAG Response) | mlx-community/Mistral-7B-v0.1 (Apple MLX) |
| UI | Streamlit + SQLite for chat memory |
| Packaging | Docker (with ARM64 support) or conda-pack |
✅ Features
- Fully offline: no internet access needed
- Runs locally on M1 Mac with 32 GB RAM
- Custom RAG pipeline (no LangChain or LlamaIndex)
- Memory of chat history (SQLite backend)
- Modern models optimized for M1
- Simple packaging for portability
📁 File Structure
offline_rag/
├── data/
│ └── docs/ # Place your PDFs, markdown here
├── db/
│ └── vectorstore.faiss # FAISS index
│ └── chat.db # SQLite chat history
├── models/
│ └── mistral-7b/ # Converted Mistral-7B model in GGUF or MLX format
├── rag_pipeline.py # Core RAG logic
├── ui.py # Streamlit frontend
├── requirements.txt # Python dependencies
└── Dockerfile # Optional: containerization
🛠️ Step-by-Step Implementation
1. Install Dependencies (Python)
Create a virtual environment and install:
python3 -m venv venv
source venv/bin/activate
pip install torch numpy faiss-cpu sentence-transformers pypdf unstructured streamlit sqlite3
For Apple Silicon, use versions compatible with arm64. Use pip install --pre faiss-cpu to get the nightly build.
2. Document Ingestion Pipeline (rag_pipeline.py)
import os
import PyPDF2
from unstructured.partition.auto import partition
from sentence_transformers import SentenceTransformer
import faiss
import numpy as np
import pickle
class OfflineRAG:
def __init__(self, doc_folder="data/docs", index_file="db/vectorstore.faiss", text_file="db/text_chunks.pkl"):
self.doc_folder = doc_folder
self.index_file = index_file
self.text_file = text_file
self.model = SentenceTransformer('BAAI/bge-m3') # Works well offline after download
self.texts = []
self.index = None
def parse_documents(self):
for filename in os.listdir(self.doc_folder):
path = os.path.join(self.doc_folder, filename)
if filename.endswith(".pdf"):
with open(path, "rb") as f:
reader = PyPDF2.PdfReader(f)
for page in reader.pages:
self.texts.append(page.extract_text())
elif filename.endswith(".md") or filename.endswith(".txt"):
with open(path, "r") as f:
self.texts.append(f.read())
else:
# Try generic parser
elements = partition(filename=path)
self.texts.append("\n".join(str(e) for e in elements))
def build_index(self):
embeddings = self.model.encode(self.texts, show_progress_bar=True)
dimension = embeddings.shape[1]
self.index = faiss.IndexFlatL2(dimension)
self.index.add(embeddings)
# Save index and texts
faiss.write_index(self.index, self.index_file)
with open(self.text_file, "wb") as f:
pickle.dump(self.texts, f)
def load_index(self):
self.index = faiss.read_index(self.index_file)
with open(self.text_file, "rb") as f:
self.texts = pickle.load(f)
def query(self, question, top_k=5):
q_emb = self.model.encode([question])
D, I = self.index.search(q_emb, top_k)
results = [self.texts[i] for i in I[0]]
return results
3. Chat History Management (chat_history.py)
import sqlite3
import time
def init_db():
conn = sqlite3.connect("db/chat.db")
c = conn.cursor()
c.execute("""
CREATE TABLE IF NOT EXISTS chats (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp REAL,
user TEXT,
assistant TEXT
)
""")
conn.commit()
conn.close()
def save_message(user, assistant):
conn = sqlite3.connect("db/chat.db")
c = conn.cursor()
c.execute("INSERT INTO chats (timestamp, user, assistant) VALUES (?, ?, ?)",
(time.time(), user, assistant))
conn.commit()
conn.close()
def get_history():
conn = sqlite3.connect("db/chat.db")
c = conn.cursor()
c.execute("SELECT user, assistant FROM chats ORDER BY id DESC LIMIT 10")
rows = c.fetchall()
conn.close()
return rows[::-1] # Show oldest first
4. Local LLM Inference (llm.py)
Use MLX framework for Mistral-7B inference on M1:
from mlx_lm import load, generate
class LocalLLM:
def __init__(self, model_path="models/mistral-7b"):
self.model, self.tokenizer = load(model_path)
def respond(self, prompt, max_tokens=200):
response = generate(self.model, self.tokenizer, prompt=prompt, max_tokens=max_tokens)
return response
Download and convert a GGUF version of Mistral-7B (e.g., via TheBloke) and place it under models/mistral-7b.
Install MLX and MLX LM:
pip install mlx mlx-lm
5. Streamlit UI (ui.py)
import streamlit as st
from rag_pipeline import OfflineRAG
from llm import LocalLLM
from chat_history import init_db, save_message, get_history
# Initialize components
@st.cache_resource
def load_components():
rag = OfflineRAG()
try:
rag.load_index()
except:
rag.parse_documents()
rag.build_index()
llm = LocalLLM()
return rag, llm
rag, llm = load_components()
# UI Setup
st.title("🧠 Offline RAG Assistant")
init_db()
for user, bot in get_history():
with st.chat_message("user"):
st.markdown(user)
with st.chat_message("assistant"):
st.markdown(bot)
if prompt := st.chat_input("Ask something about your documents"):
with st.chat_message("user"):
st.markdown(prompt)
contexts = rag.query(prompt)
context_str = "\n\n".join(contexts[:3])
full_prompt = f"""
You are an AI assistant answering questions based on provided context.
Answer the following question using only the context below:
Context:
{context_str}
Question:
{prompt}
Answer:
"""
with st.chat_message("assistant"):
response = llm.respond(full_prompt)
st.markdown(response)
save_message(prompt, response)
📦 Packaging & Deployment
Option A: Docker Container (ARM64)
FROM ghcr.io/ml-explore/mlx:latest
WORKDIR /app
COPY . /app
RUN pip install -r requirements.txt
CMD ["streamlit", "run", "ui.py"]
Build and run:
docker build --platform linux/arm64 -t offline_rag .
docker run --platform linux/arm64 -p 8501:8501 offline_rag
Option B: Conda Pack
Use conda-pack to bundle everything:
conda create -n offline_rag python=3.10
conda activate offline_rag
pip install -r requirements.txt
conda pack -o offline_rag_env.tar.gz
Then extract and run on another machine:
mkdir -p env && tar -xzf offline_rag_env.tar.gz -C env
source env/bin/activate
streamlit run ui.py
🔒 Notes
- Models should be pre-downloaded and placed in the correct directories before going offline.
- Ensure all dependencies are vendored or cached.
- You can add document upload functionality dynamically by extending the
parse_documents() method.
🚀 Final Thoughts
This system is fully offline, runs on M1 hardware efficiently, and uses best-in-class tools:
- FAISS for fast similarity search
- Sentence Transformers (bge-m3) for high-quality embeddings
- MLX for efficient LLM inference on Apple Silicon
- Streamlit for easy UI prototyping
- SQLite for persistent chat history
Let me know if you'd like a downloadable zip or GitHub repo template!