Building a Stable AI Agent with LLMs and a Private Knowledge Base
Turning a chatbot demo into a production-grade enterprise agent requires more than connecting a large language model to a chat window. This article walks through the full architecture needed for reliability: choosing between vector search, graph-based retrieval, and structured knowledge pages; preparing documents so retrieval actually works; designing tools the model can call safely; separating short-term context from long-term memory and business state; handling air-gapped or on-premises deployment; and building an evaluation framework that checks retrieval, generation, tool use, and runtime performance. It closes with a five-phase rollout plan for moving from a minimal working loop to a fully governed production system.
1. Define the Goal First: Being Conversational Is Not the Same as Being Production-Ready
Many teams build their first AI agent by taking the shortest path: a user asks a question, the question is sent to a large language model, and the answer is returned to the chat window. This approach produces an impressive demo, but once it reaches a real enterprise environment, problems surface quickly:
- The model’s answers may sound fluent but lack a verifiable source.
- The answer exists in the knowledge base, but the retrieval module fails to find it.
- The agent calls tools, but parameters are frequently missing or malformed.
- As conversations grow longer, the model forgets earlier context or mixes up information from different users.
- In an isolated network environment with no access to external services, system stability drops.
- After a document is updated, the agent keeps citing the outdated version.
- Business users can’t tell which policy document or record an answer actually came from.
An enterprise-grade agent should not be thought of as a chatbot. It is a decision-and-execution system made up of several cooperating modules:
User request↓Intent recognition and task decomposition↓Knowledge retrieval / tool calls / memory access↓Result validation and answer generation↓Source citation, execution logs, and security audit
A more complete way to describe this is:
Agent = LLM + Knowledge system + Tool system + Memory system + Operational governance
A weak design in any single component will drag down the performance of the whole system.
2. Choosing a Knowledge Base: No Single Approach Solves Every Problem
The knowledge base is the agent’s infrastructure. Choosing one isn’t just about retrieval speed or deployment complexity — it requires analyzing the shape of the business problem: single-document Q&A versus cross-document reasoning, high-frequency lookups versus constantly updated content, and use by general staff versus specialized operators.
2.1 Vector Search Works Well for Semantically Similar Questions
The basic vector search pipeline looks like this:
- Split source documents into chunks.
- Convert each chunk into a numerical vector using an embedding model.
- Store the vectors in a vector database.
- Convert the user’s question into a vector.
- Retrieve relevant chunks by similarity.
- Pass the retrieved chunks and the question to the LLM to generate an answer.
This approach fits well when:
- The content is relatively self-contained, such as policies, manuals, or FAQs.
- User phrasing varies, but the underlying meaning is similar.
- You need to build a minimum viable version quickly.
- The document volume is large but the relationships between documents are simple.
However, vector search doesn’t truly understand complex business relationships. For example, if a user asks “what should be checked when a device fails to recover automatically after a protection trip,” the answer may be scattered across equipment manuals, fault-handling procedures, operation logs, and safety regulations. A single similarity search may only retrieve part of the relevant content, leading to an incomplete answer.
2.2 Graph-Based Retrieval Works Well for Multi-Hop Relationships and Relational Reasoning
For domains with many entities, attributes, and relationships, it helps to build a structured relationship layer on top of the documents, for example:
Device A ——belongs to—— System BSystem B ——has fault—— Fault CFault C ——inspection item—— Item DItem D ——references procedure—— Document E
This approach supports multi-step retrieval along a chain of relationships, and fits:
- Hierarchical relationships between equipment and components.
- Associations between faults, causes, and remedial actions.
- Cross-references between policy clauses.
- Constraints linking personnel, roles, permissions, and operating procedures.
More complexity isn’t always better, though. Graph-based retrieval requires additional work for entity recognition, relation extraction, conflict resolution, and ongoing maintenance. For simple factual questions, a complex graph query can add latency and introduce error propagation instead of reducing it. A more practical approach is to route questions by type:
Simple factual question → Vector searchMulti-entity, multi-relationship question → Structured relationship retrievalFixed-process question → Rule engine or workflow engineAction-required question → Tool call
2.3 Structured Knowledge Pages Work Well for Long-Term Maintenance
Beyond vector search and graph structures, document content can be pre-organized into structured knowledge pages. Each page includes fields such as topic, scope, prerequisites, core conclusion, procedure steps, risk notes, related documents, and last-updated date.
For example:
topic: Handling abnormal equipment shutdownscope: A specific category of production equipmentprerequisites:- Equipment confirmed to be shut down- On-site safety isolation completedprocedure:- Check power supply status- Check protection devices- Review recent operation logsrisk_notes:- Do not perform a reset before isolation is completesources:- Document ID A- Document ID B
The advantage is more stable information organization, easier manual review, and better long-term maintainability. The downside is higher upfront effort to organize the content and the need for a clear data schema.
2.4 A Hybrid Knowledge Architecture Is Recommended
Production systems generally shouldn’t rely on a single knowledge representation. A combined approach works better:
- Vector search for open-ended semantic Q&A.
- Structured relationships for cross-document, multi-entity reasoning.
- Structured knowledge pages for high-frequency, critical, and stable business knowledge.
- Rule engines for clear-cut decision logic.
- Manual review for high-risk content.
The key isn’t which technology you pick — it’s building a clear mapping from question type to retrieval strategy to answer format.
3. Document Processing Sets the Ceiling for Retrieval Quality
Many retrieval failures aren’t caused by weak model capability — they come from poor document preprocessing.
3.1 Don’t Chunk by a Fixed Character Count
Mechanically splitting text by a fixed length can separate a heading from its body text, break apart a sequence of steps, or chop a table into fragments that no longer make sense. A more reliable chunking process looks like this:
- Identify the document’s heading hierarchy.
- Split by section, paragraph, and semantic boundaries.
- Handle tables, lists, and formulas with dedicated logic.
- Attach metadata to each chunk — document name, section path, version, and applicable scope.
- Merge chunks that are too short or lack complete information.
Each knowledge chunk should carry at minimum the following metadata:
{"document_id": "DOC-001","title": "Equipment Operating Procedure","section": "Fault Handling/Abnormal Shutdown","version": "2025-01","department": "Operations Management","effective_date": "2025-01-01","content": "..."}
3.2 Version and Validity Must Be Part of the Retrieval Criteria
Enterprise documents often exist in multiple versions. If retrieval relies solely on semantic similarity, an outdated version can be retrieved alongside the current one, and the model may synthesize a conclusion that doesn’t actually hold.
Retrieval should therefore account for:
- Whether the document is still valid.
- Whether the requesting department has access permission.
- The time range relevant to the question.
- Whether the document is the current version.
- Whether a higher-priority policy document exists.
A knowledge base isn’t a static folder of files — it’s a data system with versioning, access control, and a content lifecycle.
4. Tool Design: Make the Model Able to Call Tools — and Unable to Misuse Them
Tools are what distinguish an agent from a plain Q&A system. Tools can query business data, generate reports, run calculations, create tickets, or trigger approval workflows.
4.1 Tool Definitions Must Follow a Strict Schema
A well-defined tool should specify at minimum:
- Tool name
- Purpose
- Input parameters
- Parameter types
- Whether each parameter is required
- Valid value ranges
- Return format
- Error messages on failure
- Call permissions and risk level
Example structure:
{"name": "query_operation_record","description": "Query the operating records of a specific device within a given time range","parameters": {"device_id": {"type": "string","required": true},"start_time": {"type": "string","required": true},"end_time": {"type": "string","required": true}}}
The vaguer the parameter definitions, the more likely the model is to pass null values, malformed input, or irrelevant fields. Tool descriptions shouldn’t be too broad either, or the model may call the tool in situations where it doesn’t actually apply.
4.2 Tool Names Should Reflect Business Semantics
Tool names should directly express the action and the target object — for example, “query operation record,” “calculate risk level,” or “get current inventory” — rather than vague labels. When the number of tools grows large, group them or add a routing layer so the model doesn’t have to choose among dozens of similar tools.
4.3 High-Risk Tools Require a Confirmation Step
For operations like deleting data, submitting approvals, modifying configuration, or sending notifications, the model shouldn’t be allowed to execute them directly. A two-stage flow is safer:
Model generates an action plan↓System displays the scope of impact and parameters↓User confirms↓Tool executes↓Result returned and logged for audit
The model’s role is to propose actions and assemble parameters. Final execution authority should remain with the business system and its permission controls.
5. Memory System: Separate Context, Long-Term Memory, and Business State
“Memory” isn’t simply concatenating the entire conversation history into the prompt. At minimum, three types of information should be kept separate.
5.1 Short-Term Context
Short-term context supports understanding the current conversation — things like a device ID the user just mentioned, a time range, or the current task goal. It should have a length limit and be summarized when needed, rather than growing without bound.
5.2 Long-Term User Preferences
Long-term memory can store a user’s preferred answer format, frequently used business scope, and default query conditions. This kind of data requires explicit consent, and users must be able to view, edit, and delete it.
5.3 Business State
Business state generally shouldn’t live in the model’s memory at all — it should be maintained by the business database, covering things like a ticket’s current status, approval stage, assigned owner, and execution result. The model can read this state, but conversational history alone should never be the source of truth for it.
A sound memory strategy looks like this:
Current conversation: keep only necessary contextLong-term preferences: structured storage, user-manageableBusiness state: owned by the business system as the single source of truth
6. Private and Air-Gapped Deployment: It’s Not Just About Getting the Model Running
Deploying an agent in an isolated or on-premises network environment requires planning for the model, the knowledge base, logging, dependencies, and the upgrade process together.
6.1 Model Selection Must Respect Operational Constraints
Model selection shouldn’t be based on public benchmark scores alone. Consider:
- Available GPU memory and compute resources.
- Concurrency and latency requirements.
- Whether long-context support is needed.
- Whether structured output is supported.
- Stability for tool calling and complex reasoning.
- Whether data isolation requirements are met.
- Whether a quantized version still delivers acceptable quality.
For example, an on-call support assistant may prioritize response speed, citation accuracy, and sustained uptime, while a research analysis system may prioritize long-context comprehension. Different goals call for different trade-offs in model choice.
6.2 Air-Gapped Environments Need a Complete Dependency Chain
Common issues in offline deployments include:
- Incomplete model files.
- Version mismatches between the embedding model and the main LLM.
- Python or other runtime dependencies that can’t be installed online.
- Document parsers missing required fonts or system libraries.
- Time synchronization, certificates, and logging services not properly configured.
- No ability to roll back quickly during an upgrade.
Teams should prepare offline installation packages, dependency manifests, model checksum records, and version registries in advance, along with a complete rollback plan. In production, the real risk isn’t a single outage — it’s being unable to recover from one.
7. Evaluation: Don’t Judge an Agent Just by How Human It Sounds
Before launch, an agent needs a repeatable evaluation set covering at least these dimensions.
7.1 Retrieval Metrics
- Whether relevant chunks are retrieved.
- Whether key evidence appears near the top of the results.
- Whether expired or unauthorized documents get retrieved.
- Whether multi-document questions are covered by complete evidence.
7.2 Generation Metrics
- Whether the answer is accurate.
- Whether the answer contains unsupported inferences.
- Whether cited sources are real.
- Whether uncertainty is clearly stated when appropriate.
- Whether formatting and safety requirements are followed.
7.3 Tool-Use Metrics
- Whether the correct tool is selected.
- Whether parameters are complete.
- Whether the number of calls is reasonable.
- Whether the system retries or escalates to a human after a tool failure.
- Whether any unauthorized operations occur.
7.4 Runtime Metrics
- Time to first response.
- Total completion time.
- Resource usage under concurrent load.
- Error rate and timeout rate.
- Time to effect after a knowledge base update.
The evaluation set should include normal questions, ambiguous questions, cross-document questions, questions with no answer, out-of-scope questions, and adversarial prompts. It’s especially important to test whether the system honestly says “I don’t know” when the knowledge base has no answer.
8. Recommended Rollout Sequence
To reduce implementation risk, roll out the system in stages.
Phase 1: Build a Minimal Working Loop
Implement document ingestion, retrieval, answer generation, and source display first, without rushing to integrate many tools. The goal is to validate the chunking, retrieval, and citation pipeline.
Phase 2: Introduce Question Routing
Route questions to vector search, structured queries, rule-based logic, or human handoff based on question type, instead of sending every request through the same path.
Phase 3: Integrate Low-Risk Tools
Start with read-only queries, calculations, and summarization tools to validate parameter checking, error handling, and audit logging.
Phase 4: Build Out Memory and Permissions
Add user identity recognition, department-level permissions, conversation summarization, long-term preferences, and business state management.
Phase 5: Production Governance
Fill in monitoring, alerting, the evaluation set, version management, data masking, staged rollout, and rollback procedures.
Conclusion
Building a knowledge-base agent that can answer questions isn’t the hard part. The hard part is keeping it working reliably, consistently, and explainably in a real production environment. Technology selection is only the starting point — document governance, tool boundaries, permission control, memory design, offline deployment, and evaluation are what determine whether the system can run long-term.
A more reliable approach isn’t chasing a single “do-everything” agent. It’s building a layered architecture: let the retrieval system find evidence, let the structured system store facts, let the tool system execute actions, let the business system own permissions and state, and let the LLM handle understanding, planning, and communication. Only by clearly assigning responsibility to each module can an agent move from a demo to a system an enterprise can actually run on.
