Building a Local LLM Knowledge Base: A Practical Guide to RAG Setup
This guide walks through building a private knowledge base on top of locally deployed large language models. It explains why local inference alone cannot answer questions about internal documents, then breaks the implementation into five layers covering model serving, ingestion configuration, document processing, index storage, and application orchestration. You will find practical details on API configuration across containers, choosing an embedding model, chunking strategies with metadata, hybrid retrieval with reranking, prompt constraints for citations, capacity and operations planning, common pitfalls, and a phased rollout path. The goal is a traceable, low-hallucination knowledge base that keeps data in-house without retraining the model.
1. Why a Knowledge Base Is Still Needed After Local Deployment
Local deployment solves one problem: inference never leaves the internal network. It does not give the model knowledge it never had. A model only carries the general knowledge from its training corpus, so it cannot answer questions about internal documents, product manuals, or ticket records.
A knowledge base converts unstructured material into a searchable structured index and injects relevant context into the prompt at inference time. This expands the model’s knowledge boundary without any second round of training.
This approach is commonly known as Retrieval-Augmented Generation (RAG). Its value comes from three points:
- Knowledge updates only require rebuilding the index, not retraining weights.
- Answers can be traced back to specific document fragments, which helps with auditing.
- Hallucination rates drop significantly because the model is instructed to answer from the provided material.
Local deployment and a knowledge base are two independent concerns. Local deployment protects privacy; the knowledge base delivers domain accuracy. Only the combination forms a complete enterprise solution.
2. Layered Architecture
A solid implementation can be split into five layers:
- Model serving layer: the local inference runtime, exposing OpenAI-style HTTP endpoints for both chat completions and embeddings.
- Configuration layer: register the model provider in the orchestration platform with the internal address, model names, and a placeholder key.
- Document processing layer: handles upload, parsing, cleaning, and splitting to produce chunks.
- Index storage layer: a vector store holds embeddings and metadata, while a relational database holds structured records for documents and segments.
- Orchestration layer: prompt templates, retrieval parameters, reranking, citation display, and the feedback loop.
The benefit of layering is that any layer can be swapped. For example, moving the vector store from a single-node setup to a distributed one requires no changes to the orchestration layer above it.
3. Preparing the Model Service and API Contract
Once the local inference runtime starts, it typically listens on a port such as 11434. If the model runs in one container and the orchestration platform runs in another, localhost will not work. Use the service name in the container network or the host address instead. Example configuration:
# Orchestration platform environment variablesMODEL_BASE_URL=http://ollama:11434MODEL_API_KEY=local-placeholderCHAT_MODEL_NAME=qwen2.5:7bEMBEDDING_MODEL_NAME=bge-m3
Two details must be verified. First, when accessing across containers, the security group or firewall must allow the corresponding port. Second, if all services share one compose network, prefer service names over IP addresses so the address does not drift after a restart.
4. Why the Embedding Model Is Configured Separately
A common reason implementations fail is that only the chat model is configured and the embedding model is not. Retrieval quality is capped by the embedding model, not the generation model. When selecting one, consider:
- Dimensions: commonly 384, 768, or 1024. Higher dimensions mean stronger expressiveness but more storage and retrieval cost.
- Maximum input length: this determines how much text a single chunk can hold. Anything beyond the limit is truncated, causing semantic loss.
- Mixed Chinese-English capability: enterprise documents often mix both languages, so a multilingual-friendly model is needed.
- Normalization and similarity metric: most models require cosine similarity, and this must match the vector store configuration.
5. Document Parsing and Chunking Strategy
Chunking is the first dividing line for knowledge base quality. Chunks that are too large reduce retrieval precision and waste context; chunks that are too small break semantics apart. The following rules work well:
- Split by structure first, using heading levels, clause numbers, and table boundaries as natural separators.
- Set chunk size between 300 and 800 characters with 10% to 20% overlap to keep semantics continuous across chunks.
- Attach metadata to every chunk: source file, section path, effective date, and permission labels.
- Use a separate parsing path for tables and code blocks so ordinary tokenization does not break them apart.
Example pseudocode:
def split_document(text, size=500, overlap=80):chunks, start = [], 0while start < len(text):end = start + sizechunks.append({"text": text[start:end],"meta": {"start": start, "end": end}})start = end - overlapreturn chunks
6. Retrieval and Reranking in Practice
Vector-only retrieval tends to return fragments that look similar but do not answer the question. The recommended approach is hybrid retrieval: vector recall handles semantic similarity, keyword recall handles exact matches for proper nouns, IDs, and model numbers, and a fusion ranking step merges the results.
After recall, add a reranking model to score the top 20 to 50 candidates and inject only the top 3 to 5 into the prompt. Suggested retrieval parameters: start the similarity threshold at 0.6 to 0.7 and watch the recall rate, start topK at 4 and raise it gradually, and add a prompt constraint that instructs the model to say it does not know when nothing relevant is found, which suppresses fabrication.
7. Prompts and Citation Traceability
The prompt should explicitly constrain model behavior, for example:
Answer only from the [References] provided; if the material is insufficient, state that no supporting evidence was found.Mark citation numbers [1][2] at the end of the answer.
Citation display is what determines whether a private knowledge base is accepted by the business. Users need to click a source and land on the original text before they trust the answer. The file path and section in the metadata must therefore be written into the index in full.
8. Capacity, Performance, and Operations
- Resource estimation: a quantized 7B-class model takes roughly 5 to 8 GB of VRAM, and the embedding model needs another 1 to 2 GB.
- Concurrency control: local inference has limited concurrency, so set request queuing and timeouts to keep long document parsing from blocking interaction.
- Incremental updates: when a document changes, rebuild the index only for affected segments, and use version numbers to support a gradual switch.
- Observability: connect log services and monitoring alerts, and track time to first token, retrieval hit rate, and the no-answer rate.
- Backup: take regular snapshots of the vector store and relational database, and configure object storage for off-site retention.
9. Common Pitfalls
The first is loading every document at once without filtering by permission, which leads to out-of-scope answers. The second is ignoring document freshness, so an expired policy gets cited as a current rule. The third is doing vector retrieval only with no keyword fallback, which makes model-number queries nearly useless. The fourth is not validating chunks after splitting, so broken tables are only discovered after launch.
Before going live, build an evaluation set of 50 to 100 question-answer pairs and measure recall accuracy and answer correctness as a baseline for iteration.
10. Suggested Rollout Path
In the first phase, run the full pipeline with a small single-node model and validate document parsing and chunking quality. In the second phase, introduce hybrid retrieval and reranking, and build the evaluation set. In the third phase, add permission isolation, incremental indexing, and monitoring alerts to form a knowledge base that can be operated sustainably.
If the enterprise already uses relevant Baidu AI Cloud products, local inference can be combined with cloud capabilities such as object storage, log services, and monitoring alerts, balancing data sovereignty with operational efficiency.
