Basic RAG from Scratch: Chunk, Embed, Compare, Prompt

Part 2 of a RAG workshop series: a complete retrieval-augmented generation pipeline in plain Python, with no framework or vector database, and the first thing that went wrong.
GenAI
RAG
Workshop
Author
Published

September 19, 2026

RAG workshop series. I prepared these notebooks for the RAG day of AI Innovation & Product Development, a three-day workshop I ran for final-year B.Tech AI & Data Science students.

  1. When to use RAG, and when a long context window is enough
  2. Basic RAG from scratch
  3. Hybrid search: BM25, embeddings and a reranker
  4. RAG on real documents: query rewriting, chunking, metadata and Chroma
  5. Agentic RAG: corrective, adaptive and ReAct

All notebooks: github.com/Zilch123/ai-workshop

Frameworks like LangChain hide the parts of RAG that matter most when something breaks. So for the workshop, the first notebook built the whole pipeline by hand. It’s about 20 lines of real code.

flowchart LR
  A[Documents] --> B[Chunks]
  B --> C[Embeddings]
  Q[Question] --> D[Question<br/>embedding]
  C --> E[Cosine<br/>similarity]
  D --> E
  E --> F[Top chunks]
  F --> G[Prompt]
  G --> H[LLM]

The knowledge base

Four short paragraphs about AWS services: S3, SQS, Lambda and DynamoDB. Real systems have millions of documents, but the mechanism is the same, and with four you can read every score.

The question we want answered:

Which AWS service should I use to decouple applications?

The right answer is SQS.

Chunking

Embedding a 200-page PDF as a single vector gives a poor representation for any one question, so RAG systems split documents into chunks first. The simplest chunker splits on word count:

def chunk_text(text, chunk_size=250):
    words = text.split()
    chunks = []
    for i in range(0, len(words), chunk_size):
        chunks.append(" ".join(words[i:i + chunk_size]))
    return chunks

Each of our documents is shorter than 250 words, so this gives 4 chunks, one per document. In this example chunking does nothing yet. Part 4 covers better strategies.

Embeddings

An embedding model turns text into a vector of numbers. Texts with similar meanings end up close together. We used all-MiniLM-L6-v2: 384 dimensions, about 22 million parameters, around 70 MB, fast on a CPU, and no API key needed.

from sentence_transformers import SentenceTransformer

embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
chunk_embeddings = embedding_model.encode(chunks)   # shape (4, 384)

The first surprise

My notebook said “you should see the SQS document receive the highest similarity score” for the decouple question. It didn’t:

Chunk Score
Lambda 0.549
SQS 0.467
S3 0.437
DynamoDB 0.405

Lambda won. My guess is that the Lambda text shares more surface words with the question (“AWS”, “service”, “applications”) than the SQS text does. The only word that points to SQS is “decouple”. Small embedding models pick up overlap like this more than you’d hope.

This turned into a better lesson than the one I’d planned: retrieval is the part most likely to be wrong, and it fails quietly.

Prompt and answer

Because top_k=2, SQS still made it into the context, in second place. The prompt tells the model to use only that context:

def build_prompt(question, retrieved_chunks):
    context = "\n\n".join(retrieved_chunks)
    return f"""
    Answer the question using only the context below.

    CONTEXT:
    {context}

    QUESTION:
    {question}
    """

Then we send it to Llama 3.1 8B Instruct. Nscale serves it behind an OpenAI-compatible API, so the standard openai client works:

from openai import OpenAI

client = OpenAI(api_key=NSCALE_TOKEN, base_url="https://inference.api.nscale.com/v1")

response = client.chat.completions.create(
    model="meta-llama/Llama-3.1-8B-Instruct",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": prompt},
    ],
    max_tokens=500,
    temperature=0.7,
)

The answer:

You should use Amazon SQS to decouple applications. It’s a managed message queue service that allows applications to communicate asynchronously.

Correct. But only because the right chunk happened to be in the top 2 and the LLM picked it over the Lambda chunk listed above it. With top_k=1, the model would only have seen the Lambda chunk.

Five experiments to try

The point of the notebook was to change things, not just run it. These are the experiments I set for the students:

  1. Add similar documents. For example “EventBridge connects applications using events” and “SNS distributes messages to multiple subscribers”. Does SQS still rank first for “decouple”?
  2. Change the chunk size to 50, then 500. What happens to retrieval?
  3. Change top_k from 1 to 3. Does more context always give a better answer?
  4. Add irrelevant documents. Does retrieval get worse?
  5. Ask something ambiguous, like “Which service should I use for messaging?”

Each one shows a problem real RAG systems have to deal with. The LLM can only answer from the chunks it’s given, and basic vector search alone doesn’t reliably give it the right ones.

What’s next

Embeddings are good at meaning and bad at exact words. Part 3 adds keyword search (BM25), combines it with the vector scores, and adds a reranker to fix the order.

Notebook: basic_RAG.ipynb · Open in Colab