Building a Private RAG System: From Model Inference to Document Parsing

    This article walks through how to build a private, on-premises RAG system as a coordinated pipeline rather than a set of isolated components. It covers a unified model inference layer for LLMs, embedding, multimodal, and rerank models; document parsing and index construction with layout analysis, semantic chunking, and metadata tagging; hybrid retrieval with reranking and tightly constrained generation prompts; and the containerized deployment practices that prevent common failures, including cache persistence, resource planning, health checks, observability, and version pinning.

    1. Why Private RAG Has Become a Business Requirement

    Once large models proved their capabilities, enterprise attention shifted quickly from “how good are the results” to “how do we run this inside our own environment.” Three constraints drive many scenarios toward a private deployment: data must stay inside the internal network, access must be auditable, and per-call cost must be predictable.

    RAG (Retrieval-Augmented Generation) became the mainstream choice for a straightforward reason. It uses an external knowledge base to cover the gaps in a model’s parametric knowledge, turning a “memory problem” into a “retrieval problem,” and it naturally provides citation traceability, which significantly reduces the business risk caused by hallucination.

    A complete private RAG system is essentially a pipeline. The inference service layer hosts the large language model, the embedding model, and the rerank model. The index construction layer handles document parsing, chunking, and vectorization. The retrieval layer handles recall and ranking. The application orchestration layer handles prompt assembly, session management, and result citation. The deployment pain that comes up again and again has a single root cause: every layer in this chain carries its own environment dependencies, and all of them must coexist as containers on the same machine.

    2. Layer One: A Unified Model Inference Service

    The traditional approach builds a separate service for each model, with ports, dependencies, and GPU memory usage all managed independently. A more workable approach introduces a unified inference abstraction layer that registers the large language model, the embedding model, multimodal models, and the rerank model as service endpoints callable through a standard protocol. This yields three direct benefits:

    • Consolidated interfaces: applications target a single calling protocol, so switching models requires no changes to business code;
    • Resource reuse: one process pool manages multiple models, allowing unified tuning of GPU memory allocation and batching strategy;
    • Elastic scaling: stateless endpoints scale horizontally and integrate easily with a load balancer.

    When starting the container, you must explicitly declare GPU device passthrough, port mapping, the model cache directory mount, and the listening address. The most common pitfall here is failing to persist the model cache directory: after the container is rebuilt, every model is downloaded again, and pulling several GB to tens of GB of weights repeatedly is both slow and prone to failure when the network fluctuates. Mapping the cache directory to the host machine or external storage is the first step that has to be done right.

    For model sources, domestic mirror repositories are the better first choice, with noticeably better download stability than a direct cross-ocean connection. The selection principles for the embedding and rerank models are also clear. The embedding model sets the ceiling on recall, so prioritize Chinese semantic matching performance and weigh vector dimensionality against storage cost. The rerank model determines final accuracy; a lightweight cross-encoder is the usual choice, scoring the recalled results a second time and trading millisecond-level latency for a clear improvement in ranking quality.

    3. Layer Two: Document Parsing and Index Construction

    Eighty percent of RAG quality is determined by data quality. Real enterprise documents are a mix of PDFs, scans, tables, PPT decks, and rich text. Splitting them by a fixed character count shreds the semantics. The more reliable engineering path is:

    1. Format detection and layout analysis: distinguish headings, body text, headers and footers, tables, and image regions;
    2. Structure restoration: convert tables into searchable structured text, and hand images to a multimodal model to generate descriptions;
    3. Semantic chunking: split primarily along heading hierarchy and paragraph boundaries, control chunk length, and keep an overlap window;
    4. Metadata tagging: record the source file, section path, page number, and last-updated time to support filtering and citation;
    5. Vectorization and indexing: write to the vector store in batches while retaining a mapping back to the original text positions.

    Metadata is a key design decision that many teams overlook. Without it, you cannot filter for “only this product family’s documents” or “exclude archived versions,” and you cannot give page-precise citations after an answer.

    4. Layer Three: Retrieval, Reranking, and Generation Orchestration

    A hybrid strategy is recommended for retrieval: vector search handles semantic similarity, keyword search handles exact matches on proper nouns, model numbers, and identifiers, and the two result sets are merged and passed to the rerank model for fine-grained ordering. Relying on vector recall alone degrades noticeably with abbreviations, code names, and long digit strings.

    The generation prompt should tightly constrain three things: answer only from the retrieved passages, say explicitly when the passages are insufficient, and attach a source number to every conclusion. Illustrative pseudocode:

    1. context = rerank(recall(query, top_k=30), top_n=6)
    2. prompt = f"""
    3. Answer only from the material below; if the material is insufficient, answer "insufficient information".
    4. Material: {context}
    5. Question: {query}
    6. Requirement: give conclusions one by one and label the source number.
    7. """
    8. answer = llm.chat(prompt)

    5. Deployment and Operations: Filling in the Pits Early

    The general notes for containerized deployment come down to five points:

    • Resource planning: large model inference and vector retrieval compete for memory, so leave headroom on the host to avoid an OOM that takes the containers down with it;
    • Layered persistence: mount model weights, vector store data, and session logs separately so each can be backed up independently;
    • Health checks: configure a readiness probe for every service so the orchestration layer does not send requests before dependencies are ready;
    • Observability: connect a unified logging service with monitoring and alerting, and set thresholds for time-to-first-token, retrieval hit rate, and failure rate;
    • Version pinning: pin image and index construction versions as a pair, and rebuild the index in a canary environment before upgrading, so a change in vector dimensionality or chunking strategy does not make existing data unusable.

    To reduce the burden of self-hosting, it is also worth evaluating a combination of general cloud capabilities: a container platform to host the inference services, object storage for raw documents and model weights, a managed vector retrieval service for the index, and logging and monitoring to close the operations loop. Baidu AI Cloud offers corresponding categories for these general components; check the official documentation for specific specifications.

    6. Conclusion

    The complexity of a private RAG deployment lies not in any single technology but in coordination across the chain. Make inference abstraction, data governance, hybrid retrieval, and observability solid at each layer, and surprises during deployment drop sharply, leaving the system with room to evolve over the long term.