Skip to main content

LangChain Fundamentals

LangChain is a framework for building applications powered by Large Language Models. It provides components for working with:
  • LLMs and chat models
  • Prompts
  • Documents
  • Document loaders
  • Text splitters
  • Embeddings
  • Vector stores
  • Retrievers
  • Output parsers
  • Chains
  • Tools and agents
LangChain is commonly used to build:
  • RAG applications
  • Document question-answering systems
  • AI chatbots
  • AI agents
  • Tool-using applications
  • Multi-step LLM workflows

1. Why LangChain?

A basic LLM application may involve manually connecting several components:
LangChain provides standardized abstractions for these components.
These components can be combined into a chain.

2. Core LangChain Components

The main components used in a RAG application are:

3. Documents

LangChain represents text using the Document object.
Example:
A document generally contains:

page_content

Contains the actual text.
Example:

metadata

Stores additional information about the document. Example:
Metadata is useful for:
  • Source citations
  • File names
  • Page numbers
  • URLs
  • Document IDs
  • Filtering documents

4. Document Loaders

A document loader reads data from external sources and converts it into LangChain Document objects. Examples of sources:
  • Text files
  • PDFs
  • CSV files
  • Websites
  • Databases
  • Notion
  • Google Drive
Conceptually:
Example:
The result is a list of Document objects.

5. Text Splitting and Chunking

Large documents should usually not be embedded as one large piece of text. Instead:
Example:

Important Parameters

chunk_size

Maximum approximate size of each chunk.

chunk_overlap

Some text from the previous chunk is repeated in the next chunk. Example:
Overlap helps preserve context between chunks.

6. Embeddings

Embeddings convert text into numerical vectors.
Example:
Example using Hugging Face embeddings:
Embeddings allow semantic comparison between text. For example:

7. Vector Store

A vector store stores embedding vectors and supports similarity search. Common vector stores include:
  • FAISS
  • Chroma
  • Pinecone
  • Qdrant
  • Weaviate
  • Milvus
The process is:
Example with FAISS:
This internally performs:

8. Similarity Search

Similarity search finds documents whose embeddings are closest to the query embedding.
Example:
The parameter:
means:

9. Retriever

A retriever is an abstraction for retrieving relevant documents. Create a retriever from a vector store:
Retrieve documents:
Conceptually:
A retriever separates the retrieval logic from the rest of the application.

10. Retrieval Strategies

The default retrieval method is usually similarity search. Other strategies can include:
MMR means Maximum Marginal Relevance. It balances:
  • Relevance
  • Diversity
Instead of retrieving three nearly identical chunks:
MMR attempts to retrieve:
Example:

11. Prompt Templates

Prompt templates create structured prompts. Import:
Example:
The placeholders:
are replaced with actual values. Example:
Prompt templates make prompts reusable and structured.

12. LLMs and Chat Models

LangChain supports multiple LLM providers through integrations. Examples include:
  • Google Gemini
  • OpenAI
  • Anthropic
  • Hugging Face
  • Ollama
Example with Gemini:

Temperature

The temperature parameter controls randomness.
For RAG:
or a low value is commonly used when factual and consistent answers are preferred.

13. Output Parsers

LLMs can return structured response objects. An output parser converts the output into a desired format. For plain text:
Conceptually:
Example chain:

14. Chains

A chain connects multiple components together. Example:
In LangChain:
The | operator is part of LCEL.

15. LCEL

LCEL stands for:
LCEL is used to compose LangChain components. Example:
The output of one component becomes the input of the next.
Run the chain using:
Other execution methods include:
for multiple inputs, and:
for streaming output.

16. Basic RAG Flow with LangChain

A RAG pipeline has two major stages.

Indexing Stage

Retrieval and Generation Stage


17. Basic LangChain RAG Example

Installation

Set the Gemini API key.

Git Bash


langchain_rag.py


18. Step-by-Step Code Flow


19. The Complete Chain Concept

The generation chain is:
However, retrieval can also be integrated into a larger workflow. Conceptually:
The main idea is that each component has a specific responsibility.

20. Manual RAG vs LangChain RAG


21. Important RAG Concepts with LangChain

Chunk Size

Chunk size affects retrieval quality.
Choosing a suitable chunk size is important.

Chunk Overlap

Overlap preserves context between neighboring chunks.
Without overlap, important information can be split across chunk boundaries.

Top-K Retrieval

Controls the number of retrieved documents.

Context Window

The retrieved documents are added to the LLM prompt.
Too much retrieved context can increase cost, latency, and irrelevant information.

Grounding

A RAG prompt can instruct the model to answer only from the retrieved context. Example:
This helps reduce hallucinations. However:
The quality of retrieval still affects the final answer.

Metadata Filtering

Metadata can be used to restrict retrieval. Example:
A retriever or vector store can use metadata, depending on the underlying store, to search within specific subsets of documents.

22. RAG Quality

The final answer depends heavily on retrieval quality.
A useful principle is:
The LLM can only generate a grounded answer based on the information provided in the retrieved context.

23. Advanced RAG Concepts

Important topics that build on basic LangChain RAG include:

Query Transformation

The original query can be rewritten before retrieval.

Multi-Query Retrieval

Generate multiple versions of a query.
This can improve recall.

Reranking

Initial retrieval:
Then a reranking model:
Reranking can improve the relevance of the final context.
Combines:
This can improve retrieval when exact terms, names, or technical keywords are important.

Contextual Compression

Retrieved documents may contain unnecessary text.
This reduces unnecessary context.

Parent-Child Retrieval

Small chunks are used for accurate search, while larger parent documents provide broader context.

24. LangChain RAG Architecture


Key Takeaways

The basic LangChain RAG pipeline can be summarized as: