A Practical Guide to Connecting LLMs with Private Knowledge Bases

    This article explains how to connect large language models with private knowledge bases, separating reasoning from knowledge so answers stay factual and traceable. It compares context injection and retrieval-augmented generation (RAG), outlines a five-layer reference architecture, and covers the engineering details that determine quality: document parsing and chunking, hybrid retrieval with reranking, context assembly with prompt constraints, citation and traceability, evaluation, and permissions, security, and cost control. It also lists common pitfalls and recommends a low-risk rollout path that starts small and scales to the full knowledge base.

    1. The Starting Point: General Reasoning Is Not Business Knowledge

    The value of a large language model comes from two things stacked together: the model’s language understanding and reasoning ability, and the source of facts the answer relies on. The former is determined by the model weights; the latter is usually scattered across internal documents, papers, project records, and personal notes. When a user asks a question like “why does a certain technical practice have two sides,” a model answering purely from parametric memory tends to drift on facts, produce inconsistent statements, and fail to cite sources.

    For this reason, the common industry approach is to decouple “reasoning” from “knowledge”: the model handles intent understanding, language, and reasoning, while an external knowledge base supplies authoritative facts. There are two main forms this takes in practice.

    • Context injection: the user explicitly selects a set of materials as the reference scope for the current session, and the material content is assembled into the model’s input context.
    • Retrieval-augmented generation (RAG): the system recalls fragments from a large knowledge base by semantic relevance, then dynamically assembles the context.

    These are not replacements for each other but different trade-offs at different scales. When the material volume is on the order of a few to a few dozen documents and the user clearly knows which material to consult, direct injection is simpler and more controllable. When the volume reaches thousands of documents or more and manual selection is impossible, retrieval becomes necessary.

    2. Engineering Differences Between the Two Paths

    Dimension Context Injection Retrieval-Augmented
    Suitable scale Small, curated materials Massive, continuously growing
    Context cost High and fixed Low and controllable
    Recall accuracy Depends on user selection Depends on chunking and retrieval quality
    Maintainability Simple Requires ongoing evaluation and tuning
    Typical scenario Single-project document Q&A Enterprise knowledge platform

    In practice, a mature form combines the two: retrieval first narrows the scope from the full library, the user is then allowed to add specified materials, and the context is assembled uniformly at the end.

    3. A Layered Reference Architecture

    A maintainable private knowledge Q&A system is typically divided into five layers:

    1. Ingestion layer: file upload, selection of existing note collections, and session context management.
    2. Parsing layer: format recognition, layout restoration, and preservation of tables and code blocks.
    3. Indexing layer: chunking, vectorization, keyword indexing, and metadata writing.
    4. Retrieval layer: vector recall, keyword recall, fusion ranking, reranking, and deduplication.
    5. Generation layer: prompt assembly, citation labeling, refusal strategy, and result auditing.

    The key benefit of layering is isolation: when retrieval quality drops, you tune only the indexing layer; for answer-style issues, you tune only the generation layer, without one affecting the other.

    4. Knowledge Preparation: Parsing and Chunking Set the Ceiling

    Chunking quality is the ceiling of the entire pipeline. If chunking breaks semantic integrity, no amount of retrieval strength downstream can fix it. Principles to follow:

    • Chunk by structure, not by fixed character count: prefer to break at heading, paragraph, and list-item boundaries.
    • Control block size and preserve overlap: blocks that are too large introduce recall noise, blocks that are too small lose meaning, and overlap mitigates information split across blocks.
    • Carry metadata with each block: source, section path, update time, and permission labels must be written in for filtering and traceability.

    Illustrative chunking logic:

    1. def split_document(text, max_chars=800, overlap=120):
    2. blocks, buf = [], ""
    3. for para in text.split("\n\n"):
    4. if len(buf) + len(para) <= max_chars:
    5. buf += para + "\n\n"
    6. else:
    7. if buf:
    8. blocks.append(buf)
    9. tail = buf[-overlap:] if overlap else ""
    10. buf = tail + para + "\n\n"
    11. if buf.strip():
    12. blocks.append(buf)
    13. return [b.strip() for b in blocks]

    5. Retrieval and Reranking: From “Findable” to “Accurate”

    Single-vector recall is insensitive to proper nouns, IDs, and abbreviations, so the common engineering practice is hybrid retrieval: vector recall handles semantic similarity, keyword recall handles exact matching, and fusion ranking merges the results. A reranking model can follow fusion to score the relevance of candidate fragments to the question precisely, keeping only the top few for the context.

    1. def retrieve(query, top_k=20, keep=5):
    2. dense = vector_search(query, top_k) # semantic recall
    3. sparse = keyword_search(query, top_k) # exact recall
    4. merged = fuse(dense, sparse) # fusion and dedup
    5. ranked = rerank(query, merged) # fine-grained rerank
    6. return ranked[:keep]

    You should also set a similarity threshold and a minimum evidence count: when evidence is insufficient, it is better to refuse or prompt for more material than to force an answer from low-relevance content.

    6. Context Assembly and Prompt Constraints

    The core of the assembly stage is to clearly specify “role constraints, available materials, output format, and refusal conditions,” and to enforce verifiable citations.

    1. You are a rigorous technical assistant.
    2. Answer only based on the [References]; do not make claims beyond the material.
    3. Label the source number after each conclusion, e.g., [1].
    4. If the material is insufficient to support a conclusion, state the gap explicitly; do not speculate.
    5. Output structure: conclusion -> basis -> source number.

    When concatenating materials, it is recommended to attach a number and a metadata header, for example “[1] Source: some project document / Section: risks and benefits / Updated: …”. This serves both as a traceability basis and helps users judge the timeliness of the material.

    7. Citation Traceability and Verifiability

    Private knowledge scenarios demand higher trustworthiness than open-domain Q&A. At a minimum, three things should hold: every key claim in the answer can point back to a specific fragment; the fragment can jump back to its location in the original text; and the original version is traceable. If the knowledge base has multiple versions, retrieval must filter by version or time to avoid mixing old and new statements.

    8. Evaluation and Continuous Iteration

    Do not tune parameters based on subjective feeling. It is recommended to build a small but stable evaluation set covering three question types: factual, comparative, and refusal. Metrics should include at least recall hit rate, citation accuracy, refusal accuracy, and answer consistency. After each adjustment to chunking parameters, recall count, or prompts, rerun the evaluation and let data decide the trade-offs.

    9. Permissions, Security, and Cost Control

    • Permissions up front: apply permission filtering at the retrieval stage rather than the generation stage, to prevent unauthorized fragments from entering the context.
    • Sensitive data handling: desensitize before upload, and avoid writing raw text into logs.
    • Cost control: cache high-frequency Q&A, compress redundant context, and select model tiers by scenario.
    • Observability: record recalled fragments, latency, and failure reasons to make problems easier to locate.

    If you rely on general cloud capabilities, you can typically combine object storage for raw files, a message queue for asynchronous indexing, a container platform to run parsing and retrieval services, and logging and monitoring/alerting services for observability. Similar general-purpose capabilities from vendors such as Baidu AI Cloud can serve as a selection reference; refer to the official documentation for specific specifications.

    10. Common Pitfalls

    1. Treating “stuff everything into the context” as a solution: context is limited and cost rises with length; filling it up dilutes key information instead.
    2. Optimizing only the model and not the data: most answer-quality problems stem from parsing and chunking, not model capability.
    3. Lacking a refusal mechanism: it is better to admit the material is insufficient than to generate plausible-looking but unfounded content.
    4. Launching once without evaluation: the knowledge base keeps growing and retrieval quality drifts, so regression testing must be routine.

    Conclusion

    Combining a large model’s reasoning ability with a private knowledge base is essentially a data engineering and retrieval engineering effort, not merely a model selection problem. Proceeding in the order of “parse - chunk - index - retrieve - assemble - trace - evaluate,” validating on a small set of curated materials first and then gradually expanding to the full knowledge base, is the lowest-risk and most certain path to a successful rollout.