Retrieval-Augmented Generation (RAG)
Relevant source files
The following files were used as context for generating this wiki page:
- libs/langchain/langchain/chains/retrieval_qa/base.py
- libs/langchain/langchain/chains/conversational_retrieval/base.py
- libs/langchain/langchain/chains/history_aware_retriever.py
- cookbook/README.md
- libs/core/langchain_core/tools/retriever.py
- libs/text-splitters/tests/unit_tests/test_text_splitters.py
- libs/langchain/README.md
Retrieval-Augmented Generation (RAG) is a core capability within the LangChain framework that enhances Large Language Models (LLMs) by connecting them to external data sources. While LLMs possess vast general knowledge from their training data, they are often insufficient for applications requiring access to private, specific, or real-time information. RAG addresses this by first retrieving relevant data from an external source and then passing that data as context to the LLM during the generation step.
This approach enables a wide range of applications, most notably question-answering over specific documents and building chatbots with access to a knowledge base. LangChain provides a comprehensive set of components, including document splitters, retrievers, and chains, to build robust and powerful RAG applications.
Sources: libs/langchain/README.md
Core RAG Architecture
The RAG process in LangChain generally follows a two-stage pipeline: Retrieval and Generation. An initial data ingestion and processing step is required to prepare the external knowledge source.
This diagram illustrates the typical data flow in a RAG application.
Key Components
Text Splitters
Before documents can be effectively retrieved, they must be broken down into smaller, manageable chunks. This is crucial for embedding and vector search, as it allows the retrieval mechanism to find the most relevant pieces of text for a given query. LangChain provides a variety of text splitters designed for different document formats.
| Splitter Class | Description | Source File |
|---|---|---|
CharacterTextSplitter | Splits text based on a specified character separator and chunk size. | libs/text-splitters/tests/unit_tests/test_text_splitters.py:31-36 |
RecursiveCharacterTextSplitter | Splits text recursively using a list of separators (e.g., \n\n, \n, ) to keep related text together. | libs/text-splitters/tests/unit_tests/test_text_splitters.py:270-273 |
PythonCodeTextSplitter | A specialized RecursiveCharacterTextSplitter for Python code, splitting on class and function definitions. | libs/text-splitters/tests/unit_tests/test_text_splitters.py:388-392 |
MarkdownHeaderTextSplitter | Splits a Markdown document based on its headers, preserving the header hierarchy in the metadata. | libs/text-splitters/tests/unit_tests/test_text_splitters.py:900-910 |
HTMLHeaderTextSplitter | Splits an HTML document based on header tags (h1, h2, etc.), associating content with its corresponding headers. | libs/text-splitters/tests/unit_tests/test_text_splitters.py:1612-1618 |
HTMLSectionSplitter | Splits an HTML document into sections based on header tags, keeping the content of each section together. | libs/text-splitters/tests/unit_tests/test_text_splitters.py:2146-2152 |
RecursiveJsonSplitter | Splits large JSON objects recursively into smaller chunks. | libs/text-splitters/tests/unit_tests/test_text_splitters.py:2287-2290 |
Sources: libs/text-splitters/tests/unit_tests/test_text_splitters.py
Retrievers
A retriever is a component that, given a query, returns relevant documents. While often backed by a vector store, a retriever is a more general interface. LangChain offers numerous retriever implementations for different use cases.
A key function for integrating retrievers into agentic workflows is create_retriever_tool. This function wraps a BaseRetriever instance into a Tool, which an agent can then select and use.
The following diagram shows how create_retriever_tool works.
This sequence shows the process of invoking a retriever tool, fetching documents, and formatting them into a single string for the agent.
Sources: libs/core/langchain_core/tools/retriever.py
create_retriever_tool Parameters
| Parameter | Type | Description | Source |
|---|---|---|---|
retriever | BaseRetriever | The retriever instance to be wrapped. | libs/core/langchain_core/tools/retriever.py:80 |
name | str | The unique name for the tool, passed to the LLM. | libs/core/langchain_core/tools/retriever.py:81 |
description | str | A description of the tool's purpose for the LLM. | libs/core/langchain_core/tools/retriever.py:82 |
document_prompt | Optional[BasePromptTemplate] | A prompt to format each retrieved document. Defaults to just the page_content. | libs/core/langchain_core/tools/retriever.py:84-85 |
document_separator | str | The string used to join the formatted documents. Defaults to \n\n. | libs/core/langchain_core/tools/retriever.py:85 |
Sources: libs/core/langchain_core/tools/retriever.py:78-86
RAG Chains
LangChain provides several pre-built chains to implement common RAG patterns. These chains abstract away the logic of combining retrieval with generation.
RetrievalQA
This is the fundamental chain for question-answering over an index. It takes a user's question, retrieves relevant documents, and passes them to an LLM to generate an answer.
Sources: libs/langchain/langchain/chains/retrieval_qa/base.py
ConversationalRetrievalChain
This chain extends RAG to support conversational context. It maintains a chat history and uses it to inform the retrieval and generation process. A key feature is its ability to condense the current question and the chat history into a new, standalone question before performing retrieval. This ensures that the retriever gets a query with full context.
The flow of this chain is as follows:
- A
questionandchat_historyare provided. - A
question_generatorchain condenses these into a standalone question. - The retriever fetches documents relevant to the new question.
- A separate QA chain (
combine_docs_chain) takes the retrieved documents and the original question to generate the final answer.
This diagram shows the data flow within the ConversationalRetrievalChain.
Sources: libs/langchain/langchain/chains/conversational_retrieval/base.py:126-146
create_history_aware_retriever
This factory function creates a chain that specifically handles the first part of the conversational RAG flow: taking a user's input and chat history to create a search query. It chains together a prompt and an LLM to rephrase the follow-up question into a standalone query, which is then passed to the retriever. This is a crucial step for effective retrieval in a conversational setting, as a follow-up question like "what about that one?" is meaningless without the preceding conversation.
*Sources: libs/langchain/langchain/chains/history_aware_retriever.py *
Practical Examples
The LangChain Cookbook provides numerous end-to-end examples of RAG applications, demonstrating how to combine these components to solve real-world problems.
| Cookbook Notebook | Description |
|---|---|
Semi_Structured_RAG.ipynb | Demonstrates RAG on documents containing both text and tables, using a multi-vector retriever. |
Semi_structured_and_multi_modal_RAG.ipynb | Extends RAG to handle documents with text, tables, and images. |
retrieval_in_sql.ipynb | Shows how to perform RAG on a PostgreSQL database using pgvector. |
contextual_rag.ipynb | Implements a technique where chunk-specific context is prepended to each chunk before embedding to improve retrieval quality. |
rag-locally-on-intel-cpu.ipynb | Provides an example of running a full RAG pipeline with open-source models on local hardware. |
rag-agents-locally-on-intel-cpu.ipynb | Builds a local RAG agent that can route questions to either a vector database or a web search tool. |
Sources: cookbook/README.md
Conclusion
Retrieval-Augmented Generation is a foundational pattern in LangChain for building LLM applications that can reason about and answer questions based on external data. By providing modular components like text splitters, retrievers, and composable chains, LangChain enables developers to construct sophisticated RAG pipelines tailored to specific data sources and use cases, from simple document Q&A to complex, conversational agents with memory.
Sources: libs/langchain/README.md, cookbook/README.md