Velamuvi AIAcademy

Lesson 4 of 16 · Foundations

Your First RAG Pipeline

Build a RAG pipeline step by step: index documents, retrieve with a minimum score, build a grounded prompt, skip the LLM when nothing matches, then generate.

  • 7 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Build a working RAG pipeline: index, retrieve, prompt, generate
  • Use a minimum score so weak matches never reach the model
  • Write a prompt that keeps the model to the sources
  • Connect the pipeline to a real LLM API

The plan

You'll build a question-answering assistant for the company handbook from the earlier lessons, in four small functions:

  1. Index: embed every section once.
  2. Retrieve: embed the question, rank the sections, keep the good matches.
  3. Build the prompt: instructions, sources, question.
  4. Answer: call the LLM, or reply “not found” without calling it.

The pipeline

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.",
}

# ---- Index once ----
INDEX = [(title, embed(title + ". " + text)) for title, text in HANDBOOK.items()]

def retrieve(question, k=2, min_score=0.3):
    q = embed(question)
    scored = sorted(((cosine(q, v), title) for title, v in INDEX), reverse=True)
    return [(score, title) for score, title in scored[:k] if score >= min_score]

def build_prompt(question, results):
    sources = "\n\n".join(f"Source: {title}\n{HANDBOOK[title]}" for _, title in results)
    return (
        "You answer employees' questions using ONLY the handbook sources below.\n"
        "If the sources don't contain the answer, say: I couldn't find that in the handbook.\n"
        "End with the name of the source you used.\n\n"
        f"{sources}\n\nQuestion: {question}"
    )

def answer(question):
    results = retrieve(question)
    if not results:
        return "NO SOURCES: reply 'I couldn't find that in the handbook.' without calling the LLM."
    return build_prompt(question, results)       # in a real app: return call_llm(prompt)

for question in ["Can I work from home on Fridays?", "Is there a gym?"]:
    print("=" * 60)
    print(answer(question))

Walk through what happened:

  • “Can I work from home on Fridays?” retrieved only “Remote work”. The second-best section (Business travel, score 0.27) fell below the minimum score of 0.3, so it was left out instead of distracting the model.
  • “Is there a gym?” matched nothing. The app replies “I couldn't find that in the handbook” without calling the LLM. That saves money and removes any chance of a made-up answer.

The prompt

The prompt does three jobs:

  • It tells the model to use only the sources, which reduces made-up details.
  • It gives an exact fallback sentence for when the sources don't answer the question, so the app can detect it.
  • It asks for the source name, so readers can check.

The next lessons improve each part: better chunks, better retrieval, and citations checked by code.

Calling a real LLM

To finish the pipeline, replace the comment return call_llm(prompt) with a real call. On your own computer, with an API key (see the Working with AI APIs course), for example with Anthropic's SDK:

import anthropic

client = anthropic.Anthropic()          # reads ANTHROPIC_API_KEY from the environment

def call_llm(prompt):
    message = client.messages.create(
        model="MODEL_NAME",             # copy a current model name from the docs
        max_tokens=400,
        temperature=0,                  # factual answers: keep it focused
        messages=[{"role": "user", "content": prompt}],
    )
    return message.content[0].text

or with OpenAI's:

from openai import OpenAI

client = OpenAI()                       # reads OPENAI_API_KEY from the environment

def call_llm(prompt):
    response = client.responses.create(model="MODEL_NAME", input=prompt)
    return response.output_text

For “Can I work from home on Fridays?”, a typical reply is:

Output
Yes, as long as your manager agrees. You can work from home up to 3 days a week, so Fridays can be one of them. Source: Remote work

And for the real embedding step, swap embed for a call to an embedding model and the list for a vector database, exactly as in the Vector Databases course. The rest of the code doesn't change.

Common mistakes

Practice exercise

Build the sources part of a RAG prompt: only good matches, numbered so the model can cite them.

Your solutionPython
results = [(0.92, "Remote work"), (0.41, "Equipment"), (0.12, "Training")]
texts = {
    "Remote work": "Work from home up to 3 days a week.",
    "Equipment": "New starters get a laptop, a monitor and a headset.",
    "Training": "Every employee has a learning budget of 1,000 euros.",
}
min_score = 0.4

# Print a numbered sources block, keeping only results with score >= min_score:
# [1] Remote work: Work from home up to 3 days a week.
# [2] ...
Knowledge check

Retrieval finds no section above the minimum score. What should a well-built RAG app do?

Summary

  • A first RAG pipeline is four functions: index, retrieve, build the prompt, answer.
  • A minimum score keeps weak matches away from the model; when nothing passes, reply “not found” without calling the LLM.
  • The prompt says use only the sources, gives an exact fallback and asks for the source.
  • Swapping in a real embedding model, vector database and LLM doesn't change the structure.

Next: getting clean text out of PDFs, web pages and other documents.

Finished reading? Tick it off to track your progress.