RAG Tutorial for Beginners: Build a Retrieval Pipeline in Python

Large language models write fluently, but they only know what was in their training data. They cannot read your company handbook, last week’s tickets or a product manual published yesterday, and when they lack facts they may guess. Retrieval augmented generation, or RAG, fixes this by looking up relevant passages first and handing them to the model with the question. This RAG tutorial for beginners explains how that works and walks you through building a small retrieval pipeline in Python.

You will chunk documents, create embeddings, search them, rerank the results and build a grounded prompt with citations. The code runs on a laptop with open source models, and the generation step works with whichever LLM provider you use. If you want to go further with production RAG, evaluation and LLMOps, our live LLM engineering and RAG training covers those topics with hands-on labs.

Key takeaways

  • RAG retrieves relevant text at question time and adds it to the prompt, so answers can use private and current information.
  • The core pipeline is: chunk, embed, index, retrieve, optionally rerank, then generate from a grounded prompt.
  • A fast bi-encoder finds candidates; a slower cross-encoder reranks the short list for precision.
  • Most quality problems come from retrieval (bad chunks, wrong passages), not from the language model.
  • RAG updates knowledge without retraining, while fine-tuning changes model behavior; many teams use both.

What is RAG (retrieval augmented generation)?

RAG combines two kinds of memory. The language model’s parameters hold general knowledge learned in training. A separate, searchable store holds your documents. At question time the system searches the store, picks the most relevant passages and includes them in the prompt, so the model answers from evidence instead of memory alone.

Advertisement

The term comes from a 2020 research paper by Patrick Lewis and colleagues, “Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks.” It paired a pre-trained sequence to sequence model with a dense vector index of Wikipedia accessed by a neural retriever. The paper also pointed out two problems that RAG helps with: showing where an answer came from and updating a model’s knowledge. Today the name covers a broad family of systems built on the same idea.

Why teams use RAG

  • Private knowledge: answer questions about internal policies, contracts or code without sending everything for training.
  • Freshness: add or remove documents and the next answer reflects the change; no retraining needed.
  • Traceability: show the passages used, so users can check the source.
  • Fewer unsupported answers: instructing the model to answer only from the context, and to say when the context is missing, reduces guessing.

How a RAG pipeline works

A RAG system has an indexing side that runs ahead of time and a query side that runs for each question.

Stage What happens Key decision
1. Load Collect text from PDFs, wikis, tickets or databases. Clean extraction, metadata such as title and date.
2. Chunk Split documents into passages small enough to retrieve precisely. Chunk size and overlap.
3. Embed Turn each chunk into a vector that captures its meaning. Embedding model.
4. Index Store vectors, text and metadata for fast search. Vector database or a vector index in an existing database.
5. Retrieve Embed the question and find the most similar chunks. How many results (top k), filters.
6. Rerank Score the short list again with a more precise model. Whether the gain is worth the latency.
7. Generate Send question plus passages to the LLM with clear instructions. Prompt design, citations, refusal rule.

RAG tutorial for beginners: build a pipeline in Python

This example uses the open source sentence-transformers library. Its documentation describes two model types that map neatly onto RAG: bi-encoders, which turn each text into an embedding so similarity search is very fast, and cross-encoders, which score a query and passage together and are typically more accurate but slower. That is why a common design retrieves with a bi-encoder and reranks the top results with a cross-encoder.

Step 1: Install the library

pip install sentence-transformers

The first run downloads two small pre-trained models from Hugging Face. The knowledge base below is a fictional company’s HR policy, written for this tutorial.

Step 2: Chunk, embed and retrieve

from sentence_transformers import SentenceTransformer, CrossEncoder

# 1. Your knowledge base: in a real project these come from PDFs, wikis or tickets
documents = {
    "leave-policy.md": (
        "Employees in the US accrue 15 days of paid time off per year. "
        "Unused days can be carried over up to a maximum of 5 days. "
        "Requests must be submitted in the HR portal at least two weeks in advance."
    ),
    "uk-leave-policy.md": (
        "UK employees receive 25 days of annual leave plus bank holidays. "
        "Carry-over is limited to 5 days and must be used by the end of March."
    ),
    "expenses.md": (
        "Travel expenses must be filed within 30 days with itemized receipts. "
        "Economy class is required for flights under six hours."
    ),
}

# 2. Chunking: split each document into small overlapping word windows
def chunk_text(text, size=40, overlap=10):
    words = text.split()
    step = size - overlap
    return [" ".join(words[i:i + size]) for i in range(0, len(words), step)]

chunks, sources = [], []
for name, text in documents.items():
    for piece in chunk_text(text):
        chunks.append(piece)
        sources.append(name)

# 3. Embed the chunks once and keep the vectors as your index
embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
chunk_vectors = embedder.encode_document(chunks)

# 4. Retrieve: embed the question and rank chunks by similarity
def retrieve(question, k=3):
    query_vector = embedder.encode_query(question)
    scores = embedder.similarity(query_vector, chunk_vectors)[0]
    top = scores.argsort(descending=True)[:k]
    return [(chunks[i], sources[i], float(scores[i])) for i in top]

Each chunk keeps a pointer to its source file, which you need later for citations. encode_document and encode_query produce the embeddings, and similarity compares the question vector with every chunk vector. In production you would store the vectors in a vector index instead of a Python list, but the logic is identical.

Step 3: Rerank the candidates

# 5. Optional rerank with a cross-encoder for better precision
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")

def retrieve_and_rerank(question, k=3, final_k=2):
    candidates = retrieve(question, k)
    ranked = reranker.rank(question, [c[0] for c in candidates])
    return [candidates[r["corpus_id"]] for r in ranked[:final_k]]

The retriever casts a wide net (top 3 here, usually many more in real systems), and the cross-encoder reorders that short list. rank returns results sorted by score, each with a corpus_id pointing back to the candidate list.

Step 4: Build a grounded prompt

# 6. Augment: build a grounded prompt with numbered, cited context
def build_prompt(question, passages):
    context = "\n".join(
        f"[{n}] ({source}) {text}" for n, (text, source, _) in enumerate(passages, 1)
    )
    return (
        "Answer the question using only the context below. "
        "Cite sources like [1]. If the answer is not in the context, say you don't know.\n\n"
        f"Context:\n{context}\n\nQuestion: {question}\nAnswer:"
    )

question = "How many leave days can a UK employee carry over?"
passages = retrieve_and_rerank(question)
print(build_prompt(question, passages))

Notice the three instructions: use only the context, cite the numbered sources, and admit when the answer is missing. These three rules are the core of a grounded prompt.

Advertisement

Step 5: Generate the answer

Send the prompt to the LLM you use, through your provider’s official SDK or a self-hosted model. Keep the call in one small function, for example generate(prompt), so you can switch models without touching retrieval. With the sample data, a well behaved model should answer that UK employees can carry over up to 5 days, used by the end of March, and cite the UK policy.

How to improve RAG quality

  • Chunk by structure: split on headings and paragraphs rather than fixed word counts where you can, and keep the document title with each chunk.
  • Use metadata filters: region, product or date filters stop the US policy from answering a UK question.
  • Add keyword search: combining vector search with classic keyword search (often called hybrid search) helps with product codes, names and acronyms that embeddings can miss.
  • Rerank: a cross-encoder on the top candidates often fixes “right document, wrong order” problems.
  • Evaluate retrieval separately: build a small set of real questions with known source passages and check whether the right chunk appears in the top results before judging the final answers.
  • Keep the index fresh: re-embed changed documents and delete removed ones on a schedule.

RAG vs fine-tuning

RAG Fine-tuning
Best for Facts that change, private documents, citations Style, format, domain language, task behavior
Updating knowledge Add or remove documents Train again
Shows sources Yes, by design Not by itself
Main effort Data pipeline and retrieval quality Training data and evaluation

RAG also pairs well with tool use. If you are building assistants that call external systems, our guide to the Model Context Protocol explains how agents connect to tools and data sources. For the Python and data skills behind good chunking and evaluation, start with the data science tutorial, and if your documents live in a lakehouse, the Microsoft Fabric tutorial shows how to prepare them with notebooks.

Learn LLM engineering and RAG with live, instructor-led training

Our live online LLM engineering and RAG course covers embeddings, vector search, retrieval pipelines, evaluation, fine-tuning and LLMOps for production AI applications. You build hands-on lab projects in live classes, and you can start with a free demo.

Enroll Now Request a Free Demo

Frequently asked questions

What is RAG in simple terms?

RAG adds a search step in front of the model. Before answering, the system finds the most relevant passages in your documents and passes them to the model with the question, so the answer rests on that evidence.

Is RAG better than fine-tuning?

They solve different problems. RAG is better for knowledge that changes or must be cited; fine-tuning is better for teaching a consistent style or task behavior. Many production systems combine them.

Do I need a vector database for RAG?

Not to learn. A Python list works for a few hundred chunks, as in this tutorial. For larger collections you need an index built for similarity search, either a dedicated vector database or a vector extension in a database you already run.

Why does my RAG system give wrong answers?

Usually because retrieval returned the wrong passages: chunks were too large or too small, metadata filters were missing, or keyword-heavy questions needed hybrid search. Check what was retrieved before changing the prompt or the model.

What skills do I need to build RAG applications?

Python, basic data processing, an understanding of embeddings and similarity search, prompt design and evaluation. You can explore related IT training courses in AI, data and cloud to build them step by step.

Sources

  • Lewis et al., “Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks,” arXiv:2005.11401 (2020, revised 2021).
  • Sentence Transformers documentation: Quickstart (SentenceTransformer encode_query, encode_document and similarity; CrossEncoder rank).
  • Hugging Face model cards: sentence-transformers/all-MiniLM-L6-v2 and cross-encoder/ms-marco-MiniLM-L6-v2.
Advertisement

About Tutorials Mania Editorial Team

The Tutorials Mania Editorial Team writes and maintains the site's technology tutorials, interview guides and coverage of AI tools and platforms. Every article is researched against official documentation, product announcements and primary sources, written to explain complex technology in plain language, and updated when products change.
View all posts by Tutorials Mania Editorial Team →