RAG in LangChain: Documents, a Text Splitter, a Retriever and an LCEL Chain, Next to the Same Pipeline by Hand
The same help bot for an outdoor-gear shop, built twice: by hand in 20 lines of logic and in LangChain in 16. The splitter packs 12 pieces into 7 chunks, the retriever returns two Documents from shipping.txt, and calling each step alone shows a 455-character prompt.
What you will learn
- Map each hand-written RAG step to its LangChain part: Document, text splitter, vector store, retriever, chain
- Build an LCEL chain that feeds a retriever and the question into a prompt, a model and a parser
- Explain why RecursiveCharacterTextSplitter turns 12 pieces into 7 chunks
- Call each part of the chain on its own to debug a wrong answer
Before you start
- The RAG Pipeline Explained
- What LangChain Is For, and When to Skip It
You already know the RAG recipe: load the documents, split them, embed the pieces, store them, then on every question retrieve the closest pieces, build a prompt and ask the model. In this article we cook the same recipe twice. First in plain Python, so every step is visible, and then in LangChain, where each step is a ready-made part. The order stays the same. Only who writes each step changes.
Everything runs on a stand-in test model with scripted replies, so you need no API key. The embedding model (all-MiniLM-L6-v2) runs on your own machine.
Cooking from scratch, or a meal kit
Think about making one dish two ways. From scratch, you chop and measure every ingredient yourself, and you see every step. That's plain Python. With a meal kit, the pieces arrive already measured. That's LangChain. The recipe is the same in both: load, split, embed, search, prompt, answer. The kit saves you the chopping, but you still need to know the recipe.
The use case: a help bot for an outdoor-gear shop
The shop's answers sit in three small text files in docs/: returns.txt, shipping.txt and warranty.txt. We ask two questions:
- "How many days do I have to return an unworn item?" The answer is in
returns.txt. - "Do you ship to Canada, and how long does it take?" The answer is in
shipping.txt.
Both versions share common.py: the questions, the prompt, the settings and get_model().
DOCS_DIR = pathlib.Path(__file__).parent / "docs"
EMBED_MODEL = "all-MiniLM-L6-v2"
CHUNK_SIZE = 250
CHUNK_OVERLAP = 30
TOP_K = 2
PROMPT_TEXT = """Answer the question using only the context below.
If the context does not contain the answer, say you do not know.
Context:
{context}
Question: {question}"""
def get_model():
"""A real chat model if MODEL_NAME is set in .env, otherwise the stand-in test model."""
name = os.getenv("MODEL_NAME")
if name:
from langchain.chat_models import init_chat_model
return init_chat_model(name)
from langchain_core.language_models.fake_chat_models import FakeListChatModel
return FakeListChatModel(responses=SCRIPTED_REPLIES)
FakeListChatModel hands back its scripted replies in order, one per call. Set MODEL_NAME in .env and the same code calls a real model.
The recipe by hand
01_plain_rag.py is the from-scratch version. Each document is a dictionary, the split happens at every blank line, and retrieval is one matrix product in numpy.
"""RAG written by hand: load, split, embed, search, build the prompt, ask the model."""
import numpy as np
from common import DOCS_DIR, PROMPT_TEXT, QUESTIONS, TOP_K, embedder, get_model
def load():
return [{"text": p.read_text(encoding="utf-8"), "source": p.name}
for p in sorted(DOCS_DIR.glob("*.txt"))]
def split(docs):
chunks = []
for doc in docs:
for part in doc["text"].split("\n\n"):
if part.strip():
chunks.append({"text": part.strip(), "source": doc["source"]})
return chunks
chunks = split(load())
vectors = embedder().encode([c["text"] for c in chunks], normalize_embeddings=True)
def retrieve(question):
q = embedder().encode([question], normalize_embeddings=True)[0]
best = np.argsort(vectors @ q)[::-1][:TOP_K]
return [chunks[i] for i in best]
def answer(question, model):
context = "\n\n".join(c["text"] for c in retrieve(question))
prompt = PROMPT_TEXT.format(context=context, question=question)
return model.invoke(prompt).content
Splitting the three files at every blank line gives 12 chunks. Each chunk is embedded once into 384 numbers. retrieve embeds the question, scores every chunk and keeps the best two, and answer puts those two into the prompt.
12 chunks
Q: How many days do I have to return an unworn item?
from returns.txt | You can return any unworn item within 30 days of
from returns.txt | Sale items can be returned within 14 days. Gift
A: You have 30 days from delivery to return an unworn item with its tags attached. Sale items get 14 days.
Q: Do you ship to Canada, and how long does it take?
from shipping.txt | We also ship to Canada. Delivery to Canada takes
from shipping.txt | Standard delivery inside the United States takes
A: Yes. Delivery to Canada takes 7 to 10 business days and costs 12 dollars. Customers pay any import fees.
Each part gets its LangChain name
- Our dictionary becomes a
Document: the text inpage_content, the file name inmetadata. - Our split function becomes
RecursiveCharacterTextSplitter, where size and overlap are settings. - Our numpy array becomes an
InMemoryVectorStore, with a small wrapper around our local embedding model. - Our retrieve function becomes a retriever: a question goes in, two Documents come out.
- Our answer function becomes a chain: prompt, pipe, model, pipe, parser. That pipe syntax is LCEL, the LangChain Expression Language.
The same recipe in the kit
"""The same RAG in LangChain: splitter, vector store, retriever and an LCEL chain."""
from langchain_core.documents import Document
from langchain_core.embeddings import Embeddings
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_text_splitters import RecursiveCharacterTextSplitter
from common import (CHUNK_OVERLAP, CHUNK_SIZE, DOCS_DIR, PROMPT_TEXT, QUESTIONS,
TOP_K, embedder, get_model)
class MiniLMEmbeddings(Embeddings):
"""Lets LangChain call our local sentence-transformers model."""
def embed_documents(self, texts):
return embedder().encode(texts, normalize_embeddings=True).tolist()
def embed_query(self, text):
return self.embed_documents([text])[0]
docs = [Document(page_content=p.read_text(encoding="utf-8"), metadata={"source": p.name})
for p in sorted(DOCS_DIR.glob("*.txt"))]
splitter = RecursiveCharacterTextSplitter(chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP)
chunks = splitter.split_documents(docs)
store = InMemoryVectorStore.from_documents(chunks, MiniLMEmbeddings())
retriever = store.as_retriever(search_kwargs={"k": TOP_K})
def join(found):
return "\n\n".join(d.page_content for d in found)
prompt = ChatPromptTemplate.from_template(PROMPT_TEXT)
chain = ({"context": retriever | join, "question": RunnablePassthrough()}
| prompt | get_model() | StrOutputParser())
from_documents embeds every chunk and keeps it in memory. as_retriever wraps the store, and k asks for two results. join glues the text of the found Documents into one string.
Now read the chain from left to right. The dictionary at the start builds two inputs at once: context comes from retriever | join, and question is the question passed through untouched by RunnablePassthrough(). Then come the prompt, the model and the parser. Whatever sits on the left of a pipe becomes the input of the part on its right.
Same questions, different chunks
7 chunks
Q: How many days do I have to return an unworn item?
from returns.txt | Returns policy You can return any unworn item w
from returns.txt | To start a return, open your order page and choo
A: You have 30 days from delivery to return an unworn item with its tags attached. Sale items get 14 days.
Q: Do you ship to Canada, and how long does it take?
from shipping.txt | We also ship to Canada. Delivery to Canada takes
from shipping.txt | Shipping Standard delivery inside the United St
A: Yes. Delivery to Canada takes 7 to 10 business days and costs 12 dollars. Customers pay any import fees.
Both versions find the right files. The replies match because they are scripted test model replies. The interesting difference is the first line: 12 chunks by hand, 7 in LangChain.
Why 12 pieces become 7 chunks
The splitter has two settings: chunk_size=250 characters and chunk_overlap=30. Its first cut is the same as ours, at every blank line. That gives 12 pieces, and three of them are only a heading ("Returns policy" is 14 characters, "Shipping" and "Warranty" are 8 each). Then it packs small neighbours back together, as long as the result stays under 250 characters.
shipping.txt and warranty.txt do the same, and we land on 7 chunks. That's why the LangChain run shows "Returns policy" and "Shipping" at the start of some retrieved chunks: each heading now travels with its text.
Open the kit: each step on its own
A chain hides its steps, but it does not remove them. 03_inside_the_chain.py calls every part by itself with the Canada question.
"""What the chain hides: look at each step on its own."""
from importlib import import_module
rag = import_module("02_langchain_rag")
question = rag.QUESTIONS[1]
found = rag.retriever.invoke(question)
print("1. retriever.invoke ->", len(found), "Documents")
print(" metadata of the first:", found[0].metadata)
value = rag.prompt.invoke({"context": rag.join(found), "question": question})
print("2. prompt.invoke -> a prompt of", len(value.to_string()), "characters")
message = rag.get_model().invoke(value)
print("3. model.invoke ->", type(message).__name__)
text = rag.StrOutputParser().invoke(message)
print("4. StrOutputParser -> plain text:", text[:40] + "...")
1. retriever.invoke -> 2 Documents
metadata of the first: {'source': 'shipping.txt'}
2. prompt.invoke -> a prompt of 455 characters
3. model.invoke -> AIMessage
4. StrOutputParser -> plain text: You have 30 days from delivery to return...
The retriever returns two Documents, both from shipping.txt. The filled prompt is 455 characters: the instruction, the two chunks, then the question. The model returns an AIMessage, and the parser pulls out plain text.
Look at step 4: the reply is about returns, not Canada. get_model() built a fresh stand-in here, and a fresh FakeListChatModel always starts with its first scripted line. A real model would answer from the two shipping Documents in the prompt. This is also the debugging lesson: when an answer looks wrong, call the retriever on its own first and read what came back.
What the kit saves, and what it hides
| By hand | LangChain | |
|---|---|---|
| Lines of logic | 20 | 16 |
| Chunks from the three files | 12 | 7 |
| Where the cut, the score and the prompt are visible | In your own code | Only when you call each part alone |
| Swap the splitter, store or model | Rewrite the function | Change one line |
The LangChain version is only a little shorter. The real gain is swapping: another splitter, another vector store (for example pgvector instead of memory) or another model, and the chain stays the same. The cost is that the parts are out of sight. For when LangChain is worth it at all, see What LangChain Is For, and When to Skip It.
Common mistakes
- Forgetting
RunnablePassthrough(). The prompt needs bothcontextandquestion. Without the passthrough branch, the question never reaches the template. - Piping the retriever straight into the prompt. The retriever returns a list of Documents.
jointurns them into one string first. - Judging the chain by the answer only. A wrong answer usually starts with the wrong chunks. Print
retriever.invoke(question)before you touch the prompt. - Assuming chunk size means one chunk per paragraph. The splitter packs neighbours together up to the size limit, so your chunk count changes when you change
chunk_size.
Quick recap
| Part | Job |
|---|---|
Document | The text plus where it came from (metadata["source"]) |
RecursiveCharacterTextSplitter | Cuts at blank lines, then packs neighbours up to chunk_size |
InMemoryVectorStore | Embeds and keeps every chunk |
| retriever | A question in, the k closest Documents out |
| LCEL chain | {"context": retriever | join, "question": RunnablePassthrough()} | prompt | model | parser |
For the stages of the pipeline itself, see The RAG Pipeline Explained. To keep the chunks in Postgres instead of memory, the next step is RAG on pgvector in FastAPI.
Try it yourself
Set CHUNK_SIZE = 120 in common.py and run 02_langchain_rag.py again. Watch how the chunk count changes, and check whether the retriever still finds returns.txt and shipping.txt first.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
A customer types "I cannot log in" and keyword search finds nothing, although a password-reset article exists. Turn meaning into numbers by hand, find the nearest point with math.dist, build a three-topic toy embedder that finds the right article at 1.00, and watch it score 0.00 on "I can't get into my account".
The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
Ingest, chunk, embed, store, retrieve, rerank and generate, in one Python file. Follow one question through a 26-chunk employee handbook to an answer that cites its source.
Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
Ask one question of a whole collection of vectors: which items are closest to this one? Normalise, score every row with one matrix multiply, keep the top k or everything above a threshold, and check it with NearestNeighbors.
Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
A smart model has never read your company's files, and they change every month. Three ways to give it the facts: paste everything, fine-tune, or retrieve only the right pieces. Follow a refund-policy question through all three and see why RAG wins when documents change.
