Building a RAG Pipeline

Updated · 7 min read
mediumPython 3.13airagpythonembeddingspipeline

A RAG pipeline is the code that connects document search to a model. It has two phases. Indexing happens ahead of time: load the documents, split them into chunks and embed each chunk. Answering happens for every question: embed the question, retrieve the closest chunks, and send them to the model with the question.

This lesson builds a complete pipeline over three short school documents, in about 30 lines of Python.

Two Phases

Index once, then answer every question
StepPhaseDescription
LoadIndexingIt is used to read the documents, keeping each one's name
ChunkIndexingIt is used to split documents into passages small enough to match one idea
Embed and storeIndexingIt is used to turn each chunk into a vector, kept with its text and source
RetrieveAnsweringIt is used to find the chunks closest to the question
GenerateAnsweringIt is used to have the model answer from those chunks only

Creating the Documents

This program saves three short, made-up school documents into a docs folder:

Python
from pathlib import Path
 
DOCS = {
    "fee-policy.md": """# Fee Policy, 2026-27 School Year (updated August 1, 2026)

The science lab fee is $45 a year and the library fee is $15 a year. Both are due by September 30.

Field trips cost $30 per trip, payable two weeks before the trip. The sports program costs $60 a season, including the uniform.

Tuition is $250 a month, due on the first school day of each month. Siblings get a 10% discount on tuition from the second child onward.

Fees can be paid online by card or bank transfer through the parent portal, or in cash at the school office from 8 a.m. to 3 p.m.

A late fee of $10 is added when a payment is more than 14 days overdue.

Families with financial need can apply for a fee waiver at the school office with proof of income. Decisions are made within 10 school days. Waivers cover lab, library and field trip fees, but not tuition.""",
    "admission-guide.md": """# Admission Guide for the 2027-28 School Year

Admission forms are due by March 1. Apply with the online form, a birth certificate and the last school report.

Interviews take place in March and last about 20 minutes. Decisions are sent by email in the second week of April.

There is no admission test for grades 9 and 10. Grade 11 applicants take a short math and English placement test.

Students moving from another state can join mid-year if a place is free. Vaccination records are needed before the first day.""",
    "travel-policy.md": """# Staff Travel Reimbursement Policy (effective July 1, 2026)

Staff who use a personal car for approved school trips are paid 70 cents per mile.

On overnight trips, meals are reimbursed up to $50 a day with itemized receipts. Alcohol is never reimbursed.

Hotel stays must be approved by the principal before booking. Book the standard room rate; upgrades are not reimbursed.

Submit claims within 30 days of the trip through the finance portal, with all receipts attached. Approved claims are paid within two pay periods.""",
}
 
Path("docs").mkdir(exist_ok=True)
for name, text in DOCS.items():
    Path("docs", name).write_text(text + "\n")
print("Saved", len(DOCS), "documents:", ", ".join(DOCS))
Output
Saved 3 documents: fee-policy.md, admission-guide.md, travel-policy.md

Example: The Whole Pipeline

Python
from pathlib import Path
 
from sentence_transformers import SentenceTransformer
 
from model_api import ModelClient
 
# 1. Load and split: one chunk per paragraph, remembering where it came from
chunks = []
for path in sorted(Path("docs").glob("*.md")):
    for paragraph in path.read_text().split("\n\n"):
        if not paragraph.startswith("#"):  # skip titles
            chunks.append({"source": path.name, "text": paragraph.strip()})
 
# 2. Embed every chunk once
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
vectors = model.encode([c["text"] for c in chunks], normalize_embeddings=True)
print("Indexed", len(chunks), "chunks")
 
# 3. Retrieve the three closest chunks
question = "Can I claim my hotel for the science fair trip in October?"
scores = vectors @ model.encode(question, normalize_embeddings=True)
best = scores.argsort()[::-1][:3]
for i in best:
    print(f"Retrieved {scores[i]:.2f} from {chunks[i]['source']}")
context = "\n\n".join(f"[{chunks[i]['source']}] {chunks[i]['text']}" for i in best)
 
# 4. Generate an answer from the retrieved text only
client = ModelClient()
reply = client.chat(
    [{"role": "user", "content": f"Documents:\n{context}\n\nQuestion: {question}"}],
    system=("Answer only from the documents provided, in two sentences or fewer, and name the source file. "
            "If the documents don't answer the question, say so."),
    max_tokens=500,
)
print("Answer:", reply.text)

Example output. The Indexed and Retrieved lines are real output of this code. The answer was produced by an AI model on November 16, 2026, to show the shape; the program ran end to end against a local test server that returned it, not a live API.

Output
Indexed 14 chunks
Retrieved 0.42 from travel-policy.md
Retrieved 0.29 from travel-policy.md
Retrieved 0.27 from fee-policy.md
Answer: Yes, if the principal approves the hotel before you book it, at the standard room rate; submit the claim with receipts within 30 days (source: travel-policy.md).

Explanation: Step 1 splits each document at blank lines, so every paragraph becomes a chunk that remembers its file name. Step 2 embeds all 14 chunks once. Step 3 embeds the question and keeps the three closest chunks; the hotel paragraph of the travel policy scores highest (0.42). Step 4 sends those chunks to the model with a strict rule: answer only from these documents and name the source.

Making It Real

ConcernWhat production pipelines add
Many documentsA vector database instead of an in-memory array
Changing documentsRe-index a document whenever it changes
PDFs and web pagesText extraction that keeps headings and tables readable
Who may see whatMetadata filters so people only retrieve documents they're allowed to read

Common Mistakes

Losing track of sources. Store the file name with every chunk, or you can't cite.

Embedding the documents on every question. Index once; embed only the question at answer time.

Leaving out the "only from these documents" rule. The model may fill gaps with general knowledge.

Interview Corner

What are the two phases of a RAG pipeline?

Indexing (load, chunk, embed, store), done ahead of time, and answering (embed the question, retrieve, generate), done for every question.

How do you debug a wrong RAG answer?

Look at what was retrieved first. If the right passage wasn't retrieved, fix retrieval (chunking, search, filters); if it was, fix the prompt or the model step.

Practice

Exercise: ask the pipeline more questions. Change question to "Is there a test to get into grade 11?" and then "How fast are travel claims paid?". Note the top retrieved chunk and score for each. Is the right paragraph always first?

Check your understanding:

  1. Which steps happen ahead of time?
  2. Why does every chunk store its source?
  3. What should you check first when an answer is wrong?

Quick check: RAG pipeline

4 questions
1When are the documents embedded?
2How many chunks did the three documents make?
3Why keep the file name with each chunk?
4An answer is wrong. What do you check first?

Key Takeaways

Quick reference

StepCode
Splittext.split("\n\n")
Embed chunksmodel.encode(texts, normalize_embeddings=True)
Retrievescores.argsort()[::-1][:3]
Generateclient.chat(messages, system="Answer only from ...")

Was this tutorial helpful?

Lesson 96 of 186