How to Build a Knowledge Base After Deploying a Local LLM
This article explains how to build a private knowledge base after deploying a large language model locally, using Retrieval-Augmented Generation (RAG). It breaks down the full pipeline into eight parts: a five-layer architecture, document ingestion and parsing, chunking strategies, embedding and indexing, hybrid retrieval with reranking, prompt design and constrained generation, engineering operations, and evaluation. You will find practical principles, metadata examples, prompt templates, and iteration practices for building a stable, scalable, and auditable private Q&A system while keeping data on-premises.
How to Build a Knowledge Base After Deploying a Local LLM
After deploying a large language model locally, the model itself is only an “inference engine.” It has no inherent understanding of your business documents, product manuals, or historical support tickets. To make the model answer domain-specific questions, the mainstream and controllable approach is Retrieval-Augmented Generation (RAG): first process documents into retrievable knowledge chunks, then recall relevant content at query time and inject it into the prompt so the model answers based on the given material. This article takes a general technical perspective and breaks down the engineering implementation of this pipeline end to end.
1. Start with the Architecture: What Layers Make Up a Knowledge Base
A maintainable knowledge base system is typically divided into five layers, decoupled from one another through clear data contracts:
- Data ingestion layer: pulls raw documents from local file systems, object storage, message queues, or business databases, supporting both full and incremental synchronization.
- Document parsing layer: converts heterogeneous formats (plain text, rich text, tables, scanned files) into structured text while preserving heading hierarchy and paragraph boundaries.
- Chunking and indexing layer: splits long documents into semantically complete chunks, generates vectors and writes them to the index, and retains source-location metadata.
- Retrieval layer: provides vector recall, keyword recall, and hybrid retrieval that fuses the two, with support for permission filtering.
- Generation layer: assembles recalled chunks into a prompt using a template, calls the local model to generate an answer, and outputs citation sources.
The benefit of understanding this layering is that when answer quality is poor, you can quickly pinpoint whether the problem is information lost during parsing, semantics broken during chunking, inaccurate recall, or poor prompt design, rather than rebuilding the whole system.
2. Data Ingestion and Parsing: The Ceiling on Quality
In engineering practice, more than half of effectiveness problems originate in the parsing stage. Three principles are recommended:
- Preserve structure over text. Heading, list, and table hierarchy is the anchor for downstream chunking, so parsing should output an intermediate structure with hierarchy markers (for example, JSON) rather than a flat blob of text.
- Handle tables and code separately. Tables are best converted into “field name: value” key-value sequences or kept as structured objects; code blocks should be preserved intact to avoid being cut by character count.
- Route scanned files through a separate channel. Image-based PDFs need optical character recognition first before entering the unified parsing pipeline, and pages with low recognition confidence should be spot-checked manually.
For synchronization, it is recommended to maintain a version number and content hash for each document, triggering re-vectorization only when the hash changes, to avoid wasting resources on repeated computation.
3. Chunking Strategy: Semantic Integrity First
The goal of chunking is not “make chunks as small as possible” but “self-contained semantics within a chunk, no information lost between chunks.” Common strategies can be combined:
- Structure-based chunking: use headings and subsections as boundaries, naturally aligning with the document’s table of contents.
- Semantic chunking: compute similarity between adjacent sentences and split at points of semantic shift.
- Fixed window with overlap: as a fallback, the window is usually a few hundred tokens, with an overlap ratio of 10%~20% to prevent information from being cut across chunks.
Each chunk should carry metadata, which is the basis for downstream permission control and citation tracing:
{"doc_id": "manual-2024-01","chunk_id": 17,"text": "……","heading_path": ["Installation", "Environment Requirements"],"page": 8,"update_time": "2024-05-11T09:00:00Z","acl_group": "ops"}
4. Embedding and Indexing: A Critical Step for Localization
The embedding model should be selected separately from the generation model. The embedding model determines recall quality, so prioritize a general-purpose model that supports Chinese, has a moderate dimension, and can run local inference; if GPU memory is tight, a quantized version can be used, but compare recall metrics before deciding.
On the indexing side, three points need attention:
- Keep the similarity metric consistent with the embedding model’s training objective, commonly cosine similarity or inner product.
- For larger data volumes, introduce an approximate nearest neighbor index, trading off recall against latency; for small data volumes, brute-force search is actually more stable.
- Build filter indexes on metadata fields so that “filter by department/time first, then run vector retrieval” becomes a single query rather than a second-pass filter at the application layer.
5. Hybrid Retrieval and Reranking: Raising Accuracy
A single vector retrieval approach is often weak on proper nouns, model numbers, and ID-type queries. A recommended combination:
- Keyword recall handles exact matching, vector recall handles semantic generalization, and the two result sets are fused by normalized scores.
- Introduce a reranking model to fine-rank the candidate set, sending only the top few entries into the prompt to balance effectiveness and context length.
- Set a similarity threshold and a minimum recall count. Too low a threshold introduces noise; too high a threshold may yield empty recall, in which case fall back to “instruct the model to state that the material is insufficient” rather than letting it improvise.
6. Prompts and Generation: Constraining the Model to “Answer Only from the Material”
The core of the generation stage is to keep the model within the given material. A reusable template structure is as follows:
You are an enterprise knowledge assistant. Answer questions based only on the [Material].If the material is insufficient to answer, explicitly state "No relevant content was found in the material." Do not speculate.At the end of the answer, mark citation sources with [number].[Material][1] ...[2] ...[Question]...
It is also recommended to: control the number of chunks and total length injected per call to avoid exceeding the context window; generate long answers in segments; lower sampling parameters such as temperature to improve stability; and persist the model output together with the cited chunks for auditing.
7. Engineering Support: Keeping the System Running Sustainably
- Service orchestration: split parsing, embedding, retrieval, and inference into independent services, deploy and elastically scale them via a container platform, and use a message queue to smooth out task-type workloads.
- Storage tiering: keep raw documents in object storage, vectors and metadata in the index, and session and audit logs in a logging service.
- Observability: build monitoring and alerting dashboards for recall hit rate, empty recall rate, time to first token, and per-turn latency.
- Permissions and security: enforce unified authentication at the retrieval layer so that “chunks without permission never enter the candidate set,” rather than filtering after generation.
- Cost optimization: cache results for high-frequency questions and vectorize batch documents offline to avoid heavy computation in the online path.
8. Evaluation and the Iteration Loop
Without evaluation, there is no optimization. It is recommended to build an evaluation set of several hundred real question-answer pairs, annotating the standard answers and the document chunks that should be hit, and to measure recall rate and hit rate at the retrieval layer separately from answer correctness and citation consistency at the generation layer. After each adjustment to chunking parameters, the embedding model, or the prompt, run a regression pass and let data decide whether to keep the change. On the online side, collect user downvotes and manual feedback and periodically feed them back as new evaluation samples, forming a loop.
Conclusion
Deploying a large language model locally is only the starting point; the value of a knowledge base depends on data processing and retrieval quality. Following the main thread of “preserve structure in parsing, preserve semantics in chunking, use hybrid retrieval, enforce strong constraints in generation, and keep operations observable,” and driving iteration with an evaluation set, you can build a stable, scalable, and auditable private Q&A capability while keeping data within the intranet. If further elastic scaling is needed, the vector index and task scheduling can also be migrated to cloud container platforms and managed retrieval services while keeping the data plane private.
