Given that a government wants to build an AI assistant over highly sensitive internal documents, and because it is highly sensitive, those documents are strictly prohibited sending to outside, either American or Chinese AI services. How would you build it ?
This is where we can no longer rely on ready-to-use AI services and actually learn how to build our own. LLM models cost too much to build, so training a new one from scratch is not an option (see the cost at AI Energy Consumption: The Hidden Cost Behind Artificial Intelligence). Fortunately, the AI landscape has changed significantly with the emergence of open-weight models. Instead of training a foundation model ourselves, we can download an existing model, run it on our own infrastructure, and build applications around it. Llama is one such family of open-weight models. By running Llama locally, we can have the core language model operate inside our own environment without sending prompts or sensitive documents to an external AI provider.
But there is still a problem: A locally running Llama model does not automatically know anything about the government’s internal documents. We could not expect the model to answer questions about a confidential policy that was never part of its training data. We therefore need a way to connect the LLM to our own private knowledge without retraining the model. This is where a Private Retrieval-Augmented Generation (RAG) comes in.
1. What is a Private RAG System ?
1.1 What is RAG ?
RAG, or Retrieval-Augmented Generation, is an architecture that allows a Large Language Model (LLM) to retrieve relevant information from an external knowledge source before generating an answer. Instead of expecting the LLM to know everything, we give it access to a knowledge base that contains the information it needs.
A conventional LLM relies primarily on the knowledge encoded in its model parameters during training. If the information does not exist in its training data, the model may be unable to answer the question correctly or may generate a plausible but incorrect answer. RAG changes this process by introducing a retrieval step: The system first searches a knowledge base for information related to the user’s question, then adds this information to the prompt sent to the LLM. The LLM then can use this context to generate the final response.
1.1 What make a RAG private ?
RAG itself does not necessarily mean that a system is private. A RAG application can still send documents to a cloud-based vector database or send retrieved content to an external LLM. A Private RAG System is different because the entire knowledge pipeline is kept under the organization’s control. The documents must be processed locally. Their embeddings must be generated locally. The vector database must run locally. The LLM must run locally. Even the retrieval process must remain entirely inside the organization’s infrastructure. Nothing is sent to outside.
2. What is Local Llama ?
2.1. What is Llama ?
We are probably already familiar with ChatGPT, Gemini, Claude, and many other AI assistants. Behind these applications is a Large Language Model (LLM) that processes our prompts and generates responses – the one that cost billions to train (to know how a LLM is trained, read “Attention is all you need” – Paper Explained) . Llama is another family of LLMs, trained by Meta. The key difference is that, instead of relying on a hosted AI service, we can download this open-weight Llama model and run it on our own computer or server. This makes Llama a practical choice when we need an AI system that can operate within our own environment and keep sensitive data under our control.
2.2. How to deploy Local Llama ?
The easiest way to run Llama locally is to use Ollama. Ollama provides a simple runtime for downloading, running, and communicating with local LLMs.
Step 1. Install Ollama
First, download and install Ollama for your operating system. After installation, verify that Ollama is available from the terminal:
ollama --version
If the installation is successful, the command will return the installed Ollama version.
Step 2. Download a Llama Model
Use the following command to download Llama:
ollama pull llama3.2
Ollama will download the model files to the local machine. You can check the models currently installed with:
ollama list
You should see llama3.2 in the list.
Step 3. Run Llama Locally
Start the model with:
ollama run llama3.2
Ollama will start Llama locally and open an interactive terminal session. For example:
>>> What is a firewall?A firewall is a security mechanism that...
At this point, the LLM is running locally. The prompt and response are processed by the local model rather than being sent to an external AI service.
Step 4. Verify the Local API
Ollama also provides a local HTTP API that applications can use to communicate with the model. By default, the API is available at: http://localhost:11434 . We can test it with curl:
curl http://localhost:11434/api/generate \ -d '{ "model": "llama3.2", "prompt": "What is a firewall?", "stream": false }'
If everything is working correctly, Ollama will return a JSON response containing Llama’s answer.
Step 5. Understand the Local Architecture
At this point, we have the first component of our Private RAG system. The system we are going to build would look like so:
┌──────────────────────┐│ Our Application │└──────────┬───────────┘ │ │ HTTP ▼┌──────────────────────┐│ Ollama ││ localhost:11434 │└──────────┬───────────┘ │ ▼┌──────────────────────┐│ Llama 3.2 Model ││ Running Locally │└──────────────────────┘
3. How to build a Private RAG System ?
3.1 Understand the LLM
Before diving into the step-by-step process of building a Private RAG System, it is important to understand what an LLM, in our case Llama, actually does.
An LLM does not automatically know or understand our private documents. It only learns linguistic patterns and relationships between words and concepts, enabling it to interpret context and generate relevant responses. In a simplified view, we rely on the LLM to identify relationships within the supplied text and use that information to answer questions.
This is somewhat similar to querying a SQL database. With SQL, we write structured queries to retrieve specific information from stored data. With an LLM, we use prompts expressed in natural language to guide the model toward the information we need and ask it to formulate an answer. The key difference is that a SQL database executes queries against structured data, whereas an LLM interprets the supplied context and generates a response based on its learned language capabilities.
But does this mean an LLM understands language like a human? The answer is No. We need to distinguish functional language understanding from human understanding. Below is the comparison:
| Capability | LLM | Human |
|---|---|---|
| Recognize linguistic patterns | Learns patterns from training data | Learns through language exposure and experience |
| Interpret context | Can infer relationships between words and passages | Uses language, experience, and situational awareness |
| Answer questions using supplied information | Generates responses based on context and learned capabilities | Combines information with knowledge and reasoning |
| Connect concepts | Identifies statistical and semantic relationships | Connects concepts through learned knowledge and lived experience |
| Learn new information during a conversation | Can use information in the current context without updating model weights | Can incorporate information into memory and learning |
| Verify factual accuracy | Can produce incorrect or fabricated answers | Can also make mistakes, but can use real-world observation and verification |
| Understand the physical world | Can reason about descriptions and representations of the world, with limitations | Can experience and interact with the physical world directly |
| Explain its reasoning | Can generate explanations, which may not fully reflect its internal computation | Can explain some of its reasoning, although introspection is also imperfect |
An LLM can demonstrate sophisticated language understanding, but its ability to generate convincing responses does not prove that it understands the world in the same way a human does. It can also misinterpret context, overlook a qualification, or generate unsupported claims. (read more at: AI Overuse: Risks, Consequences, and How To Avoid AI Dependency )
3.2. Document Processing
Assuming that our sensitive documents are PDF files only. The LLM itself does not know how to read a PDF file. We need to convert PDF files to a text-only format so that Llama can understand. This step is purely a traditional programming task. Some popular approaches include:
pypdf— A lightweight Python library for extracting text from text-based PDF files. It is easy to install, runs locally, and is a good starting point for our Private RAG implementation.PyMuPDF(fitz) — A Python library that provides text extraction and access to PDF page content, including layout and positional information. It is useful when we need more control over how text is extracted and organized.pdfplumber— A Python library focused on extracting text and tables from PDFs. It is particularly useful when the document layout or tabular data matters.- OCR (Optical Character Recognition) — If a PDF contains scanned pages or images instead of actual text, ordinary text extraction may return little or nothing. An OCR engine can recognize characters in those images and convert them into machine-readable text.
For testing purposes, assuming that these are highly sensitive documents, you can download them and test locally or create your own fictional ones:
3.3. Store Processed Documents
Recall that our goal is to provide the LLM with relevant context by including it in the prompt. To achieve this, we need a mechanism to retrieve relevant document passages based on a user’s query. This is essentially an information retrieval problem, similar to those encountered in traditional database and search systems.
Unlike SQL’s LIKE operator, which primarily matches text against a specified pattern, we want to identify semantic similarity rather than rely solely on exact keyword matching. This is where a vector database comes in. FAISS is a popular option for this purpose.
Instead of searching directly through raw text, we convert each text chunk into a numerical vector using an embedding model. FAISS then allows us to search for vectors that are similar to the vector representing a user’s query, helping us retrieve relevant passages even when they use different words to express similar ideas.
Besides FAISS, several alternatives can be used for vector search in a Private RAG System. The best choice depends on whether you need a lightweight local library or a full database service.
| Alternative | Type | Key advantages | Best use case |
|---|---|---|---|
| Chroma | Vector database | Simple Python API, easy setup, persistence | Beginner-friendly local RAG projects |
| Qdrant | Vector database | Metadata filtering, efficient similarity search, supports local deployment | Production RAG systems |
| LanceDB | Embedded vector database | Serverless design, local storage, works well with data-oriented workflows | Local applications and prototypes |
| Milvus | Vector database | Scalable architecture and large-scale vector search | Large document collections |
| Weaviate | Vector database | Rich search features, metadata filtering, hybrid search | More advanced retrieval systems |
| Annoy | Search library | Lightweight approximate nearest-neighbor search | Read-heavy applications with relatively static indexes |
| PostgreSQL + pgvector | Database extension | Combines vector search, SQL, metadata, and existing relational data | Applications already using PostgreSQL |
3.4. Search for Relevant Documents
This step is, again, a traditional programming challenge, similar to querying a database. Assuming we have already built our vector database in the previous step, our next task is to retrieve relevant document passages based on the user’s query.
Imagine a fictional citizen living in the world described by our fictional, restricted government document. While traveling near their settlement, they spot a strange spacecraft and submit the following prompt:
"How do I report a strange spacecraft I spotted near my settlement, and which government department should I contact to have it investigated?"
Should we simply send this prompt directly to the LLM? Not yet.
Before generating an answer, we need to use the user’s prompt to search the vector database, retrieve the most relevant passages, and include them as context in the prompt sent to the LLM.
To determine what information to retrieve from the user’s query, we can follow these steps:
- Receive the user’s query. Capture the question or prompt submitted by the user.
- Generate an embedding. Use the same embedding model that we used to index our documents to convert the user’s query into a numerical vector.
- Search the vector database. Compare the query vector against the stored document vectors to identify the most semantically similar passages.
- Rank and select relevant passages. Retrieve the top-K results, optionally applying a similarity threshold or metadata filters to exclude irrelevant documents.
- Build the final prompt. Combine the original question with the retrieved passages to provide the LLM with relevant context.
- Generate the answer. Send the augmented prompt to the local Llama model and let it generate a response based on the supplied context.
Notice that we do not necessarily need to extract individual keywords from the user’s prompt. Unlike traditional keyword-based search, embedding-based retrieval represents the meaning of the entire query as a vector, allowing us to find relevant passages even when they use different words. The embedding model used for the query must match the one used to index the documents. Otherwise, their vectors may not be comparable in the intended way.
3.5. Prompt Engineering
At this point, the LLM can finally play its role. Using the relevant passages retrieved in the previous step, we can construct an augmented prompt by combining these passages into a single context section, followed by the user’s question. We instruct the LLM to use this context to answer the question, much like how we normally interact with ChatGPT, Gemini, or other AI services.
The key difference is that, instead of relying solely on the model’s pre-trained knowledge, we provide relevant information retrieved from our private document collection to help it generate a more accurate and context-aware response. For example, with some programming, we can construct the augmented prompt like this:
## System InstructionsYou are an AI assistant for citizens of the United Martian Government. Answer questions using the provided context from official government documents.Follow these rules:* Base your answer on the supplied context.* You may make reasonable, clearly identified suggestions, but do not present unsupported information as official policy.* If the context does not specify a procedure, contact channel, or responsible authority, explicitly acknowledge that limitation.* Do not invent emergency telephone numbers, reporting portals, or government procedures.## ContextThe following passages were retrieved from the government's restricted infrastructure registry.**Passage 1 — Facility M-001: Ares Central Defense Command*** Location: Ares Administrative District, near the Ares City settlement.* Classification: Official planetary defense headquarters.* Primary function: Strategic administration, inter-settlement coordination, and defense policy.* Administrative authority: Office of the Martian Defense Commissioner.* Public status: Officially acknowledged.**Passage 2 — Facility S-12: Meridian Deep Shelter*** Location: Meridian Subsurface District, within a underground settlement network.* Registered civilian purpose: Emergency shelter engineering and life-support research.* Internal classification: Restricted civil-defense infrastructure.* Administrative authority: Martian Civil Protection Agency.* Public status: Listed as a government emergency preparedness project.* Restricted role: Long-duration shelter readiness, backup life-support coordination, and emergency resource management.**Passage 3 — Administrative Relationships*** The Office of the Martian Defense Commissioner supervises Ares Central Defense Command.* The Martian Civil Protection Agency jointly manages Meridian Deep Shelter.* The document does not define a dedicated procedure for reporting unidentified spacecraft.## User QuestionHow do I report a strange spacecraft I spotted near my settlement, and which government department should I contact to have it investigated?## Instructions for Generating the AnswerUse the retrieved passages to identify potentially relevant government authorities. Distinguish between their documented responsibilities and any suggested next steps. If the documents do not specify an official reporting channel, explain that limitation rather than inventing one.
Then we can send this prompt to our local Llama model and expect it to answer like this:
If you spot an unidentified spacecraft near your settlement, you can contact Ares Central Defense Command (Facility M-001), the main headquarters responsible for planetary defense administration and coordination across Martian settlements.You may also contact the Martian Civil Protection Agency, which oversees emergency preparedness and civil protection infrastructure.
4. Next Steps
In the upcoming posts, we will dive deeper into Ollama to understand how an inference engine works and how to evaluate an LLM system before deploying it to production. Please subscribe to stay tuned for the next articles and continue exploring the engineering behind LLMs with the-tech-lead.com.
Continue at:
- LLM Inference Engine (chapter 1): Transformer Architecture From Scratch – GGUF Format
- LLM Inference Engine (chapter 2): Transformer Architecture From Scratch – Tokenization
- LLM Inference Engine (chapter 3): Transformer Architecture From Scratch – Token Embedding
- LLM Inference Engine (chapter 4): Transformer Architecture From Scratch – Attention Scores
- LLM Inference Engine (chapter 5): Transformer Architecture From Scratch – Feed Forward Sub-Layer
- LLM Inference Engine (chapter 6): Transformer Architecture From Scratch – Next Token Prediction

2 thoughts on “Build a Private RAG System with Local Llama”