Build a RAG Chatbot with LangChain: A Beginner’s Step-by-Step Guide

Large language models can write fluent answers, but they do not know the contents of your own notes, your college syllabus or your company documents. A RAG chatbot solves this by searching your documents first and answering from what it finds. In this guide you will build a small RAG chatbot in Python, one step at a time, using free tools. Every step explains what the code does and why.

TODO (delete before publishing): Run every code block below yourself. Replace sample outputs with your own, add screenshots, and note the library versions you used (run pip list). Do not publish untested code.

What you will build

By the end you will have a script that loads a PDF, splits it into pieces, converts the pieces into searchable vectors, retrieves the passages that best match a question and builds a prompt for a language model.

TODO (delete before publishing): Add a screenshot of your final chatbot answering a question about your own PDF.

What is RAG in simple words?

RAG stands for Retrieval-Augmented Generation. Think of an open-book exam. Instead of answering from memory, the model first looks up the relevant pages in your book and then writes the answer. The retrieval part finds the right passages. The generation part writes the reply using them.

What you need

  • Python 3.10 or newer installed on your laptop (write the exact version you used).
  • A PDF to test with, for example your own lecture notes.
  • Access to a language model for the final step. We leave the choice to you because free offers and limits change often. Check the provider’s current pricing page before you sign up.

Install the libraries in a virtual environment:

pip install langchain-core langchain-text-splitters langchain-huggingface sentence-transformers pypdf

Step 1: Load your document

First we read the PDF page by page and turn each page into a Document object that keeps the page number. Keeping the source and page number later lets the chatbot say where an answer came from.

from pypdf import PdfReader
from langchain_core.documents import Document

reader = PdfReader("my_notes.pdf")
docs = []
for page_number, page in enumerate(reader.pages):
    text = page.extract_text() or ""
    if text.strip():
        docs.append(Document(
            page_content=text,
            metadata={"source": "my_notes.pdf", "page": page_number + 1},
        ))

print(f"Loaded {len(docs)} pages")

TODO (delete before publishing): Paste your own output here, for example “Loaded 12 pages”.

Step 2: Split the text into chunks

A language model can only read a limited amount of text at once, and searching a whole page for one fact is imprecise. So we cut the text into smaller chunks. Each chunk overlaps slightly with the next one, so that an idea is not cut in half at the boundary.

from langchain_text_splitters import RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=100)
chunks = splitter.split_documents(docs)

print(f"Created {len(chunks)} chunks")
print(chunks[0].page_content[:200])

Here chunk_size is the maximum chunk length in characters and chunk_overlap is how many characters are shared between neighbouring chunks. We started with 800 and 100 because they are common starting values, not because they are perfect. In our separate guide we compare different sizes: how to chunk documents for RAG.

Step 3: Turn chunks into embeddings and store them

Computers search by numbers, not meaning. An embedding model converts each chunk into a list of numbers (a vector) so that chunks with similar meaning end up close together. We store the vectors in a vector store, which is a database built for this kind of search.

from langchain_huggingface import HuggingFaceEmbeddings
from langchain_core.vectorstores import InMemoryVectorStore

embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
vector_store = InMemoryVectorStore.from_documents(chunks, embeddings)

This model runs on your own computer, so it needs no account. The first run downloads the model, which can take a few minutes. The in-memory store disappears when the script ends, which is fine for learning. For a store that keeps your data between runs, see our Pinecone free tier tutorial.

Step 4: Retrieve the most relevant chunks

Now we ask a question. The retriever turns the question into a vector and returns the k chunks that are closest to it.

retriever = vector_store.as_retriever(search_kwargs={"k": 3})

question = "What are the main topics covered in this document?"
retrieved = retriever.invoke(question)

for doc in retrieved:
    print(doc.metadata, doc.page_content[:150])
    print("---")

TODO (delete before publishing): Paste your own output and explain whether the retrieved chunks were actually relevant.

Step 5: Build the prompt and ask the model

The last step is to give the model the retrieved text and tell it to answer only from that text. This instruction is what reduces hallucination.

def build_prompt(question, retrieved_docs):
    context = "\n\n".join(doc.page_content for doc in retrieved_docs)
    return (
        "Answer the question using only the context below. "
        "If the answer is not in the context, say you do not know.\n\n"
        f"Context:\n{context}\n\n"
        f"Question: {question}\n"
        "Answer:"
    )

prompt = build_prompt(question, retrieved)
print(prompt)

Send this prompt to the language model of your choice. In LangChain, any chat model object can be called with llm.invoke(prompt).

TODO (delete before publishing): Show the exact model you used, how you set it up and your real answer. If you used a free tier, state its limits as shown on the provider’s page on the date you checked.

Mistakes we made and how we fixed them

TODO (delete before publishing): Write 3 to 5 real problems from your own run, for example: text extracted from the PDF was empty, chunks were too small to make sense, the retriever returned unrelated passages, the model ignored the context. For each one, say what happened, why, and what fixed it. This is the most original part of the article.

Frequently asked questions

Do I need a paid API to build a RAG chatbot?

Not for the retrieval part. The embedding model above runs locally for free. The final answer needs a language model, and some providers offer free tiers, or you can run a small open model locally. Check current limits before you rely on them.

Why does my chatbot say it does not know the answer?

Usually the retriever did not find the right chunk. Print the retrieved chunks, check them, and try a different chunk size or a larger k.

What is the difference between RAG and fine-tuning?

RAG gives the model fresh information at question time by searching your documents. Fine-tuning changes the model itself through extra training. RAG is usually easier for a beginner project and is simple to update: you just add or replace documents.

Can I use more than one PDF?

Yes. Load each file into Document objects with its own source name, add them all to the same list and continue from Step 2.

Where to go next

Scroll to Top