Building a Private Knowledge Base with RAG and Agents: A Practical Guide
This guide walks through building a private knowledge base using Retrieval-Augmented Generation (RAG) and AI agents. It breaks the workflow into ten progressive modules, covering environment isolation and key security, local distilled model deployment, prompt engineering, structured JSON and CSV I/O, document loading and chunking, vector database retrieval, the RAG question-answering loop, ReAct agents with tool calling, evaluation and observability, and security and permissions for production. Each module includes sample code and notes on expected output so readers can reproduce the pipeline step by step.
1. Background: Why LLMs Need External Knowledge
In enterprise applications, general-purpose LLMs often face three pain points: knowledge that stops at the training cutoff, no access to internal private data, and the tendency to generate plausible but incorrect content when uncertain. The solution is not repeated fine-tuning, but decoupling generation from retrieval: the model handles language and reasoning, while an external knowledge base supplies facts. This approach is Retrieval-Augmented Generation (RAG), which extends further into agents that can autonomously call tools.
This article takes a neutral technical perspective and breaks the entire pipeline into ten progressive modules, each with sample code and notes on the output so readers can reproduce it section by section.
2. Module 1: Environment Isolation and Key Security
The first principle is that keys never live in the codebase. Inject credentials through environment variables or a local key file, and let the code read only the variable names.
import osfrom getpass import getpassAPI_KEY = os.getenv("MODEL_API_KEY") or getpass("Enter your key: ")os.environ["MODEL_API_KEY"] = API_KEYBASE_URL = os.getenv("MODEL_BASE_URL", "http://localhost:11434")
Output: the script prints no plaintext key, and the key exists only in process memory. If you use a local inference service, no key is required at all; you only need to specify the local address.
3. Module 2: Deploying and Calling a Local Distilled Small Model
For data-sensitive scenarios, prefer a distilled model that runs locally (a smaller, instruction-tuned version). The common practice is to start a local inference service that exposes a compatible HTTP interface, then wrap the calls in a unified client.
class LocalLLM:def __init__(self, base_url: str, model: str):self.base_url, self.model = base_url, modeldef invoke(self, prompt: str) -> str:# Pseudocode: POST /api/generate, returns {"response": "..."}return call_local_service(self.base_url, self.model, prompt)
Output: the locally generated text is returned, data never leaves the internal network, and compliance requirements are met.
4. Module 3: Prompt Engineering and Few-Shot Examples
High-quality output depends on clear instructions, a role definition, output constraints, and examples. A recommended structure is a three-part layout of system instruction, few-shot examples, and the user question, with a hard rule that the model must answer “insufficient information” when evidence is lacking.
You are an enterprise knowledge base assistant. Answer only based on the given material; if the material is insufficient, reply "Insufficient information."Example 1: Q: Reimbursement cycle? A: Per Article 3 of the Financial Policy, 15 business days.Example 2: Q: Annual leave days? A: Insufficient information.
Output: the model no longer fabricates answers without grounding, and the hallucination rate drops significantly.
5. Module 4: Organizing Input and Output with JSON and CSV
Structure is the prerequisite for automation. Use JSON to carry the session and metadata on input, constrain fields with a JSON Schema on output, and store batch evaluation sets in CSV for regression testing.
{"session_id":"s1","question":"travel policy","top_k":4}{"answer":"...","sources":["doc#12"],"confidence":0.82}
Output: downstream programs can parse the results directly, with no regex extraction needed.
6. Module 5: Document Loading and Text Splitting
The first step in the RAG loop is ingesting data. Use a general document loader to read multiple file formats, then split the text into chunks by semantics with an overlap window so answers are not cut off.
docs = load_documents("./kb")chunks = split_text(docs, chunk_size=500, overlap=50)print(len(chunks)) # Example output: 1284
Key point: chunks that are too large introduce retrieval noise, while chunks that are too small lose semantics, so tune the parameters by document type.
7. Module 6: Vectorization and Vector Database Retrieval
Encode text chunks into vectors and write them to a vector database. At query time, recall the top-K by similarity and assemble them into context.
vdb = VectorStore(embedder)vdb.upsert(chunks)ctx = vdb.search("travel accommodation policy", top_k=4)
Output: the most relevant fragments are returned along with their source IDs, so they can be traced back to the original text.
8. Module 7: The RAG Question-Answering Loop
Inject the retrieval results into the prompt to form a retrieve-generate-cite loop, and keep the sources for auditing.
answer = llm.invoke(build_prompt(question, ctx))
Output: the answer comes with citations, making it verifiable and traceable.
9. Module 8: ReAct Agents and Tool Calling
An agent alternates between thought, action, and observation within its reasoning trace, autonomously choosing tools such as retrieval, calculation, or weather lookup. Middleware is used to register tools uniformly, validate parameters, and log activity.
Thought: I need the internal policyAction: search_kb("reimbursement")Observation: Article 3...Answer: 15 business days
10. Module 9: Evaluation, Caching, and Observability
Build a regression evaluation set and track recall and answer accuracy; apply semantic caching to high-frequency questions; connect logging services and monitoring alerts to track latency and failure rates.
11. Module 10: Security, Permissions, and Going Live
Filter documents at the document level by role, mask sensitive fields, and run compliance checks on the output side. For launch, use a canary release with a rollback plan.
12. Conclusion
From key security, prompts, and structured data to chunking, retrieval, the closed-loop generation, and agent orchestration, the ten modules form a reusable private knowledge base technology stack. If you need a managed setup, you can migrate the vector database, model services, and logging and monitoring to general-purpose cloud products for elasticity and decoupled operations.
