Build a RAG Pipeline in Python: End-to-End Guide (2026)

A large language model sounds confident about things it was never trained on: your internal docs, last week’s release notes, that niche product you shipped. Retrieval-Augmented Generation (RAG) fixes this without fine-tuning. You fetch the relevant text at question time and hand it to the model as context.

In this guide you build a complete RAG pipeline in Python: chunk documents, embed them, store them in a vector database, retrieve the most relevant chunks for a question, and generate a grounded answer. You also get a small evaluation script, because a pipeline you cannot measure is a pipeline you cannot fix.

What you are building

The whole pipeline is five stages:

[Documents] -> [Chunking] -> [Embeddings] -> [Vector store]
                                                    |
[User question] -> [Embed query] -> [Retrieve top-k] -> [LLM] -> [Answer]

Documents get broken into chunks, each chunk becomes a vector (an embedding), and those vectors are stored. When a question arrives, you embed it too, find the chunks with the closest vectors, and paste them into the prompt so the model answers from real information instead of guessing.

Prerequisites

  • Python 3.10 or newer
  • Ollama installed, with two models pulled:
ollama pull nomic-embed-text   # embeddings, runs locally
ollama pull llama3.1           # chat model that writes answers

Install the Python packages:

pip install chromadb sentence-transformers ollama

Everything below runs on your machine except the generation step, which hits your local Ollama server. Swap llama3.1 for any model you prefer later; the code only touches one function.

Step 1: Chunk your documents

Chunking is the least glamorous part of RAG and the one that breaks the most pipelines. Chunks that are too long bury the relevant sentence in noise. Chunks that are too short lose the surrounding context the model needs. Overlap between chunks keeps sentences that straddle a boundary from being cut in half.

A simple character-based splitter with overlap:

def chunk_text(text: str, chunk_size: int = 600, overlap: int = 100) -> list[str]:
    chunks = []
    start = 0
    while start < len(text):
        chunks.append(text[start:start + chunk_size])
        start += chunk_size - overlap
    return chunks

This works for a first version. Know its limits: it cuts mid-sentence and counts characters, not tokens. In production you will want a token-aware splitter (LangChain’s RecursiveCharacterTextSplitter or the tiktoken-based equivalent) that prefers splitting on paragraph and sentence boundaries.

Practical starting points:

Setting Suggestion Why
Chunk size 400-800 characters Small enough for one idea, large enough for context
Overlap 10-20% of chunk size Protects sentences crossing a boundary
Structured docs Split on headings first Keeps a section together instead of slicing it

There is no universal best chunk size. 600 with 100 overlap is a sane default, not a law. Tune it against real questions from your users, using the evaluation script at the end of this guide.

Step 2: Turn chunks into embeddings

An embedding is a list of floating-point numbers that represents the meaning of a text. Two chunks about the same topic end up close together in vector space; unrelated chunks end up far apart. Retrieval is just “find the nearest vectors.”

Load a sentence-transformers model. all-MiniLM-L6-v2 is small (384 dimensions), fast, and free to run locally:

from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")

def embed_texts(texts: list[str]) -> list[list[float]]:
    return model.encode(texts, normalize_embeddings=True).tolist()

def embed_query(query: str) -> list[float]:
    return model.encode(query, normalize_embeddings=True).tolist()

Normalized embeddings pair well with cosine similarity, which ChromaDB uses when you set hnsw:space to cosine.

An honest caveat: a general-purpose embedding model understands general language well and your domain’s jargon poorly. If your documents are full of internal acronyms, expect retrieval quality to drop. That is when you start looking at domain-specific embedding models or fine-tuning, not before.

Step 3: Store chunks in a vector database

ChromaDB stores the text, the vector, and metadata together, and searches by vector similarity:

import chromadb

client = chromadb.PersistentClient(path="./chroma_db")
collection = client.get_or_create_collection(
    "docs",
    metadata={"hnsw:space": "cosine"},
)

def ingest(doc_id: str, text: str):
    chunks = chunk_text(text)
    collection.add(
        ids=[f"{doc_id}-chunk-{i}" for i in range(len(chunks))],
        documents=chunks,
        embeddings=embed_texts(chunks),
        metadatas=[{"doc_id": doc_id, "chunk_index": i} for i in range(len(chunks))],
    )

Metadata like doc_id matters more than it looks. Once you have ten documents you will want to answer “which document did this come from” and filter retrieval by source. Add metadata now; retrofitting it later means re-ingesting everything.

Example ingestion:

docs = {
    "refund-policy": """...paste your refund policy text here...""",
    "shipping-faq": """...paste your shipping FAQ text here...""",
}

for doc_id, text in docs.items():
    ingest(doc_id, text)
print(f"Stored {collection.count()} chunks")

Step 4: Retrieve the relevant chunks

At query time, embed the question and pull the nearest chunks:

def retrieve(question: str, k: int = 4) -> list[dict]:
    results = collection.query(
        query_embeddings=[embed_query(question)],
        n_results=k,
    )
    return [
        {"text": doc, "metadata": meta, "distance": dist}
        for doc, meta, dist in zip(
            results["documents"][0],
            results["metadatas"][0],
            results["distances"][0],
        )
    ]

k = 4 is a starting point. More chunks give the model more context; they also burn more context window and give it more chances to get confused by a near-miss. For a 600-character chunk size, 3-5 chunks is a reasonable range.

Step 5: Generate the answer from retrieved context

The prompt template is where you keep the model honest. Tell it to use only the provided context and to say it does not know when the answer is not there:

PROMPT_TEMPLATE = """Answer the question using ONLY the context below.
If the answer is not in the context, say "I don't know" and stop.

Context:
{context}

Question: {question}

Answer:"""

def generate(question: str, chunks: list[dict]) -> str:
    import ollama
    context = "nn---nn".join(c["text"] for c in chunks)
    prompt = PROMPT_TEMPLATE.format(context=context, question=question)
    response = ollama.chat(
        model="llama3.1",
        messages=[{"role": "user", "content": prompt}],
    )
    return response["message"]["content"]

This instruction is the one that keeps the system trustworthy. A RAG system that refuses to answer when context is missing beats one that hallucinates a plausible answer. Test it: ask a question your documents cannot answer, and confirm the model actually refuses.

Step 6: Put it all together

def ask(question: str) -> str:
    chunks = retrieve(question, k=4)
    return generate(question, chunks)

print(ask("What is your refund policy?"))

That is the entire pipeline. Six steps, no framework required, every moving part visible.

How to evaluate your retrieval

Most RAG tutorials stop at “it printed an answer.” Answers can look right while coming from the wrong chunks. A tiny evaluation script catches this early: write questions where you know the correct source chunk, and measure how often retrieval finds it.

def evaluate(test_cases: list[tuple[str, str]], k: int = 4) -> float:
    """test_cases: (question, expected doc_id) pairs. Returns recall@k."""
    hits = 0
    for question, expected_doc_id in test_cases:
        chunks = retrieve(question, k=k)
        if any(c["metadata"]["doc_id"] == expected_doc_id for c in chunks):
            hits += 1
    return hits / len(test_cases)

test_cases = [
    ("How long do I have to return an item?", "refund-policy"),
    ("How much does shipping cost?", "shipping-faq"),
]

score = evaluate(test_cases)
print(f"Retrieval recall@4: {score:.0%}")

Start with 10-20 hand-written pairs. This will not prove production quality, but it gives you a number that moves when you change chunk size, overlap, or k. A retrieval score of 100% on your own hand-written questions means “probably fine,” not “proven.” Expanding the test set with real user questions is the honest next step before you declare the pipeline good.

Common pitfalls worth knowing

  • Chunking by fixed size across headings. A table or procedure split in half produces chunks that retrieve well but read badly. Split structured documents on headings or logical sections first.
  • Trusting similarity scores as truth. A low distance means “looks similar to the query,” not “answers the question.” Always inspect retrieved chunks on real queries before wiring generation to them.
  • Ignoring unanswerable questions. If you skip the “I don’t know” instruction, the model will invent policies, prices, and dates. Test with out-of-scope questions deliberately.
  • Context window overflow. Concatenating retrieved chunks with no length check will eventually exceed the model’s limit. Sum the chunk lengths before building the prompt, and trim the lowest-ranked chunks if needed.
  • Evaluating only the final answer. When an answer is wrong, check whether retrieval or generation failed. Fix the stage that failed instead of guessing.

What is the difference between RAG and fine-tuning?

RAG keeps knowledge in an external store you can update by re-ingesting documents, which takes minutes. Fine-tuning bakes knowledge into the model weights, which takes hours or days and is hard to undo. Use RAG when your knowledge changes often or when you need to cite sources. Fine-tuning fits cases where you want the model to learn a style, a format, or behavior rather than facts. Many production systems use both.

Next steps

From this baseline, the upgrades that pay off fastest are: metadata filtering (search only the relevant document type), query rewriting (turn a vague question into a better search query), and reranking (a second, heavier model that reorders the top-k chunks). Add them one at a time, and keep measuring with the evaluation script so you know which change actually helped.

Build the small version first, measure it honestly, and only add complexity when the numbers tell you to.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.