9. 09 - Build a Small Grounded Question-Answering Pipeline Workshop#
Time: 60 minutes · Audience: beginners · Updated: November 18, 2026.
9.1. Workshop preparation#
Completed retrieval workshop, a local Ollama chat model, and the three Python files from the kit.
Download the shared workshop kit and extract it into a disposable folder. Browse all workshops. Code blocks run in your local terminal, not on this web page. Record your tool versions and use synthetic inputs.
9.2. Hands-on route#
Run the offline assertions before connecting to a model. Read local_rag.py and identify the evidence selection, prompt construction, request and result stages.
Set OLLAMA_MODEL as shown in the Ollama API workshop and run
python local_rag.py.Check the first answer against S1; a citation label alone does not prove support. Confirm the unsupported question takes the empty-evidence branch.
Add one distractor and one contradictory source. Ask the same question again and record whether the answer expresses the conflict. Do not grade a fluent answer as correct if it hides contradictory evidence.
For the optional semantic extension below, replace lexical retrieval with embeddings, keep the same document and question embedding model, and rerun the same evaluation set. Use a currently supported generation model from your provider; do not assume a historical model ID remains available.
"""Ollama native API exercise. Set OLLAMA_MODEL to a locally installed model."""
import json, os, urllib.request
from retrieval import retrieve
def answer(question):
evidence=retrieve(question)
if not evidence: return {'answer':'Insufficient evidence','sources':[]}
model=os.environ.get('OLLAMA_MODEL')
if not model: raise RuntimeError('Set OLLAMA_MODEL to an ID from ollama list')
prompt='Use only the evidence below. Cite source IDs. If unsupported, say insufficient evidence.\n'+repr(evidence)+'\nQuestion: '+question
req=urllib.request.Request('http://127.0.0.1:11434/api/chat',data=json.dumps({'model':model,'messages':[{'role':'user','content':prompt}],'stream':False}).encode(),headers={'Content-Type':'application/json'})
with urllib.request.urlopen(req,timeout=180) as r: result=json.load(r)
return {'answer':result['message']['content'],'sources':[x[0] for x in evidence]}
if __name__=='__main__':
print(json.dumps(answer('When does the library open?'),indent=2))
print(json.dumps(answer('parking fees'),indent=2))
The complete beginner path uses only Python’s standard library and Ollama. The older multi-library pipeline below is additional reading; install its optional dependencies in a separate environment and verify current APIs before using it.
9.3. Acceptance evidence#
A working local script, cited answer, unsupported-case result and a comparison table for the conflict experiment.
Create evidence.md with your environment, commands, observed outputs, failures and fixes. Label anything you did not run. Do not include secrets, screenshots of account pages, or private paths.
9.4. Troubleshooting and cleanup#
Import error: run from the kit folder with retrieval.py alongside local_rag.py. Citation wrong: compare the claim with the source text, not just the ID. Stop any demo server when finished; retain only the small fixture and evidence needed to reproduce your result.
flowchart LR
A["Prepare synthetic fixture"] --> B["Run guided task"]
B --> C["Check observed result"]
C --> D["Record evidence and limitations"]
Image Suggestion (Nanobanana Prompt): A clean technical workshop illustration titled “Build a Small Grounded Question-Answering Pipeline”, with a neutral editor window, a small synthetic fixture, and an evidence checklist. Use legible navy and teal typography on a light background, even lighting, and a visible “Concept illustration” label. Show no account identity, private paths, or simulated success presented as a screenshot.
9.5. Reference and optional extensions#
The material below provides background. Complete the guided acceptance test above first; vendor interfaces and example model IDs can change. Consult the linked official documentation for the version you use.
This hands-on tutorial walks you through building a complete RAG system from scratch using Python. You will implement every stage of the pipeline: chunking, embedding, vector storage, retrieval, reranking, and generation.
9.6. Prerequisites#
Python 3.10+
A package manager: uv (recommended) or pip
Jupyter Notebook
A free Gemini API key from Google AI Studio (or any LLM API)
9.7. Project Setup#
# Create project directory
mkdir rag-demo && cd rag-demo
# Initialize with uv (or use pip)
uv init .
# Install dependencies
uv add sentence-transformers chromadb google-genai python-dotenv jupyter
What each dependency does:
Package |
Purpose |
|---|---|
|
Load embedding models and cross-encoder reranking models |
|
Open-source vector database |
|
Google Gemini API client (free tier available) |
|
Load API keys from |
|
Interactive notebook environment |
Start Jupyter Notebook with your project dependencies:
uv run jupyter notebook
9.8. Step 1 — Chunking#
The first step is splitting your document into smaller chunks. Here we use a simple line-based strategy:
from typing import List
def split_into_chunks(doc_path: str) -> List[str]:
"""Read a document and split it into chunks (one per paragraph/line)."""
with open(doc_path, "r", encoding="utf-8") as f:
content = f.read()
# Split by double newlines (paragraphs) and filter empty strings
chunks = [chunk.strip() for chunk in content.split("\n\n") if chunk.strip()]
return chunks
# Test it
chunks = split_into_chunks("my_document.md")
for i, chunk in enumerate(chunks):
print(f"Chunk {i}: {chunk[:80]}...")
print(f"\nTotal chunks: {len(chunks)}")
9.8.1. Advanced: Recursive Character Splitting (LangChain Style)#
For production systems, use recursive splitting with overlap:
def recursive_chunk(text: str, chunk_size: int = 500, overlap: int = 50) -> List[str]:
"""Split text with overlap to preserve context across boundaries."""
chunks = []
start = 0
while start < len(text):
end = start + chunk_size
chunks.append(text[start:end])
start = end - overlap # Step back by overlap amount
return chunks
9.9. Step 2 — Embedding#
Convert each chunk into a vector using a Sentence Transformer embedding model:
from sentence_transformers import SentenceTransformer
# Load an embedding model (downloads ~90MB on first run)
embed_model = SentenceTransformer("all-MiniLM-L6-v2")
def embed_chunk(chunk: str) -> List[float]:
"""Convert a text chunk into a vector."""
vector = embed_model.encode(chunk)
return vector.tolist()
# Test: embed one chunk
test_vector = embed_chunk(chunks[0])
print(f"Vector dimensions: {len(test_vector)}")
print(f"First 5 values: {test_vector[:5]}")
# Embed ALL chunks
embeddings = [embed_chunk(chunk) for chunk in chunks]
print(f"Total embeddings: {len(embeddings)}")
9.10. Step 3 — Storing in a Vector Database (ChromaDB)#
import chromadb
# Create an in-memory vector database
client = chromadb.EphemeralClient()
# For persistent storage, use: chromadb.PersistentClient(path="./chroma_db")
# Create a collection (like a "table")
collection = client.create_collection(name="my_documents")
def store_chunks(chunks: List[str], embeddings: List[List[float]]):
"""Store all chunks and their embeddings in ChromaDB."""
ids = [str(i) for i in range(len(chunks))]
collection.add(
documents=chunks,
embeddings=embeddings,
ids=ids
)
print(f"Stored {len(chunks)} chunks in the vector database.")
# Store everything
store_chunks(chunks, embeddings)
9.11. Step 4 — Retrieval#
Search the vector database for chunks most similar to the user’s question:
def retrieve(query: str, top_k: int = 5) -> List[str]:
"""Find the top_k most relevant chunks for a given query."""
query_vector = embed_chunk(query)
results = collection.query(
query_embeddings=[query_vector],
n_results=top_k
)
return results["documents"][0]
# Test retrieval
query = "What are the three secret gadgets Doraemon used?"
retrieved = retrieve(query, top_k=5)
for i, chunk in enumerate(retrieved):
print(f"\n--- Retrieved Chunk {i+1} ---")
print(chunk[:200])
9.12. Step 5 — Reranking with Cross-Encoder#
Refine the retrieved results using a more accurate Cross-Encoder model:
from sentence_transformers import CrossEncoder
def rerank(query: str, retrieved_chunks: List[str], top_k: int = 3) -> List[str]:
"""Re-score and re-order retrieved chunks using a Cross-Encoder."""
# Load cross-encoder model (~400MB on first run)
cross_encoder = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
# Create query-chunk pairs for scoring
pairs = [[query, chunk] for chunk in retrieved_chunks]
scores = cross_encoder.predict(pairs)
# Sort by score (descending) and take top_k
scored_chunks = list(zip(retrieved_chunks, scores))
scored_chunks.sort(key=lambda x: x[1], reverse=True)
return [chunk for chunk, score in scored_chunks[:top_k]]
# Rerank the retrieved results
reranked = rerank(query, retrieved, top_k=3)
for i, chunk in enumerate(reranked):
print(f"\n--- Reranked Chunk {i+1} ---")
print(chunk[:200])
9.13. Step 6 — Generation with an LLM#
Finally, send the reranked chunks and the question to a large language model:
import os
from dotenv import load_dotenv
from google import genai
# Load API key from .env file
load_dotenv()
google_client = genai.Client()
def generate(query: str, context_chunks: List[str]) -> str:
"""Generate an answer using Gemini based on retrieved context."""
context = "\n\n".join(context_chunks)
prompt = f"""Based on the following context, answer the user's question.
If the answer cannot be found in the context, say "I don't know based on the provided documents."
Context:
{context}
Question: {query}
"""
response = google_client.models.generate_content(
model="gemini-2.0-flash",
contents=prompt
)
return response.text
# Generate the final answer!
answer = generate(query, reranked)
print("=" * 60)
print("ANSWER:")
print(answer)
9.13.1. Setting up your .env file#
Create a .env file in your project root:
GEMINI_API_KEY=your_api_key_here
9.14. Putting It All Together#
Here is the complete pipeline in one clean function:
def ask_rag(question: str, doc_path: str = "my_document.md") -> str:
"""End-to-end RAG pipeline: chunk → embed → store → retrieve → rerank → generate."""
# Phase A: Preparation (would normally be done once)
chunks = split_into_chunks(doc_path)
embeddings = [embed_chunk(c) for c in chunks]
store_chunks(chunks, embeddings)
# Phase B: Answering
retrieved = retrieve(question, top_k=10)
reranked = rerank(question, retrieved, top_k=3)
answer = generate(question, reranked)
return answer
# Usage
result = ask_rag("What are the three secret gadgets Doraemon used?")
print(result)
9.15. Complete Project Structure#
rag-demo/
├── .env # API keys (add to .gitignore!)
├── pyproject.toml # Dependencies managed by uv
├── my_document.md # Your knowledge base document
├── rag_notebook.ipynb # Jupyter notebook with all code
└── chroma_db/ # (Optional) Persistent vector storage
9.16. Read More#
Sentence Transformers Documentation — Embedding and cross-encoder model library.
ChromaDB Getting Started — Official ChromaDB quickstart guide.
Google Gemini API Quickstart — Free LLM API setup.
LangChain RAG Tutorial — Higher-level RAG framework.
LlamaIndex Starter Tutorial — Another popular RAG framework.
uv Package Manager — Fast Python dependency manager used in this tutorial.
Pinecone: Chunking Strategies — Deep dive into different text splitting approaches.
9.17. Knowledge Quiz#
Q1: Why do we use uv run jupyter notebook instead of just jupyter notebook?
Answer
Using `uv run` ensures Jupyter launches within the project's virtual environment, so it has access to all the dependencies installed via `uv add`. Running `jupyter notebook` directly would use the system Python, which likely doesn't have `sentence-transformers`, `chromadb`, etc. installed.Q2: What is the purpose of the Cross-Encoder reranking step? Why not just use the embedding similarity directly?
Answer
Embedding similarity is fast but less accurate — it independently encodes the query and each chunk, then compares their vectors. The Cross-Encoder takes the query and a chunk together as a single input, enabling much deeper semantic comparison. It's slower but significantly more precise, which is why we use it only on the small shortlist (e.g., 10 chunks) returned by retrieval.Q3: What would happen if you used a different embedding model for the query than the one used to embed the document chunks?