Building an Enterprise LLM Engine: RAG and Real-Time Search
A reliable enterprise LLM application needs more than well-crafted prompts. This article explains how to combine retrieval-augmented generation, real-time search, tool calling, and application orchestration into an evidence-based system. It covers document ingestion, parsing, cleaning, chunking, access-controlled retrieval, safe tool execution, source verification, context assembly, and production evaluation, with a phased approach to deployment.
1. Define the Goal: Complete Tasks Using Reliable Evidence
Enterprises adopting large language models often face three problems: models cannot directly access internal documents, their existing knowledge does not reflect recent changes, and business workflows require interaction with external systems. Prompt optimization alone is unlikely to solve all three.
A more complete approach is to build an intelligent engine that combines application orchestration, retrieval-augmented generation (RAG), tool calling, and real-time search:
- RAG supplies evidence from internal enterprise knowledge.
- Real-time search adds time-sensitive external information.
- Tool calling queries structured data or performs authorized business operations.
- Application orchestration manages authorization, task routing, context assembly, and output.
More capabilities do not automatically make a system better. A question about an internal expense policy usually does not require external search. A question about a recently published public policy may need it. Submitting a business request must go through a controlled operational interface. The system should first determine which evidence and actions a task requires, then select the appropriate execution path.
The architecture can be divided into two pipelines:
Offline knowledge pipeline:Source ingestion → Document parsing → Cleaning and validation→ Chunking and metadata enrichment→ Embedding and keyword indexing → Version releaseOnline question-answering pipeline:User request → Identity and authorization checks → Intent analysis→ Retrieval or tool calling → Evidence selection→ Context assembly → Answer generation → Citations and audit
The offline pipeline determines whether the knowledge is reliable. The online pipeline determines whether it is used correctly. Bulk-indexing low-quality documents does not automatically produce high-quality answers.
2. Data Ingestion: Reading Files Is Only the First Step
Enterprise information is typically distributed across document repositories, business systems, websites, and archived attachments. Formats may include PDFs, word-processing documents, Markdown notes, scanned images, and web pages.
The ingestion layer must answer three questions: Where does the information come from? How will it stay current? Who is allowed to use it?
2.1 Give Documents Stable Identities
Each document should have a stable identifier, along with its source location, content hash, owning department, access scope, version status, and processing timestamp.
A content hash helps detect changes, while a stable identifier links different versions. File names alone are insufficient: different departments may use identical names, and the same document may be renamed repeatedly.
Updates should be idempotent. Receiving the same version more than once should not create duplicate index entries. When a source file is deleted, its associated chunks and retrieval records should also be removed or invalidated so the system cannot continue citing a withdrawn policy.
2.2 Separate Incremental Synchronization from Full Rebuilds
Routine updates are best handled incrementally, processing only new, modified, and deleted documents. Significant changes to parsing rules, chunking strategies, or embedding models may require rebuilding the affected indexes.
During a rebuild, keep the previous version available where possible. Switch only after the new version passes validation, so users do not search an incomplete collection.
2.3 Make Processing Failures Visible
Corrupted files, password protection, encoding errors, and failed image recognition can interrupt ingestion. Failed jobs should not disappear silently. Record the failed stage, the cause, and whether a retry is possible.
Important documents that cannot be processed automatically can enter a manual review queue. An enterprise knowledge system must track not only how many files were processed successfully, but also which files never entered the knowledge base—and why.
3. Document Parsing: Preserve Structure, Not Just Text
Parsing should recover the organization of the original content, rather than merely produce a string of characters.
3.1 Use Parsing Paths Appropriate to Each Source
For documents with a text layer, prioritize extracting text and layout information. Scanned documents require optical character recognition (OCR), with attention to low-confidence regions. Web pages require main-content extraction that excludes navigation, recommendations, and advertisements. Word-processing documents should retain relationships among headings, lists, tables, and comments wherever possible.
Parsed output should include body text, heading hierarchy, page numbers, paragraph order, table locations, and source anchors. Preserve a trustworthy publication date when the source provides one. If it does not, do not present the ingestion timestamp as the publication date.
3.2 Protect the Reading Order
Multi-column layouts, margin notes, and tables spanning multiple pages can disrupt text order. For example, an illustration in the right-hand column may be inserted into a policy paragraph from the left-hand column, changing its meaning.
Sample parsed documents to verify reading order, especially for structurally complex sources such as contracts, technical manuals, and financial reports. Documents sharing a file format do not necessarily share the same parsing difficulty.
3.3 Do Not Flatten Tables into Unstructured Text
Table values depend on row and column headings. Extracting only cell contents may leave the model unable to determine which item an amount belongs to or which period a metric describes.
A safer approach is to preserve the original table location and also generate a text representation that retains field relationships:
Item: Equipment maintenanceApplicable period: AnnualBudget limit: Refer to the corresponding amount in the original tableApproval condition: Submit after department manager reviewSource: Specified table location in the original document
This representation supports retrieval; it must not fill in information absent from the table. Merged cells, footnotes, and unit conversions require particular care to preserve fidelity.
4. Data Cleaning: Remove Noise Without Removing Business Meaning
Headers, footers, repeated copyright notices, advertising fragments, and meaningless whitespace add retrieval noise and consume model context. However, cleaning is not simply a matter of deleting repeated content.
4.1 Identify Actual Noise
Repeated headers and footers can be identified using frequency, page position, character patterns, and layout features. Web cleaning should focus on menus, overlays, and recommendations outside the main content area.
Some repetition carries business meaning, such as “For internal use only” or “This clause does not apply to certain cases.” Do not remove such text merely because it appears multiple times.
4.2 Normalize Characters and Formatting Carefully
Standardizing whitespace and repairing unusual line breaks is often useful. However, numbering, dates, amounts, units, negation, and code indentation can all affect meaning.
For example, “must not exceed” and “exceeds” convey different requirements. Missing negation in OCR output can cause serious errors. Critical policy language and monetary fields should receive stricter validation or manual review.
4.3 Preserve Originals and Transformation History
Cleaned text should remain traceable to the original file. Record parser versions, cleaning-rule versions, processing timestamps, and exception flags. These records help determine whether an incorrect answer originated in the source, parsing, or subsequent retrieval.
Personal information and sensitive business data should be minimized according to the intended use. Validate whether redacted content remains searchable in the relevant business context; successful replacement alone is not enough.
5. Knowledge Chunking: Make Each Passage Independently Understandable
Because model context is limited, retrieval systems usually divide long documents into chunks. Large chunks can introduce irrelevant material, while small chunks can lose conditions and context.
5.1 Prefer Structure-Aware Chunking
Start with sections, headings, paragraphs, and lists, then subdivide content that remains too long. Keep procedural steps, definitions and exceptions, and tables with their explanations within the same semantic unit where possible.
Avoid mechanically splitting text at a fixed character count. If a policy states its scope and then lists exceptions, separating them may cause retrieval to return the rule without its restrictions.
5.2 Control Overlap to Reduce Duplication
Some overlap between adjacent chunks can reduce information loss at boundaries. More overlap, however, also increases storage, retrieval redundancy, and repeated context.
Determine chunk length and overlap through testing rather than adopting a universal value. Policies, question-and-answer collections, and operating manuals often need different strategies.
5.3 Add Interpretable Metadata
Every chunk should be associated with at least a document identifier, version, section path, source location, and access permissions. Effective dates, regions, and business categories may also be useful.
Retrieval can first return highly relevant chunks and then expand to their parent sections or neighboring paragraphs as needed. This balances precise matching with contextual completeness, but expanded content must still pass authorization checks.
6. Retrieval Augmentation: Combine Semantics, Keywords, and Applicability
Vector retrieval is effective at finding semantically similar content, but it may be less reliable for exact identifiers, abbreviations, specialized terms, or amounts. Keyword retrieval supports exact matching but can miss questions phrased differently from the source.
Enterprise applications therefore often need both.
6.1 Establish Scope Before Retrieval
User identity, organizational membership, document validity, and business scope should influence filtering as early as possible. Do not retrieve all sensitive material and rely on the model to ignore unauthorized content when answering.
If the retrieval system cannot provide sufficient permission filtering, use evaluated partitioning, isolation, or post-retrieval authorization checks. Ensure unauthorized content never enters model context, caches, or logs.
6.2 Rerank After Hybrid Retrieval
Semantic and keyword retrieval can generate separate candidate sets, followed by deduplication, fusion, and relevance ranking. Raw scores from different retrieval methods are usually not directly comparable and should not simply be added together without appropriate handling.
Ranking should consider not only relevance to the question, but also validity, source authority, and coverage of required conditions. For policy questions, a highly similar but obsolete passage should not outrank the current effective version.
6.3 Allow for Insufficient Evidence
The presence of retrieval results does not mean the evidence is sufficient. Check whether it covers the subject, time constraints, applicable parties, and exceptions.
When evidence is partial, answer the supported portion and identify the gaps. When essential evidence is missing, request clarification or state that the answer cannot be confirmed. Relevance thresholds can assist this decision, but they are not a general guarantee of factual truth.
7. Tool-Calling Protocols: Standardize Connections Without Replacing Security
Standardized connection mechanisms such as the Model Context Protocol (MCP) can help applications discover tools, access resources, and make structured calls. Their value lies in reducing repeated integration work—not in automatically providing reliability or secure authorization.
7.1 Make Tool Descriptions Clear and Verifiable
Each tool should define its purpose, input and output structures, failure conditions, and whether it has side effects. Read-only tools and tools that modify data should be managed separately.
Model-generated arguments are only proposed inputs. The server must still validate types, ranges, business rules, and caller permissions. Conforming to an input schema does not make an operation legitimate.
7.2 Establish Boundaries for High-Risk Actions
Operations such as modifying records, initiating payments, or deleting documents should require confirmation, approval, or additional validation according to their risk.
Confirmation should identify the actual target, key parameters, and possible consequences. A vague “Continue?” prompt is insufficient.
Write operations also require idempotency. Retrying after a network timeout should not create duplicate submissions. If the outcome is unknown, check the operation’s status before deciding whether to retry.
7.3 Limit Call Chains and Resource Use
Tool execution needs timeouts, call limits, concurrency limits, and failure handling to prevent the model from repeatedly cycling among tools.
Tool responses are also untrusted input. Even an internal API may return malicious text submitted by a user. Treat returned content as data, not as instructions that can alter system rules or permission boundaries.
8. Real-Time Search: Add Current Information, Not Just Search Snippets
Internal knowledge bases are well suited to stable information. Recent policies, public announcements, and market developments may require real-time search.
Here, “real-time” means retrieving currently accessible information on demand. It does not guarantee that the information itself is fully up to date.
8.1 Trigger Search According to the Question
Search may be appropriate when a question has explicit time requirements or internal sources lack the necessary external evidence. Questions containing internal secrets, personal information, or customer data should not send their raw contents to external search services.
Before searching, extract necessary keywords and remove sensitive details that do not need to leave the system. If the query cannot be performed without disclosure, stop that path and explain the limitation.
8.2 Verify the Underlying Page
Search snippets may be truncated or omit applicability conditions. For important conclusions, inspect the original page where possible and check publication dates, update dates, the publisher, and the full context.
Prioritize original publications and authoritative sources. Significant changes or disputed facts may warrant cross-checking against independent sources. Several websites republishing the same article do not constitute independent evidence.
8.3 Keep Internal and External Evidence in Their Proper Scope
Internal documents establish enterprise rules; public sources establish external facts. Neither should automatically substitute for the other.
If they conflict, explain the relevant versions, dates, and scopes, and clearly mark issues requiring human judgment.
Web fetching should also restrict accessible addresses and response sizes to prevent access to internal network resources, unsafe redirects, or oversized content. Text such as “ignore previous instructions” on a retrieved page is source data, not an instruction for the engine.
9. Context Assembly: Organize Evidence into Verifiable Answers
Before generation, deduplicate, condense, and rank the evidence rather than passing large volumes of similar passages to the model.
For each evidence item, retain a source identifier, document title, version or date, location anchor, and relevant text. Clearly distinguish system rules, user requests, and retrieved content.
Answer generation should follow these principles:
- Attach corresponding sources to factual conclusions where possible.
- Distinguish source facts, calculated results, and inferences.
- Do not present model memory as a fact verified through retrieval.
- Do not invent essential conditions when evidence is incomplete.
- State the time scope of the evidence for time-sensitive information.
Citations help users locate evidence, but do not automatically prove a conclusion. Post-generation checks can verify that citations exist, that the cited content supports the associated claims, and that important restrictions have not been omitted.
10. Evaluation and Deployment: From Answering Questions to Sustainable Operation
A production system should evaluate document processing, retrieval, and answer generation separately.
At the document-processing layer, assess parsing completeness, table recovery, duplicate-data rates, and incremental synchronization correctness.
At the retrieval layer, assess whether essential evidence enters the candidate set, whether ranking is appropriate, and whether permission filtering works.
At the answer layer, assess factual consistency, citation accuracy, completeness of conditions, and the quality of responses when evidence is insufficient.
Test sets should include ordinary questions as well as unanswerable questions, obsolete policies, cross-department access restrictions, ambiguous terms, complex tables, and malicious instructions. Easy examples alone cannot establish system quality.
Operations also require monitoring latency, failure rates, context consumption, and per-request cost, with timeouts and fallback strategies. If external search fails, for example, the system may still answer from existing evidence, but must clearly state that time-sensitive information was not verified.
Logs and caches should follow data-minimization principles. Sensitive workloads should not default to recording complete prompts and tool responses. Cache reuse must account for user permissions, document versions, and expiration so that outdated or unauthorized answers are not served.
11. Implementation Sequence: Build a Trustworthy Loop Before Expanding Automation
A safer starting point is a narrowly scoped, low-risk internal knowledge use case backed by authoritative documents. First establish a complete loop covering ingestion, parsing, retrieval, citations, and evaluation.
Once foundational quality is stable, add read-only tools and real-time search. Validate routing, source selection, and failure handling. Introduce operations with side effects gradually, with confirmation, approval, idempotency, and audit controls in place.
The strength of an enterprise LLM engine is not the number of capabilities it connects. It is whether the system can consistently answer four questions:
- Where does the evidence come from?
- Is the information still valid?
- Is the current user allowed to access it?
- Does the evidence actually support the conclusion?
Embedding these checks into both the data pipeline and the execution pipeline is the foundation for a reliable enterprise LLM application.
