InferenceAIAll articles

Build Your First RAG App in Python: A Student Portfolio Project

By InferenceAI Editorial · 12 min read · intermediate · Updated

Build retrieval-augmented generation from first principles (chunking, retrieval, prompting, citations), then evaluate it and turn it into a portfolio project.

"Built a RAG chatbot" is probably the most common line on student AI CVs right now. Most of those projects are a framework tutorial with the names changed. That's a shame, because a well-built RAG project is one of the best ways to show you understand modern AI engineering: retrieval, prompting, evaluation and honest handling of failure.

In this tutorial we'll build the core of a RAG system from first principles in plain Python, so you understand every moving part. Then we'll add the thing almost every student project skips, an evaluation, and finish with how to upgrade it into a portfolio piece that stands out.

Our example is a "course assistant" that answers questions about a syllabus. Swap in your own documents: lecture notes, a sports rulebook, your society's constitution, a set of research papers.

What RAG is, in one paragraph

A large language model only knows what was in its training data, and it will confidently make things up about everything else. Retrieval-augmented generation (RAG) fixes this by first retrieving relevant passages from your own documents, then generating an answer with those passages pasted into the prompt, with an instruction to use only that context. The model becomes a reader of your documents rather than a guesser.

The pipeline has four steps:

  1. Chunk documents into passages.
  2. Index them so they can be searched.
  3. Retrieve the passages most relevant to a question.
  4. Generate an answer from those passages, with citations.

Step 1: Your documents

python
docs = [
    {"id": "syllabus-1", "text": "The final project is due on December 12. Submit a GitHub link and a two-page report."},
    {"id": "syllabus-2", "text": "Late submissions lose 10 percent per day, up to a maximum of three days."},
    {"id": "syllabus-3", "text": "Office hours are on Tuesdays from 2 pm to 4 pm in room 3.14 and on Zoom."},
    {"id": "syllabus-4", "text": "Grading: homework 40 percent, midterm 20 percent, final project 40 percent."},
    {"id": "syllabus-5", "text": "You may use AI assistants for brainstorming, but you must cite them in your report."},
]

Each passage has a stable id. That's what makes citations possible later.

Step 2: Chunking

Real documents are long, and you can't paste a 200-page PDF into every prompt. We split them into overlapping chunks:

python
def chunk(text, size=40, overlap=10):
    words = text.split()
    step = size - overlap
    return [" ".join(words[i:i + size]) for i in range(0, max(len(words) - overlap, 1), step)]

A 100-word document becomes three 40-word chunks, each overlapping the previous one by 10 words, so a sentence that falls on a boundary still appears whole in at least one chunk.

Chunk size is a real design decision:

  • Too small: chunks lose context ("it is due then" — what is?).
  • Too large: retrieval gets less precise, and you waste prompt space and money.

Splitting on paragraphs or headings usually beats fixed word counts. Our syllabus entries are already short, so each one is a chunk.

Step 3: Indexing and retrieval

We'll start with TF-IDF, a classic keyword-based method. It needs no API key, runs instantly, and is a good baseline to beat later:

python
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer

vectorizer = TfidfVectorizer(stop_words="english")
doc_matrix = vectorizer.fit_transform([d["text"] for d in docs])

def retrieve(question, k=2):
    q = vectorizer.transform([question])
    scores = (doc_matrix @ q.T).toarray().ravel()
    top = np.argsort(scores)[::-1][:k]
    return [(docs[i]["id"], round(float(scores[i]), 3)) for i in top if scores[i] > 0]

TF-IDF vectors are already length-normalised, so the matrix product gives cosine similarity between the question and every passage. Let's try it:

python
print(retrieve("When is the final project due?"))
# [('syllabus-1', 0.405), ('syllabus-4', 0.293)]

print(retrieve("How much is the midterm worth?"))
# [('syllabus-4', 0.257)]

print(retrieve("What is the capital of France?"))
# []

The right passage comes first in each case, and an unrelated question retrieves nothing. That empty result matters: it's how the system will know to say "I don't know".

Step 4: Building the prompt

Now we assemble the retrieved passages into a prompt with clear rules:

python
def build_prompt(question, k=2):
    hits = retrieve(question, k)
    by_id = {d["id"]: d["text"] for d in docs}
    context = "\n".join(f"[{doc_id}] {by_id[doc_id]}" for doc_id, _ in hits)
    return (
        "Answer the question using only the context below. "
        "Cite the source id in square brackets. If the answer is not in the context, say you don't know.\n\n"
        f"Context:\n{context}\n\nQuestion: {question}\nAnswer:"
    )

print(build_prompt("What happens if I submit late?"))
text
Answer the question using only the context below. Cite the source id in square brackets. If the answer is not in the context, say you don't know.

Context:
[syllabus-2] Late submissions lose 10 percent per day, up to a maximum of three days.
[syllabus-1] The final project is due on December 12. Submit a GitHub link and a two-page report.

Question: What happens if I submit late?
Answer:

Send this string to any LLM API (OpenAI, Anthropic, Google, or an open model running locally with Ollama), and you'll get an answer like "You lose 10% per day, for up to three days [syllabus-2]." The generation step is literally one API call; all the engineering is in what you put into the prompt.

Three rules in that prompt do the heavy lifting:

  1. "Using only the context" keeps the model grounded.
  2. "Cite the source id" makes answers checkable, and builds user trust.
  3. "Say you don't know" gives the model permission to refuse, which reduces hallucinations a lot.

Step 5: Evaluate it (what most projects skip)

How do you know your system works? Not by trying three questions and feeling good. Build a small test set of questions with the passage that should be retrieved, and measure hit rate:

python
eval_set = [
    ("When is the final project due?", "syllabus-1"),
    ("What happens if I submit late?", "syllabus-2"),
    ("When are office hours?", "syllabus-3"),
    ("How much is homework worth?", "syllabus-4"),
    ("Can I use ChatGPT?", "syllabus-5"),
]

def hit_rate(eval_set, k=2):
    hits = 0
    for question, expected in eval_set:
        if expected in [doc_id for doc_id, _ in retrieve(question, k)]:
            hits += 1
    return hits / len(eval_set)

print(hit_rate(eval_set))   # 1.0

A perfect score, but look closer, because this is where real understanding shows:

python
print(retrieve("What happens if I submit late?"))
# [('syllabus-2', 0.256), ('syllabus-1', 0.251)]

The right answer only just wins. TF-IDF matches exact words, and "submit" matches the word "Submit" in the deadline passage just as well as "late" matches "Late". And "Can I use ChatGPT?" only finds the AI policy because of the word "use". The word "ChatGPT" appears nowhere in the syllabus.

That's the core weakness of keyword search: it matches words, not meaning. Ask "Am I allowed to get help from a chatbot?" and it may fail completely.

The fix is embeddings: vectors that capture meaning, so "chatbot" lands near "AI assistant". Swap TF-IDF for an embedding model (for example sentence-transformers locally, or an embeddings API) and keep everything else the same. Retrieval becomes "embed the question, then find the nearest passage vectors by cosine similarity". When you have thousands of chunks, store the vectors in a vector database such as FAISS, Chroma, pgvector or Qdrant.

Then re-run your evaluation. That's the whole point of having one: you can prove the upgrade helped instead of hoping it did. Many production systems use hybrid search (keyword plus embeddings) because each catches what the other misses.

Turning this into a portfolio project that stands out

To make recruiters stop scrolling, go beyond the tutorial:

  • Use real documents you understand: your course notes, a public dataset of research papers, your city's council minutes.
  • Grow the eval set to 30–50 questions, including ones with no answer in the documents, and report retrieval hit rate and answer correctness.
  • Compare approaches in a results table: TF-IDF vs embeddings vs hybrid, with and without reranking.
  • Show failure cases honestly in the README. "Here's where it still breaks, and why" signals maturity.
  • Deploy it with a simple web UI (Streamlit, Gradio or a small FastAPI app) and include a short demo video.
  • Track cost and latency per query. Production teams care about both.

For deeper evaluation ideas, read RAG Evaluation: Measure the System, Not the Demo. And if you're unsure whether RAG is even the right tool, see Fine-Tuning vs RAG vs Prompt Engineering.

Frequently asked questions

What is RAG in simple terms?

Retrieval-augmented generation is a technique where an AI system first searches your own documents for relevant passages, then asks a language model to answer using only those passages. It lets the model answer questions about information it was never trained on, with citations.

Do I need a vector database to build a RAG app?

Not to start. For a few hundred chunks, an in-memory search with NumPy or scikit-learn is enough. Vector databases become useful when you have many thousands of chunks, need filtering by metadata, or need to update the index while the app is running.

Which is better for RAG, keyword search or embeddings?

Embeddings handle synonyms and paraphrases, while keyword search is better at exact terms like product codes, names and rare words. Many production systems combine both in a hybrid search and then rerank the results.

How do I stop a RAG chatbot from hallucinating?

Instruct the model to answer only from the provided context and to say it does not know otherwise, require citations, return no context when retrieval scores are low, and measure hallucinations with an evaluation set that includes unanswerable questions.

Is a RAG project good for an AI internship application?

Yes, if it goes beyond a tutorial. Use real documents, include a quantitative evaluation, compare approaches, document failure cases and deploy a working demo. That shows the engineering judgement employers look for.

#rag#llm#python#projects#students#evaluation

Sources and further reading

Practise what you just read

Solve hands-on AI and ML coding problems in your browser, with instant feedback on every test case.

Browse problems