Skip to main content
← Back to Blog
2026-02-21 · 9 min readAI AgentsPythonUpdated Oct 31, 2026

Building Your First RAG Pipeline: A Developer’s Guide to Context-Aware AI

A hands-on first RAG pipeline with LangChain, Chroma and OpenAI. You load and chunk a PDF, embed the chunks into a local vector store, wire a retrieval chain that answers only from the found text, add a simple hit-rate check for retrieval, and test the whole thing with fake models before you spend a token.

Avnish Yadav
Avnish Yadav
Developer & Automation Builder
7 views
Building Your First RAG Pipeline: A Developer’s Guide to Context-Aware AI

This guide is for developers who need an LLM to answer from their own documents, not from what it half-remembers. You will build a small retrieval-augmented generation (RAG) pipeline in Python: load a PDF, split it into chunks, store the chunks in a local vector database, and answer questions from what it finds. Then you'll check whether retrieval actually finds the right text, and test the whole pipeline with fake models.

Key takeaways

  • RAG gives the model the relevant text at question time, like an open-book exam. You don't retrain anything.
  • Chunking decides what retrieval can find. Start with the values from LangChain's RAG tutorial (1,000 characters, 200 overlap) and tune from there.
  • Measure retrieval first. If the right chunk never reaches the model, no prompt can fix the answer.

The problem: models are frozen in time

A model learns from data up to a cut-off date. Ask it about a library released last week, or about your company's internal manual, and it may invent a plausible answer. It doesn't know your data, and it doesn't know new data.

For automation work, you want an accurate processor of information, not a creative writer. You could train or fine-tune a model, but that is slow and costly, and it goes stale as your data changes. RAG changes how you ask instead.

Retrieval-augmented generation (RAG) is a pattern where you first retrieve the passages relevant to a question from your own data, then pass them to the model with the question so it answers from them. The name comes from a 2020 paper by Lewis et al.

This post is part 5 of the LLM & LangChain Fundamentals series. In part 4 you joined two prompts into your first LLM chain. Here the first link of the chain is a search over your documents.

How RAG works

RAG is an open-book exam for the model. Instead of asking it to memorize facts, you hand it the right pages when the question comes in.

LangChain's RAG tutorial splits the work into two halves. Indexing loads your data, splits it into chunks, turns each chunk into a numeric vector (an embedding) and stores it. Retrieval and generation finds the chunks closest to the question and has the model answer from them.

This demo uses LangChain to wire the steps, Chroma as a local vector store and OpenAI for embeddings and generation.

Prerequisites

You need Python 3.10 or newer (the langchain-core requirement on PyPI; this post was tested on Python 3.14) and an OpenAI API key for the real run. The test at the end needs none.

pip install -U langchain-core langchain-text-splitters langchain-openai langchain-chroma pypdf pytest

Phase 1: load and chunk

A common mistake, as a rule of thumb, is to store whole documents. Models have limited context, and vector search compares meanings. If a chunk is too big, the one fact you need is buried in a lot of unrelated text, and its vector reflects everything in the chunk.

So you split each document into chunks. How you split matters.

Recursive character splitting

You want related text to stay together. A sentence shouldn't be cut in half, and a paragraph is usually one unit of thought. RecursiveCharacterTextSplitter "recursively tries to split by different characters to find one that works," in the words of its reference page. In the langchain-text-splitters source, the default order is paragraph breaks, then line breaks, then spaces, so it cuts at the most natural point that keeps a chunk under the size limit.

Create rag_pipeline.py:

# rag_pipeline.py
import os

from langchain_core.documents import Document
from langchain_text_splitters import RecursiveCharacterTextSplitter
from pypdf import PdfReader

def load_pdf(path):
    # One Document per PDF page, with the page number kept for citations
    return [
        Document(page_content=page.extract_text(), metadata={"source": path, "page": number})
        for number, page in enumerate(PdfReader(path).pages)
    ]

def load_and_split(path):
    docs = load_pdf(path)
    splitter = RecursiveCharacterTextSplitter(
        chunk_size=1000,      # characters per chunk
        chunk_overlap=200,    # characters shared between neighbouring chunks
        add_start_index=True, # remember where each chunk starts in its page
    )
    return splitter.split_documents(docs)

Checked against langchain-core@1.7.3, langchain-text-splitters@1.1.3, langchain-openai@1.7.3, langchain-chroma@1.1.0, pypdf@6.21.4 and pytest@9.2.0 on Python 3.14, 2026-10-31.

load_pdf reads the PDF with pypdf directly. The ready-made PyPDFLoader lived in langchain-community, which LangChain sunset in May 2026 (issue 674), so it gets no more fixes.

chunk_size=1000 and chunk_overlap=200 are the values in LangChain's RAG tutorial. The overlap helps when a key sentence falls on a chunk boundary: part of it then appears in both chunks, so neither loses the thread completely. Treat both numbers as a starting point, and tune them by measuring retrieval (see the evaluation section).

Phase 2: embeddings and vector storage

To search text by meaning, you turn each chunk into a vector: a long list of numbers. Texts with similar meaning end up close together, so the search becomes "find the vectors nearest to the question's vector."

Chroma is an open-source vector store that runs locally, which suits small tools and prototypes. For choosing a database for production, see the vector database decision framework in part 7. Add this to rag_pipeline.py:

from langchain_chroma import Chroma
from langchain_openai import ChatOpenAI, OpenAIEmbeddings

def build_retriever(splits, embeddings, persist_directory="./chroma_db"):
    vector_store = Chroma(
        collection_name="manual",
        embedding_function=embeddings,
        persist_directory=persist_directory,  # keeps the index between runs
    )
    vector_store.add_documents(splits)
    return vector_store.as_retriever(search_type="similarity", search_kwargs={"k": 4})

When this runs with real embeddings, each chunk goes to OpenAI, comes back as a vector and is stored on disk by Chroma. k=4 means "return the 4 chunks closest to the question." OpenAI's embeddings guide lists text-embedding-3-small, which returns 1,536 numbers per text by default; the run code below uses it.

Phase 3: the retrieval chain

Now connect retrieval to the model. The chain does four things:

  1. Take the user's question.
  2. Search the vector store and get the closest chunks.
  3. Put the question and the chunks into one prompt.
  4. Send it to the model and return the answer.
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough

RAG_TEMPLATE = """You are a technical assistant. Answer the question using only the context below.
If the context doesn't contain the answer, say you don't know. Don't make anything up.

Context:
{context}

Question:
{question}
"""

prompt = ChatPromptTemplate.from_template(RAG_TEMPLATE)

def format_docs(docs):
    return "\n\n".join(doc.page_content for doc in docs)

def build_rag_chain(retriever, llm):
    return (
        {"context": retriever | format_docs, "question": RunnablePassthrough()}
        | prompt
        | llm
        | StrOutputParser()
    )

The dict at the start runs both values on the same input. The retriever turns the question into chunks, format_docs joins them into one string, and RunnablePassthrough passes the question through unchanged.

What about temperature?

You may see RAG examples that set temperature=0 and call the output deterministic. As a rule of thumb, a low temperature reduces variation, but it doesn't make the model stick to your documents. Grounding comes from two things: retrieval that finds the right chunks, and a prompt that tells the model to answer only from them and to say when it can't.

Run it

Add the run code at the bottom of rag_pipeline.py. It sits under if __name__ == "__main__":, so importing the file for tests calls no API:

if __name__ == "__main__":
    # Needs OPENAI_API_KEY and a PDF next to this file.
    splits = load_and_split("./technical_manual.pdf")
    print(f"Split into {len(splits)} chunks.")

    retriever = build_retriever(splits, OpenAIEmbeddings(model="text-embedding-3-small"))
    llm = ChatOpenAI(model=os.getenv("RAG_MODEL", "gpt-6-luna"))
    rag_chain = build_rag_chain(retriever, llm)
    print(rag_chain.invoke("How do I reset the configuration parameters?"))

On the date above, OpenAI's models page calls gpt-6-luna its most efficient model for focused, high-volume tasks. Model ids change often, so check that page and set RAG_MODEL to switch.

Run the script once per PDF. Each run adds the chunks to the stored collection again, so delete the chroma_db folder before you re-index the same file.

Evaluate: does it find the right text?

The pipeline gives an answer. But is it the right answer? Blindly trusting the output is risky in automation. Check two things separately:

  1. Retrieval: did the right chunk reach the model? If the answer is in the PDF but the retriever didn't return it, the system failed before the model ran.
  2. Generation: did the model answer from the context, or did it make something up?

The simplest retrieval check is hit rate: for a set of questions where you know which text holds the answer, count how often that text is among the retrieved chunks. Add it to rag_pipeline.py, above the if __name__ == "__main__": block:

def hit_rate(retriever, cases):
    """cases: list of (question, phrase that the right chunk contains)."""
    hits = sum(
        any(phrase in doc.page_content for doc in retriever.invoke(question))
        for question, phrase in cases
    )
    return hits / len(cases)

Write 20 or so real questions with their expected phrases, and run hit_rate after every change to chunk size, overlap or k. Twenty is a rule of thumb; more questions give a steadier score.

For deeper checks, tools such as Ragas score these as metrics:

Metric What it checks (from the Ragas docs) Likely cause (rule of thumb)
Context precision Whether the retriever ranks relevant chunks above irrelevant ones Search or chunking returns noise
Context recall How much of the relevant information was retrieved The right chunks are missing
Faithfulness Whether every claim in the answer is supported by the retrieved context The model adds facts of its own

As a rule of thumb, if your RAG system feels "dumb," look at retrieval first (chunking and search), and at generation second.

Test the pipeline without an API key

langchain_core ships fake models for tests. DeterministicFakeEmbedding turns text into repeatable vectors, and FakeListChatModel returns the replies you give it. Save this as test_rag_pipeline.py:

# test_rag_pipeline.py
from langchain_core.documents import Document
from langchain_core.embeddings import DeterministicFakeEmbedding
from langchain_core.language_models.fake_chat_models import FakeListChatModel

from rag_pipeline import build_rag_chain, build_retriever, hit_rate

def test_pipeline_wiring(tmp_path):
    splits = [
        Document(page_content="Hold the reset button for 10 seconds to reset the configuration."),
        Document(page_content="The device supports Wi-Fi and Ethernet."),
    ]
    retriever = build_retriever(splits, DeterministicFakeEmbedding(size=64), str(tmp_path))
    chain = build_rag_chain(retriever, FakeListChatModel(responses=["Hold the reset button."]))

    assert chain.invoke("How do I reset the configuration?") == "Hold the reset button."
    # With k=4 and only two chunks, every question retrieves everything: this checks wiring, not quality.
    assert hit_rate(retriever, [("How do I reset it?", "reset button")]) == 1.0

Run it with pytest test_rag_pipeline.py. Importing rag_pipeline.py creates no OpenAI client, so the test needs no API key. With the versions above, on Python 3.14, the test passed. The full script also ran on a one-page sample PDF up to its first API call (the embedding request), with a placeholder key.

Fake embeddings don't capture meaning, so this test can't tell you whether retrieval is good. It tells you the pieces fit together. Retrieval quality comes from hit_rate with real embeddings and real questions.

Beyond the basics

The code above is the "hello world" of RAG. It works for simple documents. With thousands of files or dense technical manuals, plain similarity search starts to miss. Common upgrades:

  • Hybrid search: combine vector search (meaning) with keyword search such as BM25 (exact words). As a rule of thumb, this helps with acronyms, error codes and serial numbers that embeddings blur.
  • Metadata filtering: narrow the search by date, author or file type before comparing vectors.
  • Re-ranking: retrieve more chunks, say 20, then let a re-ranking model sort them and keep the best 5. Cohere's docs describe its Rerank model as sorting documents "from most to least semantically relevant to the query."

Where to go next

RAG grounds a model in your own data. Start with the pipeline above and get ingestion working. Then spend your time on chunk size, overlap and k, measured with a hit-rate check, because, as a rule of thumb, retrieval is where most accuracy is won or lost.

The next part goes deeper into the first step, loading data from PDFs, CSVs and web pages, in LangChain document loaders.

Frequently asked questions

What is a good chunk size for RAG?

There is no universal value. LangChain's RAG tutorial uses 1,000 characters with a 200-character overlap, which is a sensible start. Change one setting at a time and keep the one with the better hit rate on your own questions.

Why does my RAG pipeline give wrong answers?

Check retrieval first. Print the chunks the retriever returns for a failing question. If the right text isn't there, fix chunking, k or the search method. If it is there and the answer is still wrong, tighten the prompt so the model answers only from the context.

Does temperature 0 stop RAG hallucinations?

No. As a rule of thumb, a lower temperature makes outputs vary less, but it doesn't make the model stick to your documents. Good retrieval plus a prompt that says "answer only from the context, or say you don't know" does more.

How do I evaluate a RAG system?

Measure retrieval and generation separately. A hit-rate check tells you whether the right chunk was retrieved. Tools such as Ragas add metrics like context precision, context recall and faithfulness, which checks that each claim in the answer is supported by the retrieved text.

Sources

Verified against the sources below on October 31, 2026. Products and docs change often: check the linked sources if something looks different.

  1. LangChain docs: Build a RAG agent
  2. LangChain docs: Chroma integration
  3. LangChain reference: RecursiveCharacterTextSplitter
  4. OpenAI API: Vector embeddings guide
  5. OpenAI API: Models
  6. Ragas docs: Faithfulness
  7. Ragas docs: Context precision
  8. Ragas docs: Context recall
  9. Cohere docs: Rerank overview
  10. Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks (Lewis et al.)
  11. langchain-text-splitters source: character.py
  12. langchain-chroma on PyPI
  13. langchain-core on PyPI
  14. pypdf docs: Extract text from a PDF
  15. langchain-community: sunset announcement (issue 674)
All 14 parts in this series
Share
Discussion

Comments

Loading comments...

Add a comment

Comments are reviewed before they appear.