Velamuvi AIAcademy

Lesson 3 of 16 · Foundations

RAG Architecture

RAG architecture explained: the ingestion pipeline (load, chunk, embed, store) and the query pipeline (retrieve, rerank, generate), with a Python skeleton.

  • 6 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Name the stages of the ingestion pipeline and the query pipeline
  • Explain which work happens ahead of time and which happens per question
  • Follow data through a minimal RAG system in Python
  • Know which optional stages to add as a system grows

Two pipelines

Every RAG system is really two programs that share a vector database.

Ingestion (offline)Query (online, per question)
Load files, pages, database rowsRewrite the question (optional)
Clean headers, footers, markupEmbed the question
Chunk into passagesRetrieve the top chunks (with filters)
Embed each chunkRerank them (optional)
Store vectors, text and metadataBuild the prompt and generate
Cite sources, log the interaction

Ingestion can be slow: it runs in the background. The query pipeline must be fast, because a person is waiting.

A minimal system, end to end

Here is the whole skeleton in Python, with one function per stage. It uses the see-inside embedding model from the first lesson and splits each handbook section into sentences:

Try it yourselfPython
import math, re

# ---- A tiny see-inside embedding model: one dimension per concept ----
CONCEPTS = {
    "leave":     "leave holiday holidays vacation annual time-off carried",
    "sick":      "sick ill illness unwell doctor self-certify",
    "remote":    "remote home hybrid office hours",
    "expenses":  "expenses expense claim reimbursed receipt receipts meals",
    "equipment": "laptop laptops monitor headset equipment lost stolen",
    "security":  "password passwords 2fa two-factor login phishing security",
    "parental":  "parental maternity paternity baby birth adoption adoptive",
    "training":  "training course courses learning books conferences",
    "travel":    "travel trip trips flight flights train trains journeys",
    "pay":       "pay paid salary payroll",
}
WORDS = {c: set(words.split()) for c, words in CONCEPTS.items()}

def words(text):
    return re.findall(r"[a-z0-9'-]+", text.lower())

def embed(text):
    v = [sum(w in WORDS[c] for w in words(text)) for c in CONCEPTS]
    length = math.sqrt(sum(x * x for x in v))
    return [x / length for x in v] if length else v

def cosine(a, b):
    return sum(x * y for x, y in zip(a, b))       # vectors are unit length

# ---- The knowledge base: sections of a company handbook ----
HANDBOOK = {
    "Annual leave": "Full-time employees get 25 days of paid annual leave per year, plus public holidays. Book holiday in the HR portal at least two weeks ahead. Up to 5 unused days can be carried over to next year.",
    "Sick leave": "If you are ill, tell your manager before 10am on your first day off. You can self-certify for up to 7 days; after that you need a note from a doctor. Sick pay is your full salary for up to 10 days per year.",
    "Remote work": "You can work from home up to 3 days a week, with your manager's agreement. Core hours are 10am to 4pm. The office is open from 7am to 8pm.",
    "Expenses": "Claim expenses within 30 days in the finance app, with a photo of each receipt. Meals on work trips are reimbursed up to 40 euros per day. Approved expenses are paid with your next salary.",
    "Equipment": "New starters get a laptop, a monitor and a headset. Report a lost or stolen laptop to IT within 24 hours. Laptops are replaced every 4 years.",
    "Security": "Use a password manager and turn on two-factor login (2FA) for every work account. Never share your password. Report phishing emails with the Report button in your mail app.",
    "Parental leave": "Birth parents get 26 weeks of paid parental leave and partners get 4 weeks. Adoptive parents get the same leave as birth parents.",
    "Training": "Every employee has a learning budget of 1,000 euros per year for courses, books and conferences. Courses over 300 euros need your manager's approval.",
    "Business travel": "Book work trips in the travel portal. Fly economy for flights under 6 hours and premium economy for longer flights. Take the train for journeys under 4 hours.",
}

# ================= OFFLINE: the ingestion pipeline =================
def load():
    return [{"source": title, "text": text} for title, text in HANDBOOK.items()]

def chunk(documents):
    chunks = []
    for doc in documents:
        for i, sentence in enumerate(doc["text"].split(". ")):
            chunks.append({"id": f"{doc['source']}#{i}", "source": doc["source"], "text": sentence.rstrip(".")})
    return chunks

def index(chunks):
    for c in chunks:
        c["vector"] = embed(c["source"] + ". " + c["text"])   # embed once, store with the chunk
    return chunks

store = index(chunk(load()))
print(f"Ingestion: {len(HANDBOOK)} documents -> {len(store)} chunks stored")

# ================= ONLINE: the query pipeline =================
def retrieve(question, k=3):
    q = embed(question)
    return sorted(store, key=lambda c: cosine(q, c["vector"]), reverse=True)[:k]

def build_prompt(question, chunks):
    sources = "\n".join(f"[{c['id']}] {c['text']}" for c in chunks)
    return f"Answer from these sources only, and cite them.\n{sources}\nQuestion: {question}"

question = "How long can I self-certify when I'm ill?"
found = retrieve(question)
print("Retrieved:", [c["id"] for c in found])
print()
print(build_prompt(question, found))

Each stage is small and replaceable: load could read PDFs, chunk could split by headings, index could call a real embedding model and a vector database, and retrieve could add a reranker. The shape stays the same, which is why it pays to build RAG as separate stages from the start.

Where the pieces come from

StageTypical tools
Load and cleanPDF and HTML parsers, document converters
ChunkYour own code, or splitters in libraries such as LangChain and LlamaIndex
EmbedAn embedding API or an open embedding model
Store and retrieveA vector database (Chroma, pgvector, Qdrant, Pinecone and others)
RerankA reranking model or API
GenerateAny capable LLM

Frameworks like LangChain and LlamaIndex bundle these stages. They are handy for getting started, but you can build everything with plain code, as this course does, and understanding each stage makes any framework easier to use.

Common mistakes

Practice exercise

Sort the steps of a RAG system into the offline ingestion pipeline and the online query pipeline.

Your solutionPython
steps = ["embed the question", "split documents into chunks", "send the prompt to the LLM",
         "embed each chunk", "load documents", "find the most similar chunks"]

offline = []   # ingestion: done ahead of time, when documents are added or changed
online = []    # query: done for every question

# Put each step in the right list (keep the order above within each list), then print both.
print("Offline:", offline)
print("Online:", online)
Knowledge check

Which step belongs to the ingestion pipeline rather than the query pipeline?

Summary

  • A RAG system has an offline ingestion pipeline (load, clean, chunk, embed, store) and an online query pipeline (embed, retrieve, prompt, generate, cite).
  • Ingestion can be slow; the query pipeline must be fast.
  • Build each stage separately, so you can swap tools and debug one step at a time.
  • Optional stages such as query rewriting and reranking slot into the same shape.

Next: build your first complete RAG pipeline.

Finished reading? Tick it off to track your progress.