Subtitle: Understanding Retrieval-Augmented Generation, from document processing and vector search to reliable, source-grounded answers.
One of the common challenges when building an AI application is helping it answer questions about information that is specific to a company, project, or technical domain.
A general-purpose language model may understand programming concepts, software architecture, and engineering terminology. But it may not know the latest internal design document, a company's operating procedures, a product's specific configuration, or a technical decision made last week.
One approach is to train or fine-tune a model using additional data. However, that is not always necessary—or the best first choice.
A practical alternative is to retrieve relevant information from an external knowledge source and provide it to the model when answering a question.
This architecture is called Retrieval-Augmented Generation (RAG).
RAG is particularly useful for enterprise knowledge assistants, technical research platforms, customer-support systems, document analysis, and applications that need to answer questions using information that changes over time.
Let's examine how it works and what matters when implementing it.
1. What exactly is RAG?
RAG combines two capabilities:
Retrieval: Finding relevant information from a collection of documents or other knowledge sources.
Generation: Using a language model to formulate an answer based on the retrieved information and the user's question.
Without retrieval, a model primarily relies on information learned during training and the context supplied in the current request.
With RAG, the application searches an external knowledge base and supplies relevant passages as additional context.
For example, imagine an engineering company has hundreds of technical manuals, design specifications, and troubleshooting reports.
An engineer asks:
"What is the recommended operating temperature range for this component according to our latest specification?"
A RAG application can search the approved documents, retrieve passages containing the relevant specification, and ask the model to answer using those passages.
The answer can also identify its source so that the engineer can verify the information.
The key advantage is that the application does not need to place every document into every request. It retrieves the information that is relevant to the current question.
2. How does a RAG system work?
A typical RAG architecture has two main processes: preparing the knowledge base and answering questions.
Process A: Preparing the knowledge base
Step 1 — Collect the documents
The application receives information from sources such as PDFs, Word documents, technical manuals, web pages, databases, and approved internal repositories.
The supported formats depend on the ingestion pipeline.
Step 2 — Extract and clean the content
Documents must be converted into usable text or structured data.
This step requires care. PDFs may contain tables, diagrams, headers, footers, or multi-column layouts that cannot always be interpreted correctly by simple text extraction.
For engineering documents, losing a table heading or separating a value from its unit can change the meaning of the information.
Step 3 — Split the content into chunks
Large documents are divided into smaller sections called chunks.
Each chunk should contain enough information to be understood while remaining small enough to retrieve efficiently.
Step 4 — Generate embeddings
An embedding model converts each chunk into a numerical vector that represents aspects of its semantic meaning.
These vectors can help identify passages related to a question even when the wording differs.
Step 5 — Store the chunks and their metadata
The application stores the chunk text, its embedding, and useful metadata in a suitable database or retrieval system.
Metadata might include the document title, page number, version, publication date, project, and access-control information.
Process B: Answering a question
Step 6 — Process the user's question
The application receives the question and, when necessary, rewrites or expands it to improve retrieval.
Step 7 — Retrieve relevant information
The system searches the knowledge base using semantic search, keyword search, or a combination of both.
Step 8 — Select and organise the evidence
The most relevant passages are selected, optionally reranked, and assembled into a context for the language model.
Step 9 — Generate the answer
The model receives the question and retrieved evidence, then produces a response according to the application's instructions.
Step 10 — Present the answer with sources
Where possible, the application displays source references so the user can inspect the original document and verify important claims.
This process creates a bridge between an AI model's language capabilities and an organisation's own information.
3. Why chunking is an important design decision
Chunking may appear to be a simple preprocessing step, but it can significantly influence retrieval quality.
Consider a technical manual containing a section about pressure limits. If the heading is stored in one chunk and the actual limits in another, a search might retrieve the numbers without the context needed to interpret them.
Likewise, a chunk that combines unrelated topics may match a question because it contains one relevant phrase while including substantial irrelevant material.
There are several common approaches.
Fixed-size chunking: Splits content according to a target size, often measured in tokens, with optional overlap between adjacent chunks.
Structure-aware chunking: Uses document boundaries such as headings, paragraphs, sections, or table boundaries.
Semantic chunking: Uses changes in meaning or topic to determine where one chunk should end and another should begin.
For structured technical documentation, preserving section headings and relationships between tables and their explanations can be particularly valuable.
There is no universally optimal chunk size. The right choice depends on document structure, question types, the embedding model, the language model's context capacity, and retrieval performance.
A sensible starting point is to preserve meaningful document sections, then evaluate several chunking strategies against a representative set of real questions.
4. Vector search is powerful, but it is not enough
Embeddings allow a system to compare the semantic similarity of a question and document passages.
For example, a question asking about "reducing application response time" might retrieve a passage discussing "latency optimisation," even if the wording differs.
However, vector search has limitations.
Exact identifiers, product codes, error messages, version numbers, and specialised terminology may be better handled by keyword or lexical search.
Suppose an engineer searches for a specific error code such as ERR-1042. A keyword search can identify an exact match directly, whereas semantic similarity alone may not reliably prioritise that passage.
This is why many practical systems use hybrid search, combining semantic retrieval with keyword-based retrieval.
The results can then be combined and, where useful, reranked using a model that evaluates how relevant each passage is to the complete question.
The engineering objective is not to choose the most sophisticated search technology. It is to retrieve the evidence that best answers the user's question.
5. RAG does not automatically prevent hallucinations
One of the most common misconceptions is that adding retrieval makes an AI application factually reliable.
RAG can improve grounding, but it does not guarantee correctness.
A system can still fail in several ways:
It retrieves the wrong document.
It retrieves an outdated specification.
It misses the most important passage.
It provides too much irrelevant context.
The model misinterprets the retrieved information.
The answer includes claims that are not supported by the evidence.
The source documents themselves contain incorrect information.
Consider a question about a product's current operating limits. The knowledge base contains two specifications: one from last year and another from the latest approved revision.
If the retrieval system selects the older document, the model may produce a well-written but outdated answer.
This is not necessarily a generation problem. It may be a document-versioning or retrieval problem.
A dependable RAG application should therefore:
Prioritise authoritative and approved sources.
Track document versions and publication dates.
Retrieve evidence relevant to the specific question.
Instruct the model to distinguish supported facts from missing information.
Provide source references where possible.
Allow the application to return an uncertainty response when evidence is insufficient.
The last point is especially important. A system should be allowed to say that it could not find sufficient evidence rather than inventing an answer.
6. Metadata and document freshness matter
A knowledge base is not simply a collection of text and vectors.
The information surrounding each chunk often determines whether it is useful and trustworthy.
Useful metadata may include:
Document identifier and title.
Page number and section heading.
Revision or version number.
Approval status.
Effective date.
Project or department.
Content type.
Applicable access permissions.
This metadata can support filtering, citations, version selection, and access control.
For example, a question about a current company policy should normally prioritise the latest approved version rather than an archived draft.
When a document changes, the ingestion pipeline should identify which chunks and embeddings need to be updated or removed. Otherwise, the knowledge base may return stale information even though the source repository is correct.
For frequently changing information, a combination of document retrieval and direct database queries may be more appropriate than relying exclusively on indexed document chunks.
7. Secure RAG requires access control at retrieval time
Imagine a knowledge platform serving multiple organisations.
Each organisation uploads its own documents. Users should be able to search their organisation's material, but they must not retrieve another organisation's confidential information.
The retrieval layer must enforce this boundary.
A secure design authenticates the user, determines the permitted scope of access, and applies those restrictions before returning candidate documents to the model.
The same principle applies to internal company assistants. A user should not be able to retrieve confidential HR, finance, or project information merely because it is present in the knowledge base.
Access restrictions must be enforced in the application and retrieval system. Instructions telling the language model not to disclose certain information are not a substitute for authorisation controls.
This becomes especially important when using shared vector indexes, caches, conversation histories, and background ingestion jobs.
8. How do we measure RAG quality?
A RAG application should be evaluated as a pipeline, not merely by reading a few generated answers.
There are at least three important areas to examine.
Retrieval quality
Did the system find the right information?
Useful measures include:
Recall@k: How often does the relevant evidence appear among the top (k) retrieved results?
Precision@k: How much of the retrieved material is relevant?
Mean Reciprocal Rank (MRR): How highly does the first relevant result appear?
Context relevance: Does the retrieved context address the question?
These metrics require suitable relevance labels or reference evidence.
Answer quality
Did the model use the retrieved evidence correctly?
Evaluate factual correctness, completeness, relevance, source support, and whether the model appropriately acknowledges missing information.
End-to-end quality
Did the application successfully solve the user's task?
For example, did the user receive a correct answer, with an appropriate source reference, within an acceptable response time and cost?
Create a test set of realistic questions and known supporting documents. Include straightforward questions, questions requiring multiple passages, ambiguous requests, outdated documents, and questions whose answers are not present in the knowledge base.
Then use the results to identify whether failures originate in document processing, retrieval, context construction, or generation.
Without this separation, developers may repeatedly adjust the prompt when the actual problem is poor retrieval.
9. When should you use RAG—and when should you not?
RAG is useful when an application needs to answer questions using a large or changing body of external knowledge.
Good use cases include:
Internal knowledge assistants.
Technical documentation search.
Research-paper discovery and summarisation.
Product manuals and troubleshooting.
Customer-support knowledge bases.
Policy and procedure assistants.
However, RAG is not the answer to every AI problem.
If an application needs an exact account balance, inventory quantity, or current order status, a direct query to the authoritative database may be more reliable than retrieving a document that mentions the value.
If the task involves complex calculations, a deterministic calculation engine may be more appropriate than asking a language model to calculate from retrieved text.
Fine-tuning may be useful for adapting model behaviour, style, or task-specific patterns, although it is not generally the best mechanism for keeping frequently changing factual knowledge current.
In many systems, the best architecture combines several approaches: RAG for document knowledge, direct API calls for live data, conventional code for deterministic operations, and a language model for interpreting requests and presenting results.
Conclusion: Build the knowledge pipeline, not just the chatbot
RAG is an important pattern for connecting AI models to information that lives outside their original training data.
But a successful implementation requires much more than generating embeddings and placing them in a vector database.
Document quality, chunking strategy, retrieval methods, metadata, source authority, access control, context construction, and evaluation all influence the final result.
A useful engineering principle is:
Retrieve the right evidence, preserve its context, generate an answer grounded in that evidence, and make the source verifiable.
Start with a small collection of representative documents and real questions. Measure retrieval quality. Investigate failures. Improve the pipeline before scaling to thousands of documents and users.
The real value of RAG is not that it makes an AI model know everything.
It is that it provides a controlled way for an AI application to find, use, and explain information from the knowledge sources that matter to its users.