Engineering Practices for Building Intelligent Agents with LLMs and Custom Knowledge Bases
Many enterprise teams struggle with generic LLMs lacking internal knowledge. Simply deploying an open-source model is insufficient; deep integration with custom knowledge bases, tool calling, and memory mechanisms is required to build truly effective intelligent agents. Based on extensive production environment experience, this guide details the architecture selection, common pitfalls, and practical recommendations for building enterprise-grade AI agents.
Engineering Practices for Building Intelligent Agents with LLMs and Custom Knowledge Bases
When implementing enterprise AI, many teams encounter the same problem: generic LLMs are entirely ignorant of internal company knowledge. Simply deploying an open-source model is far from enough. You must deeply integrate the model with a custom knowledge base, add tool calling, and implement memory mechanisms to form a genuinely usable intelligent agent. Based on half a year of production environment experience on self-hosted GPU servers, this article comprehensively outlines our selection strategies, pitfalls encountered, and implementation recommendations. It is important to emphasize that every conclusion here is practically verified, not just theoretical documentation reading.
1. Knowledge Base Strategies: Three Routes and Their Boundaries
The knowledge base is the foundation of a knowledge-based agent, but “how to organize knowledge” is far more critical than “whether to have a knowledge base.” There are three common industry routes, each more complex and more easily underestimated in cost than the last.
1. Vector Search (RAG): The Go-To for Simple Problems
The classic RAG approach involves chunking documents, vectorizing them, and storing them in a vector database. Queries retrieve relevant chunks based on semantic similarity. Its advantages are simple implementation, low maintenance cost, and fast cold starts. It handles most queries like “finding a specific clause” or “locating an operational step.” However, it has an inherent shortcoming: when answers are scattered across multiple documents and require multi-hop associative reasoning (e.g., “What does another file, referenced by Article X of a specific regulation, stipulate?”), the recall rate and accuracy of pure vector retrieval drop significantly.
2. Graph-Enhanced Retrieval (GraphRAG): Solves Relationship Issues but at a High Cost
GraphRAG’s concept is to extract entities and relationships from documents to build a knowledge graph, and during retrieval, perform multi-hop expansions along graph edges. This naturally suits answering associative questions across documents and entities. However, in engineering practice, we must throw cold water on two fronts:
- Extremely high construction cost. Building a graph from a few hundred industry regulations requires massive extraction, cleaning, and manual validation. Even with a self-hosted GPU cluster, it takes a long time to converge to a usable state.
- Worse for simple problems. Evaluation papers have noted that for single-point factual questions, the retrieval noise and graph traversal overhead make GraphRAG less effective than pure vector RAG. Graphs are not a panacea; they only provide irreplaceable value in scenarios where “the relationship is the answer.”
3. LLM-Digested Knowledge Bases: Letting the Agent “Digest” Knowledge
The third route is more aggressive: instead of indexing new documents, let the LLM “compile” documents into a structured knowledge base in advance (similar to a continuously evolving wiki). When new knowledge arrives, the agent automatically compares, merges, and updates existing entries. The benefit is that retrieval reads pre-digested knowledge, improving answer quality and consistency. The cost is massive token consumption—every knowledge update is a deep read and rewrite. In offline or intranet environments, the context length of open-source models directly becomes a bottleneck. Additionally, automatic updates carry the risk of knowledge pollution, so in production environments, it’s often necessary to step back to a “semi-automatic + manual review” maintenance approach.
Conclusion: Use a Hybrid Approach in Production
Don’t expect a single solution to rule them all. The recommended approach in actual production is layered routing:
- Simple factual questions → Pure vector RAG, low cost, low latency;
- Entity-associative, multi-hop reasoning questions → GraphRAG;
- High-frequency, operational knowledge requiring precise expression → Structured knowledge base, maintained primarily manually with LLM-assisted organization.
Adding a lightweight intent classification layer at the query entry point (implementable via a small model or rules) to route requests to different retrieval channels is the optimal balance of cost and performance.
2. The Four Elements of an Agent: Three Puzzle Pieces Beyond Knowledge
A complete agent can be abstracted as: Agent = LLM + Knowledge + Tools + Memory. The knowledge base has been thoroughly discussed above; the remaining three elements each have a typical major pitfall.
1. LLM Selection: Constraints Matter 100x More Than Benchmark Scores
The key to model selection isn’t who has the highest benchmark score, but two questions: What can your hardware run, and what does your business need?
Take an actual case of a duty assistance system: the business required a result within 3 seconds, and the answer had to include citation sources. These two hard constraints directly dictate:
- The model size must be able to infer at the target latency on existing GPUs—for example, low-bit quantization and multi-card tensor parallelism on a medium-sized open-source model is a common configuration for multi-GPU server environments.
- Answers requiring citations mean retrieval results must be concatenated with the generation within the same context. Context length and the precise ranking quality of retrieved chunks become hard metrics.
List business constraints like latency, cost, context length, and citation capabilities as a checklist, then look at model specifications. The order cannot be reversed. Benchmark tables are only for initial screening, not decision-making.
2. Tools: Precise Schemas + Clean Prompts
Tool calling is the core that distinguishes an agent from a standard Q&A bot, and it’s the most failure-prone area. Here are two real-world pitfalls:
Pitfall 1: Imprecise tool definitions. In early versions, the input parameter for the knowledge base retrieval tool was just a free-form query string. As a result, the model often passed empty strings, degrading retrieval into invalid calls. The solution is to define a strict parameter schema for each tool (field names, types, required flags, value constraints), giving the model’s parameter generation clear boundaries. An example is as follows:
{"name": "search_knowledge_base","description": "Search the enterprise knowledge base for document chunks related to the query","parameters": {"type": "object","properties": {"query": {"type": "string", "minLength": 2, "description": "Natural language query, must not be empty"},"top_k": {"type": "integer", "default": 5, "minimum": 1, "maximum": 10}},"required": ["query"]}}
Pitfall 2: Example pollution. Once, an agent “invented” a non-existent tool and tried to call it. Upon investigation, the cause was that a weather query tool example was included in the system prompt, and the model treated it as a real capability. The lesson is clear: Do not include tool examples in the prompt that are irrelevant to the business. Every example will be taken seriously by the model.
Additionally, standardized protocols now exist at the tool protocol level (such as standard tool connection protocols). Tool registration, description, and calling can be managed standardly, eliminating the need to reinvent the wheel with private protocols.
3. Memory: Separate Session State and Long-Term Memory Design
Memory mechanisms are often overlooked but make a significant difference in the feel of a production system. It is recommended to design them in two layers:
- Short-term memory: Multi-turn context within the current session. Note that summarization compression should be used rather than infinite concatenation; otherwise, context explosion and latency spikes will occur in long conversations.
- Long-term memory: Cross-session user preferences, high-frequency issues, and correction records. These can be persisted to structured storage and injected on-demand at the start of each session.
4. Evaluation and Security: A Crucial Step Before Launch
Production environments also require evaluation baselines and guardrails: establish a regression test set covering simple queries, associative queries, and refusal-to-answer scenarios. Run it whenever changing models, tweaking prompts, or altering retrieval logic. Apply permission filtering to retrieved content to prevent unauthorized knowledge leakage. Perform citation verification on generated results; citations in the answer must be traceable to the retrieved results. If not found, degrade to “no basis found” rather than forcing a generation.
3. Conclusion
The core experience of building an enterprise-grade knowledge agent can be distilled into four points:
- Knowledge base selection depends on the problem form: A hybrid approach (Vector RAG + GraphRAG + Structured Knowledge Base) outperforms any single solution.
- Model selection depends on business constraints: Latency, cost, and context length are more worthy of being written into requirements documents than benchmark scores.
- Tool design relies on strict schemas and clean prompts: Constrain parameters down to the field level, and only use business-relevant examples.
- Memory and evaluation are indispensable: Layered memory improves experience, and regression evaluation ensures iteration safety.
There is no silver bullet in agent engineering. If a simple solution can solve the problem, don’t introduce a complex one. Every layer of complexity must prove its worth through real business value.
