Building a Private RAG System: From Model Inference to Document Parsing
This article walks through how to build an on-premises RAG (Retrieval-Augmented Generation) system, covering the five-layer architecture, containerized inference deployment, document parsing and chunking, retrieval orchestration and tuning, and governance. It also includes common troubleshooting points and a phased rollout plan to help teams deliver a stable, auditable private knowledge Q&A foundation.
1. Why Private RAG Has Become a Must-Have
As the open-source ecosystem for large-parameter inference models matures quickly, enterprises increasingly want to “keep models in their own data centers.” Data staying inside the internal network, auditability, and offline operation are hard constraints shared across finance, manufacturing, healthcare, and government. RAG (Retrieval-Augmented Generation) has become the mainstream deployment pattern for three reasons:
- Knowledge stays up to date: Model parameters are fixed, while enterprise documents change daily. The retrieval layer decouples knowledge updates from the model.
- Answers are traceable: Responses come with cited snippets, making manual review easy and reducing the business risk of confident-sounding fabrication.
- Cost is controllable: Compared with continuous fine-tuning, the marginal cost of vector retrieval is extremely low, and switching models does not require rebuilding the knowledge base.
It is worth stressing that the quality ceiling of RAG is often determined not by the generation model but by the “document parsing + chunking + retrieval” stage. In engineering practice, the root cause of many failures lies on the retrieval side, not the generation side.
2. Layered Architecture Overview
An operable private RAG system is typically divided into five layers:
- Inference layer: Deploys the large language model, embedding model, and rerank model, exposing standard interfaces.
- Parsing layer: Converts PDFs, Word documents, scanned files, tables, and slides into structured text while preserving heading hierarchy and layout information.
- Indexing layer: Chunks, vectorizes, and writes to the vector store, while retaining source-position metadata for citation lookup.
- Orchestration layer: Handles query rewriting, multi-path retrieval, reranking, prompt assembly, generation calls, and citation organization.
- Governance layer: Permission filtering, log auditing, monitoring and alerting, quotas, and rate limiting.
3. Inference Layer: A Common Approach to Containerized Deployment
Containerizing model serving is currently the least effort-intensive option—one command brings the service up—but the pitfalls are concentrated here too. Taking an open-source model inference platform as an example, a typical startup form looks like this (illustrative; refer to the documentation for your specific version for exact parameters):
docker run -d --name inference-serving \-p 9997:9997 \-e INFERENCE_HOME=/data \-v $(pwd):/data \--gpus all \<image-name>:<version-tag> \serving-local -H 0.0.0.0
Parameter meanings: -d runs in the background; -p maps the service port; -e specifies the data home directory; -v mounts the current directory to persist model files; --gpus all exposes all GPUs; -H 0.0.0.0 allows external access.
Common pitfalls and the order in which to troubleshoot them:
- Slow or interrupted model downloads: First switch the model source to a mirror, and cache within the mounted directory for reuse, so you avoid re-pulling tens of GB of weights after the container is rebuilt.
- Insufficient GPU memory: First confirm the quantization precision and context length settings, then consider tensor parallelism; do not blindly add GPUs.
- Ports and firewall: The container listens on 0.0.0.0 but the host does not allow the port through—this is the most common “page won’t open” issue.
- Permissions and data persistence: Mismatched ownership of the mounted directory causes log write failures; unify the UID/GID.
- Version drift: Using the
latesttag makes reproduction difficult; always pin the version number in production.
The inference layer should deploy three types of models: a generation model, an embedding model, and a rerank model. The rerank model has a small parameter count and delivers clear benefits—it is the most cost-effective way to lift retrieval hit rate by a level. Its deployment is the same as the other two; just note that its input is a “query-document pair” and its output is a relevance score.
4. Parsing Layer: The Key That Sets the RAG Ceiling
Deep document understanding is the dividing line between RAG and “simple vector retrieval.” Engineering challenges include:
- Layout restoration: Multi-column layouts, headers and footers, and cross-page paragraphs will cause semantic breaks if split as a plain text stream.
- Table structuring: Tables must be converted into a searchable structured representation; otherwise, numeric Q&A will almost certainly be wrong.
- Scanned document OCR: This requires chaining layout analysis with text recognition, while preserving coordinates so content can be traced back to the source.
- Chunking strategy: Recursive splitting by heading hierarchy is better than fixed-length splitting. Combine block size with an overlap window, and attach “document name + section path + page number” metadata to each chunk.
A minimal working chunking example:
def split_by_heading(sections, max_tokens=512, overlap=64):chunks = []for sec in sections:buf = sec.textwhile len(buf) > max_tokens:chunks.append({"text": buf[:max_tokens],"meta": {**sec.meta, "heading": sec.title}})buf = buf[max_tokens - overlap:]if buf:chunks.append({"text": buf, "meta": {**sec.meta, "heading": sec.title}})return chunks
5. Orchestration and Retrieval Tuning
The recommended pipeline is “query rewriting → hybrid retrieval → reranking → generation → citation”:
- Query rewriting: Generate standalone queries using multi-turn conversation history, and split them into multiple sub-questions for parallel retrieval when necessary.
- Hybrid retrieval: Vector retrieval handles semantic similarity, while keyword retrieval handles proper nouns, IDs, and model numbers; fuse the results of both.
- Reranking: Fine-rank the top several dozen candidates after fusion, and send only the top 3–5 to generation.
- Generation constraints: The prompt should explicitly require “answer only based on the given snippets, and say you don’t know when there is no basis,” and require citation numbers in the output.
- Citation backfilling: Use metadata to map numbers back to documents and page numbers, forming clickable traceability.
Evaluation cannot be skipped. Build an evaluation set of 50–200 real business Q&A pairs, and measure retrieval hit rate and answer accuracy separately. Fix retrieval first, then tune prompts, to avoid misdiagnosing a retrieval problem as a model problem.
6. Governance: Permissions, Auditing, and Cost
In enterprise scenarios, permissions must take effect at the retrieval layer—filter documents by the user’s visible scope first, then perform vector retrieval. Never “retrieve first and filter afterward.” On the logging side, record queries, hit snippets, and cited documents to form an auditable trail. On the monitoring side, track time-to-first-token, throughput, GPU memory usage, and empty-retrieval rate, and configure alerts. If you use cloud resources, common capabilities such as container platforms, object storage, log services, and monitoring and alerting can significantly reduce the burden of self-built operations. Object storage is suitable for model weights and raw documents, while log services are suitable for carrying audit data.
7. Recommended Rollout Pace
In the first phase, use a single-machine container to get “inference + vector store + basic Q&A” working end to end. In the second phase, add deep parsing and reranking, and build an evaluation set. In the third phase, add multiple replicas, permission governance, and canary releases. Following this pace, you can typically obtain a stable, scalable, and traceable private knowledge Q&A foundation within a few weeks.
