Retrieval-Augmented Generation Pattern
local graph
Chapter 4 — Retrieval-Augmented Generation Pattern
Section titled “Chapter 4 — Retrieval-Augmented Generation Pattern”In this chapter, we explore retrieval-augmented generation (RAG), a technique that enhances language models by integrating real-time retrieval from external data sources. While generative models can produce fluent text, they often suffer from knowledge limitations, outdated information, and hallucinations. RAG mitigates these issues by retrieving the most relevant external information before generating responses, ensuring accuracy, transparency, and adaptability in dynamic environments.
We will cover the following key topics:
- Introduction to retrieval-augmented generation
- Foundations of retrieval mechanisms
- Common retrieval algorithms and data structures
- Embeddings for enhanced retrieval
- Ensuring attribution, reducing hallucinations, and facilitating revisions
Bookmark
Technical requirements
Section titled “Technical requirements”Before diving into RAG implementation, ensure you have the necessary hardware and software set up.
The following are the hardware requirements.
You can run the examples in this chapter on:
- Google Colab (recommended for easy access to GPUs)
- A local machine (if you have the required hardware)
For those running locally, the recommended specifications are:
- CPU: Intel i7/AMD Ryzen 7 (or equivalent)
- RAM: At least 16 GB (32 GB recommended for large-scale retrieval)
- GPU: Optional, but recommended for deep learning tasks:
- Google Colab provides free GPUs (T4, P100, or A100, depending on availability)
- For local use: NVIDIA RTX 3090 (or higher)
- Google Colab provides free GPUs (T4, P100, or A100, depending on availability)
The following are the software requirements:
- Operating system: Ubuntu 20.04+/Windows 11/macOS 12+
- Python version: 3.8 or higher
- Key libraries and dependencies:
transformers(for LLMs)faiss(for vector search)langchain(for retrieval pipelines)sentence-transformers(for embeddings)chromadb/pinecone(for vector storage)pypdf(for document processing)bm25(for sparse retrieval)
You can find the complete code for this chapter at https://github.com/PacktPublishing/LLMs-in-Enterprise.
Bookmark
Introduction to retrieval-augmented generation
Section titled “Introduction to retrieval-augmented generation”Modern intelligent generation systems aim to produce high-quality, contextually relevant outputs. While advanced generative models can craft fluent, coherent text, one critical challenge remains: these systems inherently rely on patterns learned from their training data and often cannot reliably access newer or more domain-specific information on demand due to their knowledge cut-off: a fixed point in time after which the model is unaware of new data.
As a result, they might provide outdated facts, overlook crucial enterprise knowledge assets, or struggle with specialized terminologies and use cases. RAG emerges as a solution to this problem, bridging the gap between powerful generative capabilities and the dynamic, ever-evolving information landscapes enterprises inhabit
RAG systems integrate a retrieval mechanism as part of the generation pipeline. Rather than depending solely on a generative model’s fixed parameters, a RAG system queries external data sources such as databases, document repositories, or knowledge graphs to fetch the most relevant context before producing a final output. By doing so, RAG ensures that the LLM’s responses are not only linguistically sound but also anchored in up-to-date, verifiable, and attributed information. The retrieval step effectively serves as an information lens, narrowing down the subset of the external corpus that best supports the user’s query. The generative step then leverages this retrieved context to produce a more accurate and contextually grounded answer.
The RAG paradigm has rapidly gained traction, especially as enterprises seek methods to tame large internal knowledge bases and deliver timely, consistent, and factually grounded content. The following sections will dissect the motivations behind RAG, highlight the importance of external context, explore how retrieval overcomes inherent limitations in generative models, discuss the reduction of hallucinations through attributed sources, and underscore how RAG systems align with modern enterprise knowledge management strategies.
Understanding the need for external information sources
Section titled “Understanding the need for external information sources”At its core, a generative model is limited by its training data. No matter how extensive its training corpus, a generative model cannot contain every fact, policy update, or new development in a specialized field. This limitation becomes starkly evident in scenarios where the information required to answer a query was not available at training time or is deeply domain-specific and stored in proprietary documents. Without access to external data, the system must rely solely on internal, pre-learned representations, which can lead to partial, outdated, or outright incorrect responses.
Figure 4.1 below illustrates the sequence of operations in a RAG system. When a user submits a query, the system first retrieves relevant documents from an external knowledge source before passing both the query and the retrieved context to the generative model. The model then generates a response based on this augmented context, ensuring factual accuracy and reducing hallucinations. This process enhances the model’s ability to provide well-informed and up-to-date answers.

Figure 4.1: Sequence diagram of a RAG system, illustrating how external data is retrieved and integrated into the generation process to enhance accuracy and reduce hallucinations
For instance, consider a technical support tool designed to assist employees in a large manufacturing firm. This tool might need to reference recent maintenance logs, updated safety regulations, or newly released product manuals. These details change frequently and cannot be feasibly encoded into the model’s internal memory every time they are updated. Similarly, a legal research assistant might need to reference the latest court rulings or changes in regulatory codes. Without external data, the system would be unable to incorporate this fresh information.
Beyond recency, domain specificity is another crucial factor. Organizations often maintain vast libraries of documents, internal wikis, whitepapers, archived emails, or standard operating procedures. Storing all such content directly in a model’s weights is both impractical and unnecessary. With RAG, the model doesn’t need to memorize everything. Instead, it can look things up as needed, retrieving only the relevant pieces of information. This modular approach not only improves accuracy but also ensures that the system can dynamically adapt to new data and evolving knowledge bases.
So, accessing external information is just one part of the equation. Another key challenge is managing context effectively. Generative models typically have a limited context length, limiting how much information they can process at once. Simply increasing the context window isn’t always practical due to the substantial rise in token and computational costs, driven in part by the quadratic scaling of attention mechanisms with respect to context length.
This is where retrieval makes a difference. Instead of overloading the model with unnecessary data, it pulls only the most relevant details. This keeps responses precise, efficient, and focused, ensuring the model generates accurate answers without wasted computation.
Overcoming context limitations with retrieval
Section titled “Overcoming context limitations with retrieval”One of the fundamental constraints in generative models is the concept of context windows or attention spans. Even state-of-the-art language models are constrained by a fixed context window, meaning they can only process a limited number of tokens at a time. If a user query is complex and requires substantial background, simply stuffing more text into the model’s context window may not be feasible or effective toward helping the model respond correctly. This is where retrieval shines.
In a RAG workflow, when a user submits a query, the retrieval engine searches through a large corpus to identify and return only the most pertinent documents or passages. These retrieved snippets serve as condensed and highly relevant document chunks, focusing the generative attention. Thus, instead of drowning the generation phase in an overwhelming ocean of extraneous data, RAG ensures the LLM works with a well-curated “knowledge snippet” that aligns precisely with the user’s request.
For example, imagine a scenario where a finance professional asks, “What was the revenue growth for our European division in Q2 of last year?” Without retrieval, the system either tries to remember if it “knows” that information (likely failing to answer correctly if it was never part of its training) or returns a generic answer. With retrieval, however, the system queries a financial database or a set of quarterly reports, finds the relevant spreadsheet or performance summary, and is able to output just the necessary numbers and commentary. This carefully selected portion of the source content, often just a few sentences, provides the essential context the model needs to generate a precise and well-supported response.
Furthermore, by bounding the amount of data given to LLMs, retrieval helps maintain cost efficiency. Since generating text from large amounts of input can be computationally expensive, focusing on the most relevant context reduces both latency and resource usage. The outcome is a more cost-efficient system that provides accurate, contextually rich answers.
Retrieval doesn’t just improve accuracy; it also strengthens trust with an enterprise’s customers. Even the best generative models can hallucinate, producing plausible but incorrect statements. In high-stakes environments, misinformation isn’t just inconvenient; it can be costly to the end users, leading to misleading decisions and affecting a company’s reputation.
By retrieving only the most relevant information from external sources, RAG overcomes context window limitations. It reduces the need to load entire documents into the prompt, cutting down on token usage and improving response time, while still grounding the model’s answers in verifiable data.
Reducing hallucinations and ensuring attributable information
Section titled “Reducing hallucinations and ensuring attributable information”A widely known shortcoming of generative models is their tendency to hallucinate to produce plausible-sounding but factually incorrect statements. Hallucinations can be as benign as mixing up dates or as harmful as providing dangerously inaccurate technical guidance. In enterprise contexts, where the cost of misinformation can be high, controlling hallucinations is paramount.
Hallucinated outputs not only undermine user trust but can also expose organizations to reputational damage, legal risk, and operational failures. For example, in 2023, a lawyer submitted a legal brief generated by ChatGPT that cited non-existent court cases, highlighting how AI errors can lead to serious professional and legal consequences.
RAG addresses this by grounding the generation process in retrieved data. Instead of relying solely on learned patterns, the system bases its output on concrete, verifiable sources. When a RAG system produces a statement, it can cite the retrieved documents that informed it. This chain of evidence serves two crucial functions:
- Verifiability: Users or auditors can trace statements back to their source documents, ensuring that outputs are grounded in identifiable and trustworthy data. This ability to verify claims supports data provenance and governance practices, which is critical for regulatory compliance, auditability, and maintaining organizational accountability. If a claim seems suspicious, it can be checked against the original repository, fostering trust and transparency.
- Accountability: By ensuring that every generated piece of information has a corresponding reference, the system encourages high-quality output. The retrieval mechanism acts like a filter, bringing only relevant and accurate data into the generation step. If the documents themselves are reliable, the final answer is more likely to be correct.
But even when errors occur, having traceable inputs ensures accountability: it becomes easier to identify whether the issue stems from flawed documents, unclear prompts, weak examples, or model misinterpretation. This visibility enables teams to take corrective actions, such as improving data quality, refining prompts, adjusting few-shot examples, or incorporating user feedback, to strengthen the overall performance of the RAG system.
This attribution mechanism is invaluable in regulated industries such as finance, healthcare, or law, where decisions often must be backed by reliable evidence. The presence of a “retrieval layer” empowers organizations to adopt generation AI models without forfeiting the rigor and compliance that such professional environments demand.
Moreover, reducing hallucinations improves user trust. When end users see that answers cite company website links, official reports, or recognized industry standards, their confidence in the system’s reliability grows. Over time, this trust can lead to broader adoption to streamline more compound processes for enterprises or end users, reinforcing the value proposition of RAG.
Enterprises often grapple with information sprawl. Documents exist in multiple formats: PDFs, spreadsheets, knowledge base articles, intranet pages, and more scattered across disparate systems. Employees struggle to find up-to-date procedures, product details, or compliance rules, resulting in inefficiencies and potential errors. Traditional search engines help but are limited: they can return a list of documents but do not synthesize or contextualize their content.
RAG effectively augments the capabilities of a traditional enterprise search. Instead of only providing links or document titles, a RAG system uses the retrieved information to generate a synthesized, coherent response. This approach transforms information retrieval (IR) from a passive directory of files into an active adviser who can answer questions, provide explanations, and outline procedures with clarity and precision.
In practice, this means that an employee can ask a question like, “What are the latest updates to our internal security protocol?” The RAG system retrieves the relevant internal guidelines or memos and then produces a summary. The employee no longer needs to sift through lengthy documents manually; the RAG pipeline does the heavy lifting, surfacing the essential facts in a directly consumable format.
Additionally, RAG can help maintain institutional memory. As staff change roles or leave the company, the knowledge they possess may become buried in archives. A RAG system can comb through these archives and present relevant historical insights to new team members. This ensures continuity and reduces knowledge attrition, empowering the enterprise to leverage its information assets more fully.
Finally, as regulatory landscapes and market conditions shift, enterprises need agile tools. RAG systems can be updated effortlessly: whenever new documents are added, the retrieval index can be refreshed, ensuring that the generative step always utilizes the latest standards or product changes. There is no need to retrain the entire LLM from scratch. This decoupling of general language capabilities from specialized domain content yields a more flexible and maintainable architecture.
For RAG to function effectively, it needs a strong retrieval backbone. Enterprises generate vast amounts of data, but surfacing the right information is a complex challenge. Traditional search methods often fall short, returning lists of documents without context.
RAG changes this by leveraging advanced retrieval techniques. Before a generative model can produce an informed response, it must locate the most relevant content. The next section delves into how retrieval systems work, from classic search algorithms to modern AI-driven approaches, ensuring that RAG-powered solutions utilize the most relevant and efficient content from enterprise data.
To build a reliable RAG system, the retrieval process must be both efficient and precise, ensuring that only the most relevant information is surfaced. The next section explores the foundations of retrieval mechanisms, tracing their evolution from traditional search algorithms to advanced AI-driven retrieval methods that power modern RAG pipelines.
Bookmark
Foundations of retrieval mechanisms
Section titled “Foundations of retrieval mechanisms”Modern enterprises rely heavily on their information assets: documents, databases, wikis, emails, reports, technical specifications, and more. Yet, accessing the right piece of information at the right time remains a non-trivial challenge. IR is the field dedicated to this problem: how do we find and present relevant items from large repositories in response to user queries?
This section explores the foundational concepts of retrieval, from its historical roots to cutting-edge algorithms, and shows how these principles improve the accuracy, efficiency, and transparency of RAG pipelines.
Historical context of information retrieval
Section titled “Historical context of information retrieval”IR as a formal discipline predates the era of LLMs by decades. Early IR systems, developed in the 1950s and 1960s, were grounded in library science and relied on the manual indexing of documents. As the amount of textual data exploded, first with digital archives and then with the World Wide Web, IR techniques became more automated and sophisticated.
By the early 1990s, the advent of web search engines like AltaVista and later Google propelled IR into the mainstream. Seminal techniques such as Term Frequency–Inverse Document Frequency (TF-IDF) weighting and the vector space model guided the design of retrieval systems for many years. Evaluations were conducted through group/community of researchers from Text REtrieval Conference (TREC), which helped establish best practices and metrics that endure today.
Over time, IR systems evolved from simple keyword matching to more nuanced approaches capable of considering synonyms, semantic meaning, user intent, and context. Today, retrieval methods draw from natural language processing and machine learning, culminating in dense embedding-based retrieval that can capture subtle semantics. Each of these developments—keyword-based search, statistical weighting, and semantic embeddings—set the stage for the modern retrieval mechanisms used in RAG systems.
Key concepts in IR
Section titled “Key concepts in IR”At the heart of IR are a few fundamental concepts:
- Document representation: Each item (document, snippet, and paragraph) in a collection must be represented in a way that is searchable. This representation can be a bag of words, a vector of token frequencies, or a dense embedding.
- Query processing: A user’s query, e.g., “Annual revenue of our European branch,” must be transformed into a form compatible with the document representations. In keyword-based IR, the query is just a set of terms. In embedding-based IR, the query is embedded into a matrix of word vectors.
- Ranking: Given a query, the retrieval system assigns a relevance score to each document, and then returns the top-ranked items to the user (or the RAG pipeline’s generative component). Ranking algorithms may consider term frequency, semantic similarity, or other relevance signals.
- Evaluation: IR systems are judged by how well their ranked lists match the user’s information needs. Metrics like precision, recall, and discounted cumulative gain (evaluates the relevance of retrieved results, with higher-ranked results receiving more weight) measure how effectively a system satisfies queries.
These concepts persist across retrieval paradigms, sparse or dense, lexical or semantic.
Sparse vs. dense retrieval strategies
Sparse retrieval (also called term-based retrieval) relies on explicit lexical features. For example, consider a dictionary-like representation where each document is indexed by the words it contains. A query is matched against documents by counting overlapping terms. Classic engines like those powered by inverted indexes and TF-IDF are prime examples of sparse retrieval.
Dense retrieval uses continuous vector representations (embeddings). Instead of indexing documents by discrete terms, each document is represented as a vector in a high-dimensional space. A query, similarly transformed into a vector, retrieves documents whose embeddings are closest in terms of a distance metric, such as Euclidean or cosine similarity. Dense retrieval captures semantic similarity rather than just lexical overlap. For example, queries like “What is the income in Q2?” can match documents mentioning “second quarter revenue” even if the words don’t match exactly.
Common retrieval algorithms and data structures
Section titled “Common retrieval algorithms and data structures”Retrieval performance hinges on choosing the right algorithms and data structures. At scale, searching millions of documents or more requires efficient indexing and querying methods.
Let’s look at a few common retrieval algorithms and data structures.
Inverted indexes
Section titled “Inverted indexes”The inverted index is a foundational data structure for sparse retrieval. It maps each term in the vocabulary to a sorted list of documents containing that term. For instance, consider a small corpus of three documents:
- d1: “annual revenue growth in europe”
- d2: “europe sales stable last quarter”
- d3: “quarterly report on growth and revenue”
The inverted index might look like this:
- “annual” -> [d1]
- “revenue” -> [d1,d3]
- “growth” -> [d1,d3]
- “europe” -> [d1,d2]
- “sales” -> [d2]
- “quarter” -> [d2]
- “quarterly” -> [d3]
- “report” -> [d3]
- “and” -> [d3]
A query like “europe revenue” retrieves documents by intersecting the postings lists: “europe” -> [d1,d2]; “revenue” -> [d1,d3]; and so on. Intersection yields d1 as most relevant, with d2 and d3 also receiving high scores but slightly lower than d1.
Inverted indexes enable fast Boolean filtering and ranking, forming the core of classical search engines. Here is a code example:
# Example: Building a simple inverted index and querying itdocuments = { 1: "annual revenue growth in europe", 2: "europe sales stable last quarter", 3: "quarterly report on growth and revenue"}def tokenize(text): return text.lower().split()# Build inverted index: term -> sorted list of doc_idsinverted_index = {}for doc_id, text in documents.items(): terms = tokenize(text) for term in terms: if term not in inverted_index: inverted_index[term] = [] inverted_index[term].append(doc_id)# Querying the inverted index: a simple AND queryquery = "europe revenue"query_terms = tokenize(query)# Get postings lists for each termposting_lists = [set(inverted_index.get(term, []))for term in query_terms if term in inverted_index]if posting_lists: candidate_docs = set.intersection(*posting_lists)else: candidate_docs = set()print("Query:", query)print("Candidate documents:", candidate_docs)Here is the output:
Query: europe revenue Candidate documents: {1}
Since doc_id 1 contains both “europe” and “revenue,” it is the most relevant match based on the inverted index structure. While doc_id 3 also contains “revenue” and doc_id 2 contains “europe,” only doc_id 1 includes both terms, making it the strongest candidate for retrieval. So, based on that, doc_id 1 is a strong candidate for our query.
Approximate nearest neighbor search
Section titled “Approximate nearest neighbor search”In dense retrieval, we must find the nearest vectors to a query vector. A naive approach requires comparing the query vector against every document vector, which is a costly operation at a large scale. Approximate nearest neighbor (ANN) algorithms solve this by trading exactness for speed. They organize vectors into data structures like trees, graphs, or quantized clusters so that we can skip large portions of the dataset.
For example, algorithms such as Hierarchical Navigable Small World (HNSW) and FAISS’s IVF-PQ index cluster the vector space, allowing sublinear search time. Given the query vector, ANN search identifies a small subset of candidates likely to be close by using ANN search, which quickly filters vectors based on similarity scores before performing more precise comparisons. It then refines the search within that subset. Here is example code:
import numpy as npimport faiss# Create a random dataset of embeddingsnp.random.seed(42)dimension = 8num_docs = 10data = np.random.random((num_docs, dimension)).astype('float32')# Build a FAISS index (exact L2 index for demonstration)index = faiss.IndexFlatL2(dimension)index.add(data)# Query vectorquery_vec = np.random.random((1, dimension)).astype('float32')# Perform ANN search: find top 3 nearest neighborsk = 3distances, indices = index.search(query_vec, k)print("Query Vector:\n", query_vec)print("Indices of nearest neighbors:", indices)print("Distances:", distances)The following is the expected output:
Query Vector:
[[0.86310345 0.6232981 0.33089802 0.06355835 0.31098232 0.32518333
0.72960615 0.63755745]]
Indices of nearest neighbors: [[2 3 7]]
Distances: [[0.7740041 0.8021247 1.0303653]]
This example demonstrates how FAISS efficiently identifies the top 3 vectors closest to the query based on L2 distance. Even in a simple setup, we see how ANN search dramatically reduces the number of comparisons required, enabling fast, scalable retrieval in dense vector spaces.
Together with sparse retrieval methods like inverted indexes, ANN algorithms are key building blocks for modern RAG systems, balancing precision and performance across different types of data.
Hybrid approaches (term-based and embedding-based)
Section titled “Hybrid approaches (term-based and embedding-based)”No single technique is universally optimal. Hybrid retrieval combines sparse and dense methods, merging the strengths of both. A hybrid approach might first run a dense embedding search to capture semantic matches, then filter or re-rank the results with a sparse method to ensure keyword precision, and vice versa. This layered strategy reduces the computational cost compared to running a dense search across the entire corpus, since it narrows down candidate documents early and avoids expensive full-scale similarity comparisons. By blending these strategies, we get robust retrieval that handles both exact matches and nuanced synonyms.
Here is example code:
Example: Combining sparse and dense retrieval results
Section titled “Example: Combining sparse and dense retrieval results”Install required libraries if needed
Section titled “Install required libraries if needed”# !pip install rank_bm25 sentence-transformersfrom rank_bm25 import BM25Okapifrom sentence_transformers import SentenceTransformer, utilimport numpy as npcorpus = [ "annual revenue growth in europe", "europe sales stable last quarter", "quarterly report on growth and revenue"]# Sparse retrieval with BM25tokenized_corpus = [doc.lower().split() for doc in corpus]bm25 = BM25Okapi(tokenized_corpus)# Dense retrieval with sentence-transformersmodel = SentenceTransformer('all-MiniLM-L6-v2')doc_embeddings = model.encode(corpus, convert_to_tensor=True)query = "european quarterly revenue"query_embedding = model.encode(query, convert_to_tensor=True)# Dense retrieval scoresdense_scores = util.cos_sim(query_embedding, doc_embeddings)[0].cpu().numpy()# Sparse retrieval scoressparse_scores = bm25.get_scores(query.lower().split())# Combine scores (simple linear combination)combined_scores = dense_scores + sparse_scores# Sort documents by combined scoreranked_indices = np.argsort(-combined_scores) # descending orderprint("Query:", query)print("Sparse Scores:", sparse_scores)print("Dense Scores:", dense_scores)print("Combined Scores:", combined_scores)print("\nRanked Documents by combined score:")for idx in ranked_indices: print(f"Doc {idx}: {corpus[idx]}")The following is the expected output:
Query: european quarterly revenue Sparse Scores: [0.07075497 0. 0.54872484] Dense Scores: [0.7896244 0.6044986 0.6067592] Combined Scores: [0.86037936 0.60449862 1.15548403] Ranked Documents by combined score: Doc 2: quarterly report on growth and revenue Doc 0: annual revenue growth in europe Doc 1: europe sales stable last quarter
The script demonstrates a hybrid retrieval approach by combining BM25 (sparse retrieval) and sentence-transformers (dense retrieval). Merging scores from both methods ensures that the results capture both exact keyword matches and semantically similar content. This approach is particularly effective in scenarios where precise terminology matters, but broader contextual understanding is also necessary. By balancing these retrieval strategies, hybrid methods provide more robust, accurate, and flexible search capabilities, making them well suited for real-world enterprise applications.
Evaluating retrieval quality
Section titled “Evaluating retrieval quality”To measure how well our retrieval system works, we must evaluate it on representative queries. Proper evaluation ensures we build systems that truly help users and support downstream RAG tasks effectively.
Retrieval is arguably the most critical component of RAG pipelines. Modern LLMs are adept at reasoning over small, well-structured inputs, but their effectiveness hinges entirely on the quality and relevance of the retrieved context. The right retrieval and chunking strategies ensure the model sees the right information at the right time.
Precision, recall, and relevance metrics
Section titled “Precision, recall, and relevance metrics”Precision refers to the fraction of retrieved documents that are relevant. Formally, if R is the set of retrieved documents and G is the set of truly relevant documents, then:

Recall is the fraction of all relevant documents that are actually retrieved:

In enterprise settings, we are often interested in the mean average precision (MAP) or normalized discounted cumulative gain (nDCG) to handle ranked results and graded relevance levels. These metrics account for not only whether relevant documents are retrieved but also where they appear in the ranking.
The following example code illustrates how precision and recall are computed in practice. Suppose a query has two truly relevant documents (IDs 1 and 3), and the system retrieves three documents (IDs 1, 2, and 4). The code calculates precision as the ratio of relevant retrieved documents (1) to total retrieved documents (3), yielding 0.33. Recall is the ratio of relevant retrieved documents (1) to all relevant documents (2), resulting in 0.50. This demonstrates how even a partial match impacts both metrics:
# Suppose we have a set of truly relevant document IDs for a particular query:relevant_docs = {1, 3}# The system retrieves a ranked list of documents:retrieved_docs = [1, 2, 4] # for exampleprecision = len(set(retrieved_docs) & relevant_docs) / len(retrieved_docs)recall = len(set(retrieved_docs) & relevant_docs) / len(relevant_docs)print("Relevant docs:", relevant_docs)print("Retrieved docs:", retrieved_docs)print(f"Precision: {precision:.2f}")print(f"Recall: {recall:.2f}")The following is the expected output:
Relevant docs: {1, 3} Retrieved docs: [1, 2, 4] Precision: 0.33 Recall: 0.50
This example highlights the inherent trade-off between precision and recall. A high-precision system minimizes irrelevant results but risks missing critical information, while a high-recall system ensures comprehensive retrieval at the expense of noise. In enterprise contexts, balancing these metrics is essential, for instance, prioritizing precision in legal compliance scenarios to avoid errors, or emphasizing recall in exploratory research to capture all potential insights. These foundational metrics set the stage for addressing enterprise-specific evaluation considerations, where domain relevance, scalability, and freshness further refine retrieval performance.
Enterprise-specific evaluation considerations
Section titled “Enterprise-specific evaluation considerations”Enterprises have unique needs. Beyond standard IR metrics, organizations may consider:
- The coverage of specific domains: Does the retrieval perform well for compliance documents, financial reports, or engineering blueprints?
- Latency and scalability: A model might achieve high accuracy but be too slow to handle thousands of queries per minute.
- The freshness of information: In dynamic business environments, how quickly can the index incorporate new data so that retrieval reflects the most recent information?
Equally important is that organizations might run offline evaluations on proprietary test sets, using subject matter experts to mark relevance. Another approach is to measure real-world impact: Are employees more productive? Are support ticket resolutions faster? Such user-centered metrics are key to refining enterprise retrieval systems.
To further enhance retrieval effectiveness, enterprises are increasingly adopting semantic search techniques. The next section explores embeddings, a powerful method for representing text numerically, enabling retrieval based on meaning rather than exact word matches.
Bookmark
Embeddings for enhanced retrieval
Section titled “Embeddings for enhanced retrieval”As enterprise knowledge bases expand encompassing everything from internal wikis and product manuals to customer communications and legal documents, retrieving the right information quickly and accurately becomes a formidable task. Traditional keyword-based search methods often struggle when queries and documents do not share exact terms, or when the user’s intent is broader than simple keyword matches. Enter embeddings: numerical representations of text that capture its meaning at a semantic level, rather than just its surface form.
Embeddings have revolutionized IR by enabling semantic search. Instead of searching documents by looking for exact keyword overlaps, we transform both queries and documents into vectors and then compare these vectors in a high-dimensional space. Documents relevant to a query cluster together in this space, allowing the system to retrieve them based on similarity in meaning, not just lexicon. This shift from lexical to semantic retrieval is a key building block of RAG since RAG systems typically rely on retrieving the most semantically relevant documents to ground their generative responses.
Conceptual overview of text embeddings
Section titled “Conceptual overview of text embeddings”A text embedding is a vector often hundreds or thousands of dimensions long that represents the content and meaning of a piece of text. The magic lies in how these vectors position similar texts close together in the vector space and dissimilar texts far apart.
Mathematically, consider a sentence s. An embedding model f maps s into a vector:

where d is the embedding dimension. If two sentences, s1 and s2, share a similar meaning, then f(s1) and f(s2) will be close under a similarity measure such as cosine similarity:

High similarity (near 1) means the sentences have related meanings.
This transformation from text to vector space empowers retrieval systems to look up relevant documents by proximity rather than exact keyword matches. As a result, if a user queries “European quarterly revenue,” the system can also retrieve documents mentioning “revenue in Q2 in Europe” even if no exact word overlap exists.
Semantic vs. lexical similarity
Section titled “Semantic vs. lexical similarity”Lexical similarity measures overlap in literal terms. For example, a keyword search might treat “car” and “automobile” as unrelated terms if the latter never appears in the text. In contrast, semantic similarity focuses on meaning. Embeddings trained on large corpora learn that “car” and “automobile” occupy similar regions in vector space.
This difference is crucial when dealing with enterprise data where terminology may vary. Perhaps some documents mention “client,” others “customer,” and still others “account holder.” Semantic embeddings unify these variants, allowing more robust retrieval.
Embedding models and their properties
Section titled “Embedding models and their properties”Embedding models have evolved significantly over time. Early approaches, such as GloVe and word2vec, learned embeddings through unsupervised training on word co-occurrence statistics. These models produced static word vectors that lacked contextual awareness.
Modern embedding models, however, are typically derived from large pre-trained language models like BERT, RoBERTa, or Sentence-BERT. These models generate contextual embeddings that capture semantic nuances at the phrase or sentence level. Key properties include:
- Contextuality: Modern embeddings consider the entire context of a sentence, not just individual words. Thus, “bank” in “river bank” and “bank” in “financial bank” produce different embeddings tailored to the respective meanings.
- Transferability: Embedding models trained on general web text often perform well on a variety of domains. However, for highly technical or domain-specific corpora (e.g., legal or medical), performance may be enhanced by domain adaptation such as fine-tuning an embedding model.
- Dimension and complexity: Common embedding dimensions range from a few hundred to a few thousand. Higher dimensions can capture more nuances but may be more computationally intensive.
This hands-on example allows you to see how embeddings actually behave. For instance, a sentence and its paraphrase should produce embeddings with a high cosine similarity, while a sentence and an unrelated sentence should have a much lower similarity score. Here is example code:
from sentence_transformers import SentenceTransformer, util# Load a pre-trained embedding modelmodel = SentenceTransformer('all-MiniLM-L6-v2')# Define some example sentencessentences = [ "The car is parked in the garage.", "A vehicle is inside the building where cars are kept.", "The weather is sunny and bright today."]# Encode the sentences into embeddingsembeddings = model.encode(sentences, convert_to_tensor=True)# Compute cosine similarities between the first sentence and the otherssimilarities = util.cos_sim(embeddings[0], embeddings[1:])sim_with_sentence2 = similarities[0,0].item()sim_with_sentence3 = similarities[0,1].item()print("Similarity with sentence 2:", sim_with_sentence2)print("Similarity with sentence 3:", sim_with_sentence3)The following is the expected output:
Similarity with sentence 2: 0.5113641619682312 Similarity with sentence 3: 0.0436665304005146
In the code above:
similarities[0,0]refers to the similarity score with the first of the subsequent sentences.similarities[0,1]refers to the similarity score with the second of the subsequent sentences.
While embedding models offer powerful ways to represent text semantically, their effectiveness depends on dimensionality and vector-space representation. The next section explores how embedding dimensions impact retrieval performance and how reducing dimensionality can improve efficiency and interpretability.
Dimensionality and vector-space representations
Section titled “Dimensionality and vector-space representations”The dimension, d, of embeddings is a design choice. A vector space might be
, meaning each sentence is mapped to a 512-dimensional vector. While humans cannot visualize such high-dimensional spaces, we can use similarity measures (like cosine similarity) to compute distances between vectors.
Reducing dimensionality (e.g., via PCA or other projection methods) can help with efficiency and sometimes with interpretability. However, the original dimension often strikes a balance between representing complex linguistic phenomena and computational tractability.
Domain adaptation of embeddings
Section titled “Domain adaptation of embeddings”An embedding model trained on general English text might not fully capture specialized terms or abbreviations found in your enterprise’s internal documents (e.g., “SKU breakdown,” “compliance protocol C-201,” or “fintech API endpoints”). Domain adaptation involves fine-tuning these embeddings on in-domain text.
For example, if your organization has thousands of support tickets and technical manuals, you can fine-tune a general-purpose embedding model on these documents. The resulting adapted embeddings understand domain-specific jargon, improving retrieval accuracy for queries that use insider terminology.
This adaptation can be done by:
- Collecting domain-specific text and fine-tuning an embedding model so that semantically related terms within that domain are mapped to similar vectors
- Using techniques like contrastive learning where pairs of related domain sentences are given as positive examples
By adapting embeddings to domain-specific data, organizations can significantly enhance retrieval accuracy and ensure that AI systems understand industry-specific terminology. This fine-tuning process allows models to provide more relevant and context-aware responses, making them better suited for enterprise applications.
Indexing, searching, and storing embeddings in vector databases
Section titled “Indexing, searching, and storing embeddings in vector databases”Once we have embeddings for all documents, we must store them in a way that supports efficient search. A vector database, or vector index, is designed for this purpose. Instead of a classical inverted index keyed on words, a vector database stores each document’s embedding, allowing us to quickly find the nearest neighbors to a query embedding.
To efficiently retrieve relevant information, we follow these steps for indexing and searching embeddings in a vector database:
- Embed the corpus: Compute embeddings for each document.
- Store embeddings: Insert embeddings into a vector database (such as Pinecone, Weaviate, or a self-hosted FAISS index).
- Search by embedding similarity: For a query, compute its embedding and perform a nearest neighbor search to find top-k similar documents.
Here’s a simple Python snippet using sentence-transformers to embed documents and then using FAISS for vector search:
from sentence_transformers import SentenceTransformerimport faissimport numpy as npcorpus = [ "annual revenue growth in europe", "europe sales stable last quarter", "quarterly report on growth and revenue"]model = SentenceTransformer('all-MiniLM-L6-v2')doc_embeddings = model.encode(corpus, convert_to_tensor=False)# Convert to float32 for FAISSdoc_embeddings = np.array(doc_embeddings, dtype='float32')dimension = doc_embeddings.shape[1]index = faiss.IndexFlatL2(dimension)index.add(doc_embeddings)query = "european quarterly revenue"query_embedding = model.encode([query], convert_to_tensor=False)query_embedding = np.array(query_embedding, dtype='float32')k = 2distances, indices = index.search(query_embedding, k)print("Query:", query)for i, idx in enumerate(indices[0]): print(f"Rank {i+1}: {corpus[idx]} (distance: {distances[0][i]:.4f})")The following is the expected output:
Query: european quarterly revenue Rank 1: annual revenue growth in europe (distance: 0.4208) Rank 2: quarterly report on growth and revenue (distance: 0.7865)
The code above demonstrates encoding documents and a query into embeddings; after that, it uses FAISS to find nearest neighbors, as well as illustrating how embeddings turn text into a vector-search problem.
Vector quantization and HNSW graphs
Section titled “Vector quantization and HNSW graphs”For large-scale retrieval (millions of documents), the exact nearest neighbor search is too slow. The following approximate methods accelerate the search:
- Vector quantization (VQ): Compress embeddings into smaller quantized representations (often called codes) that approximate their position in space. Clusters of embeddings can be searched more efficiently.
- HNSW graphs: Instead of brute forcing similarity calculation against every vector, we build a hierarchical graph of connections between embeddings. The graph is organized in layers, with upper layers offering coarse navigation and lower layers offering fine-grained connections. Searching for neighbors involves traversing this graph. HNSW drastically speeds up the search while maintaining high accuracy.
By indexing embeddings in a vector database, we enable efficient similarity searches that scale to large datasets. This approach allows for fast and accurate retrieval, making it a crucial component in RAG systems and other AI-driven search applications.
Fine-tuning embeddings for domain relevance
Section titled “Fine-tuning embeddings for domain relevance”To maximize retrieval quality, especially in RAG contexts, one can fine-tune embeddings so that documents relevant to the enterprise’s tasks are ranked higher.
Why fine-tuning helps:
- It aligns the embedding space with the specifics of the domain, making sure that internal concepts and vocabulary are properly represented.
- It ensures that the retrieval step in RAG consistently returns documents that truly help the language model produce accurate, context-rich answers.
The following code snippet demonstrates the process of fine-tuning embeddings to improve their domain relevance. By training on domain-specific data, we can ensure that similar concepts are mapped closer in vector space, leading to more accurate retrieval. This example walks through loading a dataset, evaluating an embedding model before and after fine-tuning, and measuring improvements using Spearman correlation:
import mathimport numpy as npfrom scipy.stats import spearmanrfrom sentence_transformers import ( SentenceTransformer, InputExample, losses, util)from torch.utils.data import DataLoaderfrom datasets import load_dataset# 1. Load the STS-B dataset (English subset)# stsb_multi_mt includes STS-B data in multiple languages; we choose 'en'sts = load_dataset('stsb_multi_mt', 'en')train_data = sts['train']test_data = sts['test']# STS-B similarity scores range from 0 to 5, we must scale them to [0,1] for CosineSimilarityLossdef scale_score(score, min_val=0.0, max_val=5.0): return (score - min_val) / (max_val - min_val)def to_input_examples(dataset_split): examples = [] for item in dataset_split: # similarity_score in [0,5] score = float(item['similarity_score']) scaled_score = scale_score(score) # scale to [0,1] examples.append( InputExample( texts=[item['sentence1'], item['sentence2']], label=scaled_score ) ) return examplestrain_examples = to_input_examples(train_data)test_examples = to_input_examples(test_data)# 2. Load a pre-trained modelmodel_name = "sentence-transformers/all-MiniLM-L6-v2"model = SentenceTransformer(model_name)def evaluate_model(model, examples): # Evaluate Spearman correlation between model cos_sim and gold scores s1 = [ex.texts[0] for ex in examples] s2 = [ex.texts[1] for ex in examples] gold_scores = [ex.label for ex in examples] # these are in [0,1] emb1 = model.encode(s1, convert_to_tensor=True) emb2 = model.encode(s2, convert_to_tensor=True) cos_scores = util.cos_sim(emb1, emb2).cpu().numpy() # Extract the diagonal since we compared each pair (i,i) cos_scores = np.array( [cos_scores[i][i] for i in range(len(gold_scores))] ) # Compute Spearman correlation spearman_corr = spearmanr(gold_scores, cos_scores).correlation return spearman_corr# Evaluate before fine-tuningbefore_corr = evaluate_model(model, test_examples)print("Before Fine-Tuning - Spearman Correlation on STS-B Test:", before_corr)# 3. Fine-tune the modeltrain_dataloader = DataLoader(train_examples, shuffle=True, batch_size=32)train_loss = losses.CosineSimilarityLoss(model=model) # Align cos_sim with labels in [0,1]epochs = 1warmup_steps = math.ceil(len(train_dataloader)*epochs*0.1)model.fit( train_objectives=[(train_dataloader, train_loss)], epochs=epochs, warmup_steps=warmup_steps, show_progress_bar=True)# 4. Evaluate after fine-tuningafter_corr = evaluate_model(model, test_examples)print("After Fine-Tuning - Spearman Correlation on STS-B Test:", after_corr)The following is the expected output:
Before Fine-Tuning - Spearman Correlation on STS-B Test: 0.8203246731235654 After Fine-Tuning - Spearman Correlation on STS-B Test: 0.8489561516175831
The results show a clear improvement in Spearman correlation after fine-tuning, indicating that the model has better learned domain-specific relationships. This process ensures that embeddings are more aligned with enterprise needs, leading to more relevant and accurate retrieval in downstream tasks. Fine-tuning is a critical step in optimizing retrieval performance, especially in specialized fields where general-purpose embeddings may not fully capture industry-specific terminology.
Constructing a RAG pipeline
Section titled “Constructing a RAG pipeline”RAG pipelines are not a single algorithm but a system architecture that couples a retrieval component (e.g., a vector database, a knowledge graph, and a search API) with a generation component (the LLM itself), plus orchestration logic that glues them together. Tools like LangChain simplify building these pipelines by offering components for retrieval, model interaction, and prompt formatting, allowing developers to build robust RAG pipelines quickly.
System architecture overview
Section titled “System architecture overview”A RAG pipeline consists of several key building blocks:
- User interface/input: The user asks a question or provides instructions.
- Retriever: The system uses a retrieval mechanism to find the most relevant external documents (chunks) that could help answer the query. These documents can come from a variety of data sources, including enterprise knowledge bases, wikis, product manuals, or research papers.
- Combining steps and prompt construction: The selected relevant documents are combined and integrated into a prompt for the LLM.
- LLM generation: The LLM reads the prompt (query + retrieved documents) and produces a grounded, accurate response.
- Post-processing and attribution: The final answer is often returned to the user along with citations or references to the documents used, enhancing trust and transparency.
A RAG pipeline can integrate additional steps, like query rewriting, chunk re-ranking, multi-hop retrieval, or hierarchical indexing. For complex queries, you might break down the problem into sub-queries and retrieve documents for each part before merging them.
Retrieval component integration
Section titled “Retrieval component integration”The retrieval component is at the heart of RAG. Without reliable retrieval, the LLM might not receive the necessary factual grounding. Retrieval can be done using:
- Term-based search (BM25 or Elasticsearch): A simple but fast approach that returns documents containing keywords from the user’s query
- Embedding-based (vector) search: Converts both documents and queries into embeddings and uses similarity search to find semantically related documents
- Hybrid retrieval: Combines both lexical and semantic searches to leverage the strengths of each
LangChain offers retrievers, such as VectorstoreRetriever or BM25Retriever. You can load a vector database (like FAISS or Pinecone) and connect it to LangChain’s retriever interface. Here is example code:
Step-by-Step Explanation and Script for EU AI Act PDF Analysis
Section titled “Step-by-Step Explanation and Script for EU AI Act PDF Analysis”Install required dependencies
Section titled “Install required dependencies”Run these commands in your terminal or uncomment to install directly via the script:
Section titled “Run these commands in your terminal or uncomment to install directly via the script:”# !pip install -qU langchain-ollama langchain-community pypdf faiss-cpu numpyfrom langchain.document_loaders import PyPDFLoaderfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain.embeddings import OllamaEmbeddingsfrom langchain_core.vectorstores import InMemoryVectorStorefrom langchain_core.runnables import chainfrom typing import Listfrom langchain_core.documents import Document# Step 1: Load the EU AI Act PDF# Use PyPDFLoader to load the PDF into raw document objects.pdf_path = "eu_ai_act.pdf" # Replace with the path to your PDF fileloader = PyPDFLoader(pdf_path)raw_docs = loader.load()# Step 2: Split the loaded documents into manageable chunks# Use RecursiveCharacterTextSplitter to divide the content into smaller sections for efficient processing.text_splitter = RecursiveCharacterTextSplitter( chunk_size=1500, chunk_overlap=200, separators=["\n\n", "."], add_start_index=True)docs = text_splitter.split_documents(raw_docs)print(f"Number of chunks created from PDF: {len(docs)}")Step 3: Use OllamaEmbeddings
Section titled “Step 3: Use OllamaEmbeddings”Note: Ensure Ollama is running (`ollama serve`) and a model like `llama3` is available locally.
Section titled “Note: Ensure Ollama is running (`ollama serve`) and a model like `llama3` is available locally.”# Generate embeddings using the Ollama embedding model.embeddings = OllamaEmbeddings(model="llama3")# Step 4: Initialize InMemoryVectorStore# Store and manage the embeddings in an in-memory vector store.vector_store = InMemoryVectorStore(embeddings)ids = vector_store.add_documents(documents=docs)print(f"Documents added to vector store. Total IDs: {len(ids)}")# Step 5: Perform Similarity Search# Query the vector store to find the most relevant chunk(s) based on the given question.query = ("According to the EU AI Act, what transparency obligations must providers of high-risk AI systems " "comply with, and how do these differ from obligations for general-purpose AI systems?")results = vector_store.similarity_search(query, k=1) # Adjust `k` for more resultsprint("\n--- Top Matching Document ---")print(results[0].page_content if results else "No relevant document found.")# Step 6: Define a retriever function for batch queries# Process multiple queries in one call to the retriever.@chaindef retriever(query: str) -> List[Document]: return vector_store.similarity_search(query, k=1)# Batch query examplebatch_queries = [ "What are the transparency obligations in the EU AI Act?", "How does the EU AI Act define high-risk AI systems?"]batch_results = retriever.batch(batch_queries)print("\n--- Batch Query Results ---")for idx, result in enumerate(batch_results): print(f"Query {idx + 1}: {batch_queries[idx]}") print( f"Answer: {result[0].page_content if result else 'No relevant document found.'}" ) print("-----------")The following is the expected output:
Number of chunks created from PDF: 270 Documents added to vector store. Total IDs: 270 --- Top Matching Document --- . That guida nce shall be issued 12 months after the entry into force of this Regulation, at the latest. 3. For high-risk AI systems referred to in point 5(b) of Annex III which are placed on the market or put into service by providers that are credit institutions regu lated by Directive 2013/36/EU and for high -risk AI systems which are safety components of devices, or are themselves devices, covered by Regulation (EU) 2017/745 and Regulation (EU) 2017/746, the notification of serious incidents or malfunctioning shall be limited to those that that constitute a breach of obligations under Union law intended to protect fundamental rights. --- Batch Query Results --- Query 1: What are the transparency obligations in the EU AI Act? Answer: …
Section titled “Number of chunks created from PDF: 270 Documents added to vector store. Total IDs: 270 --- Top Matching Document --- . That guida nce shall be issued 12 months after the entry into force of this Regulation, at the latest. 3. For high-risk AI systems referred to in point 5(b) of Annex III which are placed on the market or put into service by providers that are credit institutions regu lated by Directive 2013/36/EU and for high -risk AI systems which are safety components of devices, or are themselves devices, covered by Regulation (EU) 2017/745 and Regulation (EU) 2017/746, the notification of serious incidents or malfunctioning shall be limited to those that that constitute a breach of obligations under Union law intended to protect fundamental rights. --- Batch Query Results --- Query 1: What are the transparency obligations in the EU AI Act? Answer: …”Query 2: How does the EU AI Act define high-risk AI systems? Answer: …
Section titled “Query 2: How does the EU AI Act define high-risk AI systems? Answer: …”By integrating a retrieval component into a RAG pipeline, we ensure that the model has access to relevant, up-to-date information. However, retrieval alone is not enough; once the relevant documents are found, they must be effectively incorporated into the generation process. The next section explores how a retrieved context is used to guide the LLM in producing accurate and well-grounded responses.
Response generation from a retrieved context
Section titled “Response generation from a retrieved context”Once you have retrieved documents, you must feed them into the LLM. This often involves building a prompt that concatenates the user’s query with a selection of retrieved documents. The model then uses these documents as context to ground its answer.
The prompt might look like this:
[Context Document 1] [Context Document 2] … User query: {User’s question} Answer according to the above documents:
The LLM will produce a more accurate and factually supported answer because the relevant context is directly in its input. This approach is crucial for handling queries outside the model’s original training data timeframe or domain.
LangChain’s RetrievalQA chain simplifies this workflow. You specify the LLM, the retriever, and possibly a prompt template. The chain automatically:
- Takes the user query
- Uses the retriever to find top-k documents
- Constructs a prompt that includes these documents
- Calls the LLM to generate a final answer
Effectively structuring the retrieved context allows the model to generate more accurate responses. However, when dealing with long documents, retrieval efficiency depends on how the text is segmented. The next section explores chunking strategies, which ensure that relevant information is properly extracted and utilized in the RAG pipeline.
Chunking strategies for long documents
Section titled “Chunking strategies for long documents”Long documents are problematic because embedding or indexing them as a single vector loses detail. Instead, we break them into “chunks.” Each chunk represents a coherent portion of text (e.g., a paragraph). The size of these chunks matters:
- Smaller chunks provide more fine-grained retrieval but may lack context.
- Larger chunks ensure more context but might dilute relevance and reduce retrieval precision.
- Overlapping chunks ensure that important boundary information is captured. Overlap can reduce the chances of splitting a crucial piece of information in half.
Approach: Start with moderate-sized chunks (e.g., ~512 tokens). If documents are structured (like Markdown or HTML), you can chunk by headings. For unstructured text, consider sentence-level splitting plus overlap. Experiment with different sizes to achieve the best performance.
LangChain provides TextSplitter classes. For example, CharacterTextSplitter or RecursiveCharacterTextSplitter can split large documents into smaller chunks automatically, ready for embedding.
Combining multiple retrieval methods
Section titled “Combining multiple retrieval methods”No single retrieval method is perfect. Hybrid retrieval can combine semantic embeddings with keyword-based filters. For example:
- First, run a BM25 search to quickly narrow down the candidate pool by keyword.
- Then, run a vector similarity search on these candidates to select the final documents.
Or you could run both methods in parallel and merge their results using reciprocal rank fusion (RRF). This boosts retrieval quality by leveraging lexical precision and semantic recall.
The following is an example hybrid approach:
- Keyword search (BM25) retrieves the top 100 candidates.
- Embedding search reranks or narrows these down to the best 10.
- The reranker model (optional) refines the top 10 into a final top 5.
LangChain integration: LangChain’s MultiQueryRetriever can generate multiple semantic queries from an original user query and combine results. You can also chain two retrievers: first, a BM25Retriever to get candidates, then a VectorstoreRetriever for final semantic filtering.
Bookmark
Ensuring attribution, reducing hallucinations, and facilitating revisions
Section titled “Ensuring attribution, reducing hallucinations, and facilitating revisions”Ensuring proper attribution in RAG systems is essential for maintaining credibility and transparency. By linking generated responses to their original sources, we can reduce hallucinations and incorrect or fabricated information that the model might introduce.
To support these goals effectively, RAG systems should incorporate the following key practices:
- Source tracking: Every retrieved document should include metadata such as author, date, and source URL to facilitate verification.
- Contextual responses: The LLM should generate responses that not only answer queries but also reference the source of the information.
- Editable output: The system should provide mechanisms for users to modify or refine responses while maintaining provenance.
In the provenance tracking script below, these aspects are implemented to ensure that retrieved information remains traceable and verifiable:
- Using
retrieverto fetch relevant document chunks - Enhancing
rag_chain_with_sourceto return both generated answers and associated sources - Assigning metadata such as
sourceandauthorto indexed documents for better tracking
By incorporating these attribution mechanisms, RAG systems ensure that AI-generated responses remain transparent. This not only enhances user confidence but also aligns AI applications with regulatory requirements, making them more suitable for enterprise and compliance-driven environments.
Source tracking and document provenance
Section titled “Source tracking and document provenance”Tracking the provenance of retrieved documents ensures that users can trace the origins of the information presented. Provenance metadata includes:
- Document source identification: Each indexed document should store the original report, research paper, or legal document.
- Timestamping: Embedding a timestamp in the document metadata allows users to differentiate between outdated and current information.
- Audit trails: Logging retrievals and modifications enhances transparency and compliance with regulatory frameworks such as the EU AI Act.
The below script currently implements provenance tracking by:
- Storing metadata (
source,author,date) when indexing new documents - Associating retrieved text with its original document before generating responses
Script for EU AI Act Analysis with Document Embedding and Retrieval
Section titled “Script for EU AI Act Analysis with Document Embedding and Retrieval”---------------------------------------------------
Section titled “---------------------------------------------------”Install required dependencies
Section titled “Install required dependencies”Ensure the following packages are installed via terminal or uncomment to install directly in the script:
Section titled “Ensure the following packages are installed via terminal or uncomment to install directly in the script:”# !pip install langchain-ollama langchain-community chromadb pypdffrom langchain.document_loaders import PyPDFLoaderfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain.embeddings.ollama import OllamaEmbeddingsfrom langchain.vectorstores import Chromafrom langchain.chains import RetrievalQAfrom langchain import PromptTemplatefrom langchain_ollama import ChatOllamafrom langchain_core.documents import Documentfrom langchain_core.runnables import RunnablePassthrough, RunnableParallelfrom langchain_core.output_parsers import StrOutputParserfrom langchain import hub# Step 1: Load and Process the EU AI Act PDF# Description: Load the PDF and prepare the text for processing.pdf_path = "eu_ai_act.pdf" # Replace with the actual file pathloader = PyPDFLoader(pdf_path)documents = loader.load()# Step 2: Split the Text into Manageable Chunks# Description: Use RecursiveCharacterTextSplitter to chunk text into smaller sections for analysis.splitter = RecursiveCharacterTextSplitter( chunk_size=800, chunk_overlap=100)split_docs = splitter.split_documents(documents)print(f"Number of chunks created: {len(split_docs)}")# Step 3: Generate Embeddings with Ollama# Description: Use the `OllamaEmbeddings` model to generate vector embeddings for the chunks.embeddings = OllamaEmbeddings(model="llama3")# Step 4: Store Embeddings in Chroma Vector Database# Description: Index the document embeddings using Chroma for efficient retrieval.vectorstore = Chroma.from_documents(split_docs, embeddings)print("Embeddings stored in Chroma vector database.")# Step 5: Setup Retriever# Description: Configure the retriever for similarity-based search with a score threshold.retriever = vectorstore.as_retriever( search_type="similarity_score_threshold", search_kwargs={"score_threshold": 0.75})retriever = vectorstore.as_retriever()# Step 6: Initialize LLM with ChatOllama# Description: Configure the language model with desired response variability.llm = ChatOllama( model="llama3", temperature=0 # Lower temperature for deterministic responses)# Step 9: Advanced Retrieval with RAG Chain# Description: Configure a Retrieval-Augmented Generation (RAG) chain for improved retrieval and LLM processing.def format_docs(docs): return "\n\n".join(doc.page_content for doc in docs)rag_chain = ( { "context": retriever | format_docs, "question": RunnablePassthrough() }| hub.pull("rlm/rag-prompt")| llm| StrOutputParser())# Example Query with RAG Chainrag_response = rag_chain.invoke("According to the EU AI Act, what transparency obligations must providers of high-risk AI systems comply with, and how do these differ from obligations for general-purpose AI systems?")print("\n--- RAG Chain Response ---")print(rag_response)#Adjusting the RAG to retrive sources
from langchain_core.runnables import RunnableParallelrag_chain_from_docs = ( RunnablePassthrough.assign( context=(lambda x: format_docs(x["context"])))| hub.pull("rlm/rag-prompt")| llm| StrOutputParser())rag_chain_with_source = RunnableParallel( {"context": retriever, "question": RunnablePassthrough()}).assign(answer=rag_chain_from_docs)
rag_response = rag_chain_with_source.invoke("According to the EU AI Act, what transparency obligations must providers of high-risk AI systems comply with, and how do these differ from obligations for general-purpose AI systems?")print("\n--- RAG Chain Response with Sources ---")print(rag_response)Thresholding mechanisms for irrelevant or uncertain results
Section titled “Thresholding mechanisms for irrelevant or uncertain results”Setting a confidence threshold for retrieved results helps filter out irrelevant or uncertain responses. If a document’s similarity score falls below the threshold, it is discarded:
- Implementation: The script applies a
search_kwargs={"score_threshold": 0.75}parameter to the retriever. - Benefits:
- Prevents misleading outputs by eliminating weak matches
- Improves accuracy by focusing on high-confidence retrievals
- Reduces noise in enterprise applications where precise responses are critical
- Prevents misleading outputs by eliminating weak matches
# Description: Configure the retriever for similarity-based search with a score threshold.retriever = vectorstore.as_retriever( search_type="similarity_score_threshold", search_kwargs={"score_threshold": 0.75})By applying confidence thresholds, RAG systems can deliver more precise and reliable responses while minimizing irrelevant or misleading outputs. This ensures that only the most relevant and high-confidence information is used, improving both user trust and system performance.
Auditing and updating the retrieval index
Section titled “Auditing and updating the retrieval index”Regularly updating the retrieval index ensures that new information is incorporated while outdated content is archived or removed:
- New document ingestion: The script dynamically adds documents to the vector database using
vectorstore.add_documents(new_docs). - Re-indexing strategies:
- Periodically retraining the embedding model on updated documents
- Removing outdated embeddings to prevent the retrieval of obsolete information
- Periodically retraining the embedding model on updated documents
Step 10: Adding New Documents to the Index
Section titled “Step 10: Adding New Documents to the Index”# Description: Dynamically add new documents to the existing vectorstore.new_docs = [ Document(page_content="Solar panels improve energy independence.", metadata={"source": "Report_C", "author": "EnergyWorld", "date": "2023-06-20"})]vectorstore.add_documents(new_docs)retriever = vectorstore.as_retriever()The code snippet demonstrates how to dynamically update the retrieval index by adding new documents to the vector store. By calling vectorstore.add_documents(new_docs), the system ensures that newly available information is incorporated, improving retrieval accuracy. This approach keeps the knowledge base fresh and relevant, allowing the retriever to access the most up-to-date content.
Handling stale or outdated information
Section titled “Handling stale or outdated information”To prevent outdated information from influencing retrieval, the system should utilize:
- Timestamp validation: Before retrieving documents, the system checks their metadata to prioritize the most recent entries.
- Re-ranking mechanisms: After initial retrieval, a reranker model can score documents based not only on relevance to the query but also on metadata like publication date. By incorporating time-based decay functions or giving more weight to recent documents during re-ranking, the system ensures that newer, more relevant sources are prioritized over outdated ones.
- User feedback loops: This allows users to flag outdated responses for manual review.
Revision workflows for enterprise environments
Section titled “Revision workflows for enterprise environments”Enterprises require structured workflows to review and revise AI-generated responses before dissemination. A robust revision framework includes:
- Human-in-the-loop review: Allowing human experts to validate and refine AI-generated responses
- Version control: Maintaining a history of edits and source references for auditing purposes
- Approval mechanisms: Implementing an approval process before responses are published
Future enhancements could include integrating feedback mechanisms where users can edit and annotate generated responses before they are finalized.
Policies and governance for trusted RAG outputs
Section titled “Policies and governance for trusted RAG outputs”For organizations implementing RAG-based AI systems, adherence to governance policies is crucial. Best practices include:
- Regulatory compliance: Ensuring compliance with AI regulations such as the EU AI Act and GDPR
- Bias mitigation: Regularly auditing the model and retriever to minimize bias in responses
- Security and access control: Restricting data access to authorized users and ensuring sensitive information is protected
By embedding governance frameworks into the retrieval and response generation processes, enterprises can enhance trust and accountability in AI-powered workflows.
Bookmark
Summary
Section titled “Summary”RAG enhances generative AI by integrating real-time external data retrieval, addressing limitations like outdated knowledge and hallucinations through verifiable, attributed sources. It combines sparse (keyword-based) and dense (embedding-driven) retrieval methods, leveraging semantic understanding and efficient indexing (e.g., ANN and HNSW) for relevance. RAG pipelines dynamically synthesize enterprise knowledge via chunking, hybrid retrieval, and context-aware generation while ensuring traceability and governance. By grounding outputs in domain-adapted embeddings and updatable indexes, RAG enables scalable, accurate responses tailored to specialized use cases like technical support or compliance. This approach bridges generative fluency with enterprise needs for transparency, freshness, and auditability.
This chapter explored RAG and its role in enhancing generative AI by integrating external data retrieval. We examined sparse and dense retrieval methods, indexing techniques, and strategies for fine-tuning embeddings to improve accuracy and relevance. By grounding responses in real-time information, RAG reduces hallucinations and ensures transparency, making it particularly valuable for enterprise applications like technical support and compliance. These techniques enable AI models to provide up-to-date, factually supported answers without constant retraining.
In the next chapter, the book will dive deeper into customizing contextual LLMs using RAG. It will focus on how this approach reduces hallucination in conversations, further improving the relevance and reliability of LLM outputs in business applications. This will involve more detailed technical discussions and practical examples to illustrate the extended capabilities of these models in various industries.