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]
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.
- When to use RAG, and when a long context window is enough
- Basic RAG from scratch
- Hybrid search: BM25, embeddings and a reranker
- RAG on real documents: query rewriting, chunking, metadata and Chroma
- 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.
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 chunksEach 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)Similarity search
Embed the question the same way, then compare it with every chunk using cosine similarity:
from sklearn.metrics.pairwise import cosine_similarity
def search(question, top_k=2):
question_embedding = embedding_model.encode([question])
scores = cosine_similarity(question_embedding, chunk_embeddings)[0]
top_indices = scores.argsort()[::-1][:top_k]
return [{"score": float(scores[i]), "text": chunks[i]} for i in top_indices]That’s semantic search. On easy questions it works well:
| Question | Top chunk | Score |
|---|---|---|
| Where should I store application files? | S3 | 0.229 |
| How can I run code without managing servers? | Lambda | 0.311 |
| Which database provides low latency access? | DynamoDB | 0.488 |
| How can microservices communicate asynchronously? | SQS | 0.338 |
Look at the last row, though. Lambda came second with 0.324, very close behind.
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:
- Add similar documents. For example “EventBridge connects applications using events” and “SNS distributes messages to multiple subscribers”. Does SQS still rank first for “decouple”?
- Change the chunk size to 50, then 500. What happens to retrieval?
- Change
top_kfrom 1 to 3. Does more context always give a better answer? - Add irrelevant documents. Does retrieval get worse?
- 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